diff --git a/cmd/gpu-mockctl/commands/cdi.go b/cmd/gpu-mockctl/commands/cdi.go new file mode 100644 index 00000000..cda2f0a0 --- /dev/null +++ b/cmd/gpu-mockctl/commands/cdi.go @@ -0,0 +1,167 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/urfave/cli/v3" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/cdi" + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/mockdriver" + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/mocktopo" +) + +// NewCDICommand creates the 'cdi' subcommand +func NewCDICommand(cfg *gpuconfig.Config) *cli.Command { + return &cli.Command{ + Name: "cdi", + Usage: "Generate mock driver tree and CDI specification", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "driver-root", + Usage: "host mock driver tree root", + Value: cfg.DriverRoot, + Destination: &cfg.DriverRoot, + }, + &cli.StringFlag{ + Name: "cdi-output", + Usage: "CDI spec output path", + Value: cfg.CDIOutput, + Destination: &cfg.CDIOutput, + }, + &cli.BoolFlag{ + Name: "with-dri", + Usage: "include DRI render node", + Destination: &cfg.WithDRI, + }, + &cli.BoolFlag{ + Name: "with-hook", + Usage: "include CDI hook references", + Destination: &cfg.WithHook, + }, + &cli.StringFlag{ + Name: "toolkit-root", + Usage: "toolkit root for hook paths", + Value: cfg.ToolkitRoot, + Destination: &cfg.ToolkitRoot, + }, + }, + Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) { + // Validate configuration + if err := cfg.ValidateCDI(); err != nil { + return ctx, err + } + return ctx, nil + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + log := getLogger(cmd) + return runCDI(cfg, log) + }, + } +} + +func runCDI(cfg *gpuconfig.Config, log logger.Interface) error { + log.Infof("Generating CDI specification for machine: %s", cfg.Machine) + log.Debugf("Driver root: %s", cfg.DriverRoot) + log.Debugf("CDI output: %s", cfg.CDIOutput) + + // Get topology + topo, err := mocktopo.New(cfg.Machine) + if err != nil { + if os.Getenv("ALLOW_UNSUPPORTED") == "true" { + log.Warningf("Using fallback mock for CDI generation") + topo = mocktopo.NewFallback(8, "NVIDIA A100-SXM4-40GB") + } else { + return fmt.Errorf("failed to create topology: %w", err) + } + } + + gpuCount := len(topo.GPUs) + log.Debugf("GPU count: %d", gpuCount) + + // Create mock driver tree + log.Debugf("Writing mock driver files to %s", cfg.DriverRoot) + files := mockdriver.DefaultFiles(cfg.DriverRoot) + if err := mockdriver.WriteAll(files); err != nil { + return fmt.Errorf("failed to write driver files: %w", err) + } + log.Infof("Mock driver tree written to %s", cfg.DriverRoot) + + // Create device nodes + if err := createDeviceNodes(cfg, gpuCount, log); err != nil { + // Log warnings but don't fail - device nodes might already exist + log.Warningf("Device node creation had errors: %v", err) + } + + // Generate CDI spec using nvidia-container-toolkit nvcdi library + log.Debugf("Generating CDI specification") + cdiOpts := cdi.Options{ + NVMLLib: topo.NVMLInterface(), + DriverRoot: cfg.DriverRoot, + DevRoot: "/host/dev", // DevRoot is already prefixed by the DaemonSet mount + NVIDIACDIHookPath: filepath.Join(cfg.ToolkitRoot, "bin/nvidia-cdi-hook"), + } + + specYAML, err := cdi.Generate(cdiOpts) + if err != nil { + return fmt.Errorf("failed to generate CDI spec: %w", err) + } + + // Validate before writing + log.Debugf("Validating CDI specification") + if err := cdi.Validate(specYAML); err != nil { + return fmt.Errorf("CDI spec validation failed: %w", err) + } + + // Write CDI spec + log.Debugf("Writing CDI spec to %s", cfg.CDIOutput) + if err := os.MkdirAll(filepath.Dir(cfg.CDIOutput), 0o755); err != nil { + return fmt.Errorf("failed to create CDI directory: %w", err) + } + + if err := os.WriteFile(cfg.CDIOutput, specYAML, 0o644); err != nil { + return fmt.Errorf("failed to write CDI spec: %w", err) + } + + log.Infof("CDI spec written to %s (generated via nvidia-container-toolkit)", + cfg.CDIOutput) + return nil +} + +func createDeviceNodes(cfg *gpuconfig.Config, gpuCount int, log logger.Interface) error { + // Create device nodes (both host /dev and under driverRoot/dev) + // Host /dev nodes for CDI runtime compatibility + log.Debugf("Creating host device nodes in /dev") + hostDevNodes := mockdriver.DeviceNodes("/dev", gpuCount, cfg.WithDRI) + if err := mockdriver.WriteAll(hostDevNodes); err != nil { + log.Warningf("Failed to create host /dev nodes: %v", err) + // Don't return error, continue with driver root nodes + } + + // Also create under driverRoot/dev for completeness + log.Debugf("Creating device nodes under %s/dev", cfg.DriverRoot) + driverDevNodes := mockdriver.DeviceNodes(cfg.DriverRoot, gpuCount, cfg.WithDRI) + if err := mockdriver.WriteAll(driverDevNodes); err != nil { + log.Warningf("Failed to create %s/dev nodes: %v", cfg.DriverRoot, err) + // Don't return error as nodes might already exist + } + + return nil +} diff --git a/cmd/gpu-mockctl/commands/cdi_test.go b/cmd/gpu-mockctl/commands/cdi_test.go new file mode 100644 index 00000000..7bf6f77c --- /dev/null +++ b/cmd/gpu-mockctl/commands/cdi_test.go @@ -0,0 +1,217 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "bytes" + "context" + "log" + "os" + "path/filepath" + "strings" + "testing" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func TestNewCDICommand(t *testing.T) { + cfg := gpuconfig.NewDefault() + cmd := NewCDICommand(cfg) + + // Test basic properties + if cmd.Name != "cdi" { + t.Errorf("Expected name=cdi, got %s", cmd.Name) + } + + // Test flags + expectedFlags := map[string]bool{ + "driver-root": false, + "cdi-output": false, + "with-dri": false, + "with-hook": false, + "toolkit-root": false, + } + + for _, f := range cmd.Flags { + name := f.Names()[0] + if _, expected := expectedFlags[name]; expected { + expectedFlags[name] = true + } + } + + for flag, found := range expectedFlags { + if !found { + t.Errorf("Expected flag %s not found", flag) + } + } +} + +func TestRunCDI(t *testing.T) { + // Note: This test may fail with "operation not permitted" errors + // when trying to create device nodes with mknod. + // This is expected behavior when not running as root. + + // Skip this test if not running as root + if os.Getuid() != 0 { + t.Skip("Skipping test that requires root privileges for mknod") + } + + // Create a temporary directory for testing + tmpDir, err := os.MkdirTemp("", "gpu-mockctl-cdi-test-*") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer func() { + if err := os.RemoveAll(tmpDir); err != nil { + t.Logf("Failed to remove temp dir: %v", err) + } + }() + + // Capture log output + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + tests := []struct { + name string + cfg *gpuconfig.Config + env map[string]string + wantErr bool + wantLog []string + }{ + { + name: "valid dgxa100", + cfg: &gpuconfig.Config{ + DriverRoot: filepath.Join(tmpDir, "driver"), + CDIOutput: filepath.Join(tmpDir, "cdi/nvidia.yaml"), + Machine: "dgxa100", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + }, + wantErr: false, + wantLog: []string{ + "Generating CDI specification for machine: dgxa100", + "Mock driver tree written to", + "CDI spec written to", + }, + }, + { + name: "with DRI nodes", + cfg: &gpuconfig.Config{ + DriverRoot: filepath.Join(tmpDir, "driver-dri"), + CDIOutput: filepath.Join(tmpDir, "cdi-dri/nvidia.yaml"), + Machine: "dgxa100", + WithDRI: true, + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + }, + wantErr: false, + wantLog: []string{ + "Generating CDI specification for machine: dgxa100", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set environment variables + for k, v := range tt.env { + if err := os.Setenv(k, v); err != nil { + t.Fatalf("Failed to set env %s: %v", k, err) + } + defer func(key string) { + if err := os.Unsetenv(key); err != nil { + t.Logf("Failed to unset env %s: %v", key, err) + } + }(k) + } + + buf.Reset() + testLogger := logger.New("test", false) + err := runCDI(tt.cfg, testLogger) + + if (err != nil) != tt.wantErr { + t.Errorf("runCDI() error = %v, wantErr %v", err, tt.wantErr) + } + + // Check log output + logOutput := buf.String() + for _, want := range tt.wantLog { + if !strings.Contains(logOutput, want) { + t.Errorf("Expected log to contain %q, got:\n%s", want, logOutput) + } + } + + // If successful, check that files were created + if !tt.wantErr && err == nil { + // Check that CDI spec was created + if _, err := os.Stat(tt.cfg.CDIOutput); os.IsNotExist(err) { + t.Errorf("Expected CDI spec at %s to exist", tt.cfg.CDIOutput) + } + } + }) + } +} + +func TestCDICommandValidation(t *testing.T) { + tests := []struct { + name string + cfg *gpuconfig.Config + wantErr bool + }{ + { + name: "valid config", + cfg: &gpuconfig.Config{ + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: "/etc/cdi/nvidia.yaml", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: false, + }, + { + name: "empty driver root", + cfg: &gpuconfig.Config{ + DriverRoot: "", + CDIOutput: "/etc/cdi/nvidia.yaml", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: true, + }, + { + name: "empty cdi output", + cfg: &gpuconfig.Config{ + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: "", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := NewCDICommand(tt.cfg) + + // The Before hook should validate + ctx := context.Background() + _, err := cmd.Before(ctx, cmd) + + if (err != nil) != tt.wantErr { + t.Errorf("Before() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/cmd/gpu-mockctl/commands/cdi_unit_test.go b/cmd/gpu-mockctl/commands/cdi_unit_test.go new file mode 100644 index 00000000..0d74fa57 --- /dev/null +++ b/cmd/gpu-mockctl/commands/cdi_unit_test.go @@ -0,0 +1,178 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "bytes" + "log" + "os" + "strings" + "testing" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func TestRunCDILogic(t *testing.T) { + // This test verifies the logic of runCDI without actually creating device nodes + // It focuses on topology handling and logging + + // Capture log output + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + tests := []struct { + name string + cfg *gpuconfig.Config + env map[string]string + wantErr bool + wantLogMsgs []string + noLogMsgs []string + }{ + { + name: "valid machine type logs correctly", + cfg: &gpuconfig.Config{ + DriverRoot: "/tmp/test-driver", + CDIOutput: "/tmp/test-cdi.yaml", + Machine: "dgxa100", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + }, + wantErr: false, + wantLogMsgs: []string{ + "Generating CDI specification for machine: dgxa100", + }, + }, + { + name: "unsupported machine with override logs warning", + cfg: &gpuconfig.Config{ + DriverRoot: "/tmp/test-driver-unsupported", + CDIOutput: "/tmp/test-cdi-unsupported.yaml", + Machine: "unsupported-test", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + }, + env: map[string]string{ + "ALLOW_UNSUPPORTED": "true", + }, + wantErr: false, + wantLogMsgs: []string{ + "Generating CDI specification for machine: unsupported-test", + "WARNING: Using fallback mock for CDI generation", + }, + }, + { + name: "unsupported machine without override returns error", + cfg: &gpuconfig.Config{ + DriverRoot: "/tmp/test-driver-error", + CDIOutput: "/tmp/test-cdi-error.yaml", + Machine: "unsupported-test", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + }, + wantErr: true, + }, + { + name: "with verbose logging shows debug messages", + cfg: &gpuconfig.Config{ + DriverRoot: "/tmp/test-driver-verbose", + CDIOutput: "/tmp/test-cdi-verbose.yaml", + Machine: "dgxa100", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Verbose: true, + }, + wantErr: false, + wantLogMsgs: []string{ + "Generating CDI specification for machine: dgxa100", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set environment variables + for k, v := range tt.env { + if err := os.Setenv(k, v); err != nil { + t.Fatalf("Failed to set env %s: %v", k, err) + } + defer func(key string) { + if err := os.Unsetenv(key); err != nil { + t.Logf("Failed to unset env %s: %v", key, err) + } + }(k) + } + + buf.Reset() + + // Note: This will fail at various steps due to permissions or missing directories + // but we can still verify the logic + testLogger := logger.New("test", tt.cfg.Verbose) + err := runCDI(tt.cfg, testLogger) + + // For non-error cases, we might get various errors (permissions, missing dirs, etc) + if !tt.wantErr && err != nil { + // Check if it's an expected error + if !strings.Contains(err.Error(), "operation not permitted") && + !strings.Contains(err.Error(), "permission denied") && + !strings.Contains(err.Error(), "no such file or directory") && + !strings.Contains(err.Error(), "failed to write driver files") && + !strings.Contains(err.Error(), "failed to generate CDI spec") { + t.Errorf("Unexpected error: %v", err) + } + } else if tt.wantErr && err == nil { + t.Error("Expected error but got none") + } + + // Check log messages + logOutput := buf.String() + for _, msg := range tt.wantLogMsgs { + if !strings.Contains(logOutput, msg) { + t.Errorf("Expected log to contain %q, got:\n%s", msg, logOutput) + } + } + + for _, msg := range tt.noLogMsgs { + if strings.Contains(logOutput, msg) { + t.Errorf("Expected log NOT to contain %q, got:\n%s", msg, logOutput) + } + } + }) + } +} + +func TestCreateDeviceNodes(t *testing.T) { + // Test the createDeviceNodes function logic + // This will log warnings but shouldn't fail + + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + cfg := &gpuconfig.Config{ + DriverRoot: "/tmp/test-driver", + WithDRI: true, + } + + testLogger := logger.New("test", false) + + // This should not return error even if device creation fails + err := createDeviceNodes(cfg, 2, testLogger) + if err != nil { + t.Errorf("createDeviceNodes should not return error, got: %v", err) + } + + // Check that warnings were logged + logOutput := buf.String() + if !strings.Contains(logOutput, "WARNING:") { + t.Error("Expected warning logs for device node creation") + } +} diff --git a/cmd/gpu-mockctl/commands/fs.go b/cmd/gpu-mockctl/commands/fs.go new file mode 100644 index 00000000..755d2498 --- /dev/null +++ b/cmd/gpu-mockctl/commands/fs.go @@ -0,0 +1,113 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "context" + "fmt" + "os" + "path/filepath" + + "github.com/urfave/cli/v3" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/mockfs" + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/mocktopo" +) + +// NewFSCommand creates the 'fs' subcommand +func NewFSCommand(cfg *gpuconfig.Config) *cli.Command { + return &cli.Command{ + Name: "fs", + Usage: "Generate mock driver filesystem under proc and dev", + Flags: []cli.Flag{ + &cli.StringFlag{ + Name: "base", + Usage: "mock driver root directory", + Value: cfg.Base, + Destination: &cfg.Base, + }, + }, + Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) { + // Validate configuration + if err := cfg.ValidateFS(); err != nil { + return ctx, err + } + return ctx, nil + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + log := getLogger(cmd) + return runFS(cfg, log) + }, + } +} + +// getLogger retrieves logger from command metadata +func getLogger(cmd *cli.Command) logger.Interface { + // Try to get from parent metadata first + var parent = cmd + for parent != nil { + if parent.Metadata != nil { + if log, ok := parent.Metadata["logger"].(logger.Interface); ok { + return log + } + } + // Check if we can access parent through Root + if parent.Root() != nil && parent.Root() != parent { + parent = parent.Root() + } else { + break + } + } + // Fallback logger + return logger.New("gpu-mockctl", false) +} + +func runFS(cfg *gpuconfig.Config, log logger.Interface) error { + log.Infof("Creating mock filesystem for machine: %s", cfg.Machine) + log.Debugf("Base directory: %s", cfg.Base) + + // Get topology + topo, err := mocktopo.New(cfg.Machine) + if err != nil { + if os.Getenv("ALLOW_UNSUPPORTED") == "true" { + log.Warningf("Unsupported machine %q, using fallback", cfg.Machine) + topo = mocktopo.NewFallback(8, "NVIDIA A100-SXM4-40GB") + } else { + return fmt.Errorf("failed to create topology: %w", err) + } + } + + // Create layout + layout := mockfs.Layout{Base: filepath.Clean(cfg.Base)} + for _, g := range topo.GPUs { + layout.GPUs = append(layout.GPUs, mockfs.GPU{ + PCI: mockfs.NormPCI(g.PCI), + UUID: g.UUID, + Model: g.Model, + }) + log.Debugf("Adding GPU: PCI=%s, UUID=%s, Model=%s", g.PCI, g.UUID, g.Model) + } + + log.Debugf("Writing %d GPU entries to %s", len(layout.GPUs), layout.Base) + + if err := layout.Write(); err != nil { + return fmt.Errorf("failed to write mock filesystem: %w", err) + } + + log.Infof("Mock filesystem written under %s (%d GPUs)", + layout.Base, len(layout.GPUs)) + return nil +} diff --git a/cmd/gpu-mockctl/commands/fs_test.go b/cmd/gpu-mockctl/commands/fs_test.go new file mode 100644 index 00000000..b321ab4d --- /dev/null +++ b/cmd/gpu-mockctl/commands/fs_test.go @@ -0,0 +1,199 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "bytes" + "context" + "log" + "os" + "path/filepath" + "strings" + "testing" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func TestNewFSCommand(t *testing.T) { + cfg := gpuconfig.NewDefault() + cmd := NewFSCommand(cfg) + + // Test basic properties + if cmd.Name != "fs" { + t.Errorf("Expected name=fs, got %s", cmd.Name) + } + + // Test flags + hasBase := false + for _, f := range cmd.Flags { + if f.Names()[0] == "base" { + hasBase = true + } + } + if !hasBase { + t.Error("Expected base flag not found") + } +} + +func TestRunFS(t *testing.T) { + // Note: This test may fail with "operation not permitted" errors + // when trying to create device nodes with mknod. + // This is expected behavior when not running as root. + // In production, this command would typically run in a privileged container. + + // Skip this test if not running as root + if os.Getuid() != 0 { + t.Skip("Skipping test that requires root privileges for mknod") + } + + // Create a temporary directory for testing + tmpDir, err := os.MkdirTemp("", "gpu-mockctl-test-*") + if err != nil { + t.Fatalf("Failed to create temp dir: %v", err) + } + defer func() { + if err := os.RemoveAll(tmpDir); err != nil { + t.Logf("Failed to remove temp dir: %v", err) + } + }() + + // Capture log output + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + tests := []struct { + name string + cfg *gpuconfig.Config + env map[string]string + wantErr bool + wantLog []string + }{ + { + name: "valid dgxa100", + cfg: &gpuconfig.Config{ + Base: filepath.Join(tmpDir, "valid"), + Machine: "dgxa100", + }, + wantErr: false, + wantLog: []string{ + "Creating mock filesystem for machine: dgxa100", + "Mock filesystem written under", + }, + }, + { + name: "unsupported machine with override", + cfg: &gpuconfig.Config{ + Base: filepath.Join(tmpDir, "unsupported"), + Machine: "unsupported", + }, + env: map[string]string{ + "ALLOW_UNSUPPORTED": "true", + }, + wantErr: false, + wantLog: []string{ + "WARNING: Unsupported machine \"unsupported\", using fallback", + "Mock filesystem written under", + }, + }, + { + name: "unsupported machine without override", + cfg: &gpuconfig.Config{ + Base: filepath.Join(tmpDir, "unsupported-no-override"), + Machine: "unsupported", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set environment variables + for k, v := range tt.env { + if err := os.Setenv(k, v); err != nil { + t.Fatalf("Failed to set env %s: %v", k, err) + } + defer func(key string) { + if err := os.Unsetenv(key); err != nil { + t.Logf("Failed to unset env %s: %v", key, err) + } + }(k) + } + + buf.Reset() + testLogger := logger.New("test", false) + err := runFS(tt.cfg, testLogger) + + if (err != nil) != tt.wantErr { + t.Errorf("runFS() error = %v, wantErr %v", err, tt.wantErr) + } + + // Check log output + logOutput := buf.String() + for _, want := range tt.wantLog { + if !strings.Contains(logOutput, want) { + t.Errorf("Expected log to contain %q, got:\n%s", want, logOutput) + } + } + + // If successful, check that files were created + if !tt.wantErr && err == nil { + // Check that the base directory exists + if _, err := os.Stat(tt.cfg.Base); os.IsNotExist(err) { + t.Errorf("Expected base directory %s to exist", tt.cfg.Base) + } + } + }) + } +} + +func TestFSCommandValidation(t *testing.T) { + tests := []struct { + name string + cfg *gpuconfig.Config + wantErr bool + }{ + { + name: "valid config", + cfg: &gpuconfig.Config{ + Base: "/tmp/test", + Machine: "dgxa100", + }, + wantErr: false, + }, + { + name: "empty base path", + cfg: &gpuconfig.Config{ + Base: "", + Machine: "dgxa100", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + cmd := NewFSCommand(tt.cfg) + + // The Before hook should validate + ctx := context.Background() + _, err := cmd.Before(ctx, cmd) + + if (err != nil) != tt.wantErr { + t.Errorf("Before() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/cmd/gpu-mockctl/commands/fs_unit_test.go b/cmd/gpu-mockctl/commands/fs_unit_test.go new file mode 100644 index 00000000..2a2326e6 --- /dev/null +++ b/cmd/gpu-mockctl/commands/fs_unit_test.go @@ -0,0 +1,134 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "bytes" + "log" + "os" + "strings" + "testing" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func TestRunFSLogic(t *testing.T) { + // This test verifies the logic of runFS without actually creating device nodes + // It focuses on topology handling and logging + + // Capture log output + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + tests := []struct { + name string + cfg *gpuconfig.Config + env map[string]string + wantErr bool + wantLogMsgs []string + }{ + { + name: "valid machine type logs correctly", + cfg: &gpuconfig.Config{ + Base: "/tmp/test", + Machine: "dgxa100", + }, + wantErr: false, + wantLogMsgs: []string{ + "Creating mock filesystem for machine: dgxa100", + }, + }, + { + name: "unsupported machine with override logs warning", + cfg: &gpuconfig.Config{ + Base: "/tmp/test-unsupported", + Machine: "unsupported-test", + }, + env: map[string]string{ + "ALLOW_UNSUPPORTED": "true", + }, + wantErr: false, + wantLogMsgs: []string{ + "Creating mock filesystem for machine: unsupported-test", + "WARNING: Unsupported machine \"unsupported-test\", using fallback", + }, + }, + { + name: "unsupported machine without override returns error", + cfg: &gpuconfig.Config{ + Base: "/tmp/test-error", + Machine: "unsupported-test", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set environment variables + for k, v := range tt.env { + if err := os.Setenv(k, v); err != nil { + t.Fatalf("Failed to set env %s: %v", k, err) + } + defer func(key string) { + if err := os.Unsetenv(key); err != nil { + t.Logf("Failed to unset env %s: %v", key, err) + } + }(k) + } + + buf.Reset() + + // Note: This will fail at the Write() step due to mknod permissions + // but we can still verify the logic up to that point + testLogger := logger.New("test", false) + err := runFS(tt.cfg, testLogger) + + // For non-error cases, we expect mknod permission error + if !tt.wantErr && err != nil { + if !strings.Contains(err.Error(), "operation not permitted") && + !strings.Contains(err.Error(), "permission denied") { + t.Errorf("Unexpected error: %v", err) + } + } else if (err != nil && !strings.Contains(err.Error(), "mknod")) != tt.wantErr { + t.Errorf("runFS() error = %v, wantErr %v", err, tt.wantErr) + } + + // Check log messages + logOutput := buf.String() + for _, msg := range tt.wantLogMsgs { + if !strings.Contains(logOutput, msg) { + t.Errorf("Expected log to contain %q, got:\n%s", msg, logOutput) + } + } + }) + } +} + +func TestGetLogger(t *testing.T) { + // Test the getLogger function + testLogger := logger.New("test", true) + + // Test with nil command + log := getLogger(nil) + if log == nil { + t.Error("Expected fallback logger for nil command") + } + + // The actual metadata retrieval is tested through integration + // with the root command in the main test suite + _ = testLogger // Use the variable to avoid linter warning +} diff --git a/cmd/gpu-mockctl/commands/version.go b/cmd/gpu-mockctl/commands/version.go new file mode 100644 index 00000000..6210cdec --- /dev/null +++ b/cmd/gpu-mockctl/commands/version.go @@ -0,0 +1,112 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "context" + "fmt" + "runtime" + + "github.com/urfave/cli/v3" +) + +// Version information set by build flags +var ( + // Version is the version string (can be set at build time) + Version = "development" + + // GitCommit is the git commit hash (can be set at build time) + GitCommit = "unknown" + + // BuildDate is the build timestamp (can be set at build time) + BuildDate = "unknown" +) + +// VersionInfo holds version information +type VersionInfo struct { + Version string `json:"version"` + GitCommit string `json:"gitCommit"` + BuildDate string `json:"buildDate"` + GoVersion string `json:"goVersion"` + Compiler string `json:"compiler"` + Platform string `json:"platform"` +} + +// NewVersionCommand creates the 'version' subcommand +func NewVersionCommand() *cli.Command { + return &cli.Command{ + Name: "version", + Usage: "Print version information", + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "short", + Aliases: []string{"s"}, + Usage: "print only the version number", + }, + &cli.BoolFlag{ + Name: "json", + Usage: "output version information in JSON format", + }, + }, + Action: func(ctx context.Context, cmd *cli.Command) error { + return showVersion(cmd) + }, + } +} + +func showVersion(cmd *cli.Command) error { + versionInfo := VersionInfo{ + Version: Version, + GitCommit: GitCommit, + BuildDate: BuildDate, + GoVersion: runtime.Version(), + Compiler: runtime.Compiler, + Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), + } + + // Short version - just print version string + if cmd.Bool("short") { + fmt.Println(versionInfo.Version) + return nil + } + + // JSON output + if cmd.Bool("json") { + return printVersionJSON(versionInfo) + } + + // Default output - human readable + fmt.Printf("gpu-mockctl version: %s\n", versionInfo.Version) + fmt.Printf(" git commit: %s\n", versionInfo.GitCommit) + fmt.Printf(" build date: %s\n", versionInfo.BuildDate) + fmt.Printf(" go version: %s\n", versionInfo.GoVersion) + fmt.Printf(" compiler: %s\n", versionInfo.Compiler) + fmt.Printf(" platform: %s\n", versionInfo.Platform) + + return nil +} + +func printVersionJSON(v VersionInfo) error { + // Simple JSON output without external dependencies + fmt.Printf(`{ + "version": %q, + "gitCommit": %q, + "buildDate": %q, + "goVersion": %q, + "compiler": %q, + "platform": %q +} +`, v.Version, v.GitCommit, v.BuildDate, v.GoVersion, v.Compiler, v.Platform) + return nil +} diff --git a/cmd/gpu-mockctl/commands/version_test.go b/cmd/gpu-mockctl/commands/version_test.go new file mode 100644 index 00000000..98ba8632 --- /dev/null +++ b/cmd/gpu-mockctl/commands/version_test.go @@ -0,0 +1,225 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package commands + +import ( + "bytes" + "context" + "fmt" + "os" + "runtime" + "strings" + "testing" + + "github.com/urfave/cli/v3" +) + +func TestNewVersionCommand(t *testing.T) { + cmd := NewVersionCommand() + + // Test basic properties + if cmd.Name != "version" { + t.Errorf("Expected name=version, got %s", cmd.Name) + } + + // Test flags + expectedFlags := map[string]bool{ + "short": false, + "json": false, + } + + for _, f := range cmd.Flags { + name := f.Names()[0] + if _, expected := expectedFlags[name]; expected { + expectedFlags[name] = true + } + } + + for flag, found := range expectedFlags { + if !found { + t.Errorf("Expected flag %s not found", flag) + } + } +} + +func TestShowVersion(t *testing.T) { + // Save original stdout + oldStdout := os.Stdout + defer func() { os.Stdout = oldStdout }() + + // Save original version values + origVersion := Version + origGitCommit := GitCommit + origBuildDate := BuildDate + defer func() { + Version = origVersion + GitCommit = origGitCommit + BuildDate = origBuildDate + }() + + // Set test values + Version = "1.2.3" + GitCommit = "abc123" + BuildDate = "2025-01-01T00:00:00Z" + + tests := []struct { + name string + flags map[string]interface{} + wantOut []string + notWant []string + }{ + { + name: "default output", + flags: map[string]interface{}{}, + wantOut: []string{ + "gpu-mockctl version: 1.2.3", + "git commit: abc123", + "build date: 2025-01-01T00:00:00Z", + fmt.Sprintf("go version: %s", runtime.Version()), + fmt.Sprintf("platform: %s/%s", runtime.GOOS, runtime.GOARCH), + }, + }, + { + name: "short output", + flags: map[string]interface{}{ + "short": true, + }, + wantOut: []string{"1.2.3"}, + notWant: []string{"git commit", "build date", "go version"}, + }, + { + name: "json output", + flags: map[string]interface{}{ + "json": true, + }, + wantOut: []string{ + `"version": "1.2.3"`, + `"gitCommit": "abc123"`, + `"buildDate": "2025-01-01T00:00:00Z"`, + `"goVersion":`, + `"platform":`, + "{", + "}", + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Create pipe to capture output + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("Failed to create pipe: %v", err) + } + os.Stdout = w + + // Create the version command + versionCmd := NewVersionCommand() + + // Build args based on flags + args := []string{"test", "version"} + for flag, value := range tt.flags { + if boolVal, ok := value.(bool); ok && boolVal { + args = append(args, "--"+flag) + } + } + + // Create app with version command + app := &cli.Command{ + Commands: []*cli.Command{versionCmd}, + } + + // Run the command + runErr := app.Run(context.Background(), args) + if runErr != nil { + t.Errorf("Run() error = %v", runErr) + } + + // Close writer and read output + if err := w.Close(); err != nil { + t.Logf("Failed to close writer: %v", err) + } + var buf bytes.Buffer + if _, err := buf.ReadFrom(r); err != nil { + t.Fatalf("Failed to read output: %v", err) + } + output := buf.String() + + // Check expected output + for _, want := range tt.wantOut { + if !strings.Contains(output, want) { + t.Errorf("Expected output to contain %q, got:\n%s", want, output) + } + } + + // Check unwanted output + for _, notWant := range tt.notWant { + if strings.Contains(output, notWant) { + t.Errorf("Expected output NOT to contain %q, got:\n%s", notWant, output) + } + } + }) + } +} + +func TestVersionInfo(t *testing.T) { + // Test that VersionInfo struct contains expected fields + v := VersionInfo{ + Version: "test", + GitCommit: "test-commit", + BuildDate: "test-date", + GoVersion: runtime.Version(), + Compiler: runtime.Compiler, + Platform: fmt.Sprintf("%s/%s", runtime.GOOS, runtime.GOARCH), + } + + if v.Version != "test" { + t.Errorf("Expected Version=test, got %s", v.Version) + } + if v.GitCommit != "test-commit" { + t.Errorf("Expected GitCommit=test-commit, got %s", v.GitCommit) + } + if v.BuildDate != "test-date" { + t.Errorf("Expected BuildDate=test-date, got %s", v.BuildDate) + } + if v.GoVersion == "" { + t.Error("Expected GoVersion to be non-empty") + } + if v.Compiler == "" { + t.Error("Expected Compiler to be non-empty") + } + if v.Platform == "" { + t.Error("Expected Platform to be non-empty") + } +} + +func TestVersionCommandIntegration(t *testing.T) { + // Test that the command can be created and has correct structure + cmd := NewVersionCommand() + + // Test running with context + ctx := context.Background() + + // Create a test app to run the command + app := &cli.Command{ + Commands: []*cli.Command{cmd}, + } + + // Test help output + err := app.Run(ctx, []string{"test", "version", "--help"}) + // Help returns an error but it's expected + // Some versions of cli don't return error for help + // This is fine, we just want to make sure it doesn't panic + _ = err // Ignore the error - we're just testing it doesn't panic +} diff --git a/cmd/gpu-mockctl/config/config.go b/cmd/gpu-mockctl/config/config.go new file mode 100644 index 00000000..6abce34b --- /dev/null +++ b/cmd/gpu-mockctl/config/config.go @@ -0,0 +1,84 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "fmt" + "os" + + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/cdi" +) + +// Config holds all configuration for gpu-mockctl +type Config struct { + // Common flags + Verbose bool + + // FS mode flags + Base string + + // CDI mode flags + DriverRoot string + CDIOutput string + Machine string + WithDRI bool + WithHook bool + ToolkitRoot string +} + +// NewDefault creates config with default values +func NewDefault() *Config { + machine := "dgxa100" + if v := os.Getenv("MACHINE_TYPE"); v != "" { + machine = v + } + + return &Config{ + Base: "/run/nvidia/driver", + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: cdi.DefaultSpecPath, + Machine: machine, + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + } +} + +// Validate checks config for errors +func (c *Config) Validate() error { + if c.Machine != "dgxa100" && os.Getenv("ALLOW_UNSUPPORTED") != "true" { + return fmt.Errorf("unsupported machine type %q (set ALLOW_UNSUPPORTED=true to override)", c.Machine) + } + return nil +} + +// ValidateFS validates configuration for FS mode +func (c *Config) ValidateFS() error { + if c.Base == "" { + return fmt.Errorf("base path cannot be empty") + } + return c.Validate() +} + +// ValidateCDI validates configuration for CDI mode +func (c *Config) ValidateCDI() error { + if c.DriverRoot == "" { + return fmt.Errorf("driver-root path cannot be empty") + } + if c.CDIOutput == "" { + return fmt.Errorf("cdi-output path cannot be empty") + } + if c.ToolkitRoot == "" { + return fmt.Errorf("toolkit-root path cannot be empty") + } + return c.Validate() +} diff --git a/cmd/gpu-mockctl/config/config_test.go b/cmd/gpu-mockctl/config/config_test.go new file mode 100644 index 00000000..52dfc128 --- /dev/null +++ b/cmd/gpu-mockctl/config/config_test.go @@ -0,0 +1,204 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package config + +import ( + "os" + "testing" + + "github.com/NVIDIA/k8s-test-infra/pkg/gpu/cdi" +) + +func TestNewDefault(t *testing.T) { + // Test default values + cfg := NewDefault() + + if cfg.Base != "/run/nvidia/driver" { + t.Errorf("Expected base=/run/nvidia/driver, got %s", cfg.Base) + } + if cfg.DriverRoot != "/var/lib/nvidia-mock/driver" { + t.Errorf("Expected driver-root=/var/lib/nvidia-mock/driver, got %s", cfg.DriverRoot) + } + if cfg.CDIOutput != cdi.DefaultSpecPath { + t.Errorf("Expected cdi-output=%s, got %s", cdi.DefaultSpecPath, cfg.CDIOutput) + } + if cfg.Machine != "dgxa100" { + t.Errorf("Expected machine=dgxa100, got %s", cfg.Machine) + } + if cfg.ToolkitRoot != "/usr/local/nvidia-container-toolkit" { + t.Errorf("Expected toolkit-root=/usr/local/nvidia-container-toolkit, got %s", cfg.ToolkitRoot) + } + + // Test environment variable override + if err := os.Setenv("MACHINE_TYPE", "test-machine"); err != nil { + t.Fatalf("Failed to set env: %v", err) + } + defer func() { + if err := os.Unsetenv("MACHINE_TYPE"); err != nil { + t.Logf("Failed to unset env: %v", err) + } + }() + + cfg2 := NewDefault() + if cfg2.Machine != "test-machine" { + t.Errorf("Expected machine from env=test-machine, got %s", cfg2.Machine) + } +} + +func TestValidate(t *testing.T) { + tests := []struct { + name string + cfg *Config + env map[string]string + wantErr bool + }{ + { + name: "valid dgxa100", + cfg: &Config{ + Machine: "dgxa100", + }, + wantErr: false, + }, + { + name: "unsupported machine without override", + cfg: &Config{ + Machine: "unsupported", + }, + wantErr: true, + }, + { + name: "unsupported machine with override", + cfg: &Config{ + Machine: "unsupported", + }, + env: map[string]string{ + "ALLOW_UNSUPPORTED": "true", + }, + wantErr: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + // Set environment variables + for k, v := range tt.env { + if err := os.Setenv(k, v); err != nil { + t.Fatalf("Failed to set env %s: %v", k, err) + } + defer func(key string) { + if err := os.Unsetenv(key); err != nil { + t.Logf("Failed to unset env %s: %v", key, err) + } + }(k) + } + + err := tt.cfg.Validate() + if (err != nil) != tt.wantErr { + t.Errorf("Validate() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateFS(t *testing.T) { + tests := []struct { + name string + cfg *Config + wantErr bool + }{ + { + name: "valid config", + cfg: &Config{ + Base: "/run/nvidia/driver", + Machine: "dgxa100", + }, + wantErr: false, + }, + { + name: "empty base path", + cfg: &Config{ + Base: "", + Machine: "dgxa100", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.ValidateFS() + if (err != nil) != tt.wantErr { + t.Errorf("ValidateFS() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func TestValidateCDI(t *testing.T) { + tests := []struct { + name string + cfg *Config + wantErr bool + }{ + { + name: "valid config", + cfg: &Config{ + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: "/etc/cdi/nvidia.yaml", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: false, + }, + { + name: "empty driver-root", + cfg: &Config{ + DriverRoot: "", + CDIOutput: "/etc/cdi/nvidia.yaml", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: true, + }, + { + name: "empty cdi-output", + cfg: &Config{ + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: "", + ToolkitRoot: "/usr/local/nvidia-container-toolkit", + Machine: "dgxa100", + }, + wantErr: true, + }, + { + name: "empty toolkit-root", + cfg: &Config{ + DriverRoot: "/var/lib/nvidia-mock/driver", + CDIOutput: "/etc/cdi/nvidia.yaml", + ToolkitRoot: "", + Machine: "dgxa100", + }, + wantErr: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.ValidateCDI() + if (err != nil) != tt.wantErr { + t.Errorf("ValidateCDI() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} diff --git a/cmd/gpu-mockctl/internal/logger/logger.go b/cmd/gpu-mockctl/internal/logger/logger.go new file mode 100644 index 00000000..f307886e --- /dev/null +++ b/cmd/gpu-mockctl/internal/logger/logger.go @@ -0,0 +1,68 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package logger + +import ( + "fmt" + "log" + "os" +) + +// Interface defines logging methods matching toolkit patterns +type Interface interface { + Infof(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Debugf(format string, args ...interface{}) +} + +// logger implements Interface +type logger struct { + prefix string + verbose bool +} + +// New creates a new logger instance +func New(prefix string, verbose bool) Interface { + return &logger{ + prefix: prefix, + verbose: verbose, + } +} + +func (l *logger) Infof(format string, args ...interface{}) { + log.Printf("[%s] INFO: %s", l.prefix, fmt.Sprintf(format, args...)) +} + +func (l *logger) Warningf(format string, args ...interface{}) { + log.Printf("[%s] WARNING: %s", l.prefix, fmt.Sprintf(format, args...)) +} + +func (l *logger) Errorf(format string, args ...interface{}) { + log.Printf("[%s] ERROR: %s", l.prefix, fmt.Sprintf(format, args...)) +} + +func (l *logger) Debugf(format string, args ...interface{}) { + if l.verbose { + log.Printf("[%s] DEBUG: %s", l.prefix, fmt.Sprintf(format, args...)) + } +} + +// Fatal logs an error and exits +func Fatal(err error) { + if err != nil { + log.Fatalf("FATAL: %v", err) + } + os.Exit(1) +} diff --git a/cmd/gpu-mockctl/internal/logger/logger_test.go b/cmd/gpu-mockctl/internal/logger/logger_test.go new file mode 100644 index 00000000..4aa53634 --- /dev/null +++ b/cmd/gpu-mockctl/internal/logger/logger_test.go @@ -0,0 +1,63 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package logger + +import ( + "bytes" + "log" + "os" + "strings" + "testing" +) + +func TestLogger(t *testing.T) { + // Capture log output + var buf bytes.Buffer + log.SetOutput(&buf) + defer log.SetOutput(os.Stderr) + + // Test non-verbose logger + l := New("test", false) + + l.Infof("info message %d", 1) + if !strings.Contains(buf.String(), "[test] INFO: info message 1") { + t.Errorf("Expected info message, got: %s", buf.String()) + } + buf.Reset() + + l.Warningf("warning message %s", "test") + if !strings.Contains(buf.String(), "[test] WARNING: warning message test") { + t.Errorf("Expected warning message, got: %s", buf.String()) + } + buf.Reset() + + l.Errorf("error message") + if !strings.Contains(buf.String(), "[test] ERROR: error message") { + t.Errorf("Expected error message, got: %s", buf.String()) + } + buf.Reset() + + // Debug should not print when verbose is false + l.Debugf("debug message") + if buf.String() != "" { + t.Errorf("Expected no debug message when verbose=false, got: %s", buf.String()) + } + + // Test verbose logger + vl := New("verbose-test", true) + vl.Debugf("debug message visible") + if !strings.Contains(buf.String(), "[verbose-test] DEBUG: debug message visible") { + t.Errorf("Expected debug message when verbose=true, got: %s", buf.String()) + } +} diff --git a/cmd/gpu-mockctl/main.go b/cmd/gpu-mockctl/main.go new file mode 100644 index 00000000..ff8abfdc --- /dev/null +++ b/cmd/gpu-mockctl/main.go @@ -0,0 +1,29 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "os" + + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func main() { + // Create and run the root command + cmd := New() + if err := cmd.Run(context.Background(), os.Args); err != nil { + logger.Fatal(err) + } +} diff --git a/cmd/gpu-mockctl/main_test.go b/cmd/gpu-mockctl/main_test.go new file mode 100644 index 00000000..0991b99e --- /dev/null +++ b/cmd/gpu-mockctl/main_test.go @@ -0,0 +1,57 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "testing" +) + +func TestMain(t *testing.T) { + // Test that the New() function is available and returns a valid command + cmd := New() + if cmd == nil { + t.Fatal("New() returned nil") + } + + // Test that the command has the expected name + if cmd.Name != "gpu-mockctl" { + t.Errorf("Expected command name 'gpu-mockctl', got %s", cmd.Name) + } + + // Test that help works + err := cmd.Run(context.Background(), []string{"gpu-mockctl", "--help"}) + if err != nil { + t.Errorf("Help command failed: %v", err) + } + + // Test that it has the expected subcommands + expectedCommands := map[string]bool{ + "fs": false, + "cdi": false, + "version": false, + } + + for _, subcmd := range cmd.Commands { + if _, ok := expectedCommands[subcmd.Name]; ok { + expectedCommands[subcmd.Name] = true + } + } + + for name, found := range expectedCommands { + if !found { + t.Errorf("Expected command %s not found", name) + } + } +} diff --git a/cmd/gpu-mockctl/root.go b/cmd/gpu-mockctl/root.go new file mode 100644 index 00000000..05229f1b --- /dev/null +++ b/cmd/gpu-mockctl/root.go @@ -0,0 +1,88 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + + "github.com/urfave/cli/v3" + + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/commands" + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +const ( + appName = "gpu-mockctl" +) + +// New creates the root command +func New() *cli.Command { + cfg := gpuconfig.NewDefault() + + return &cli.Command{ + Name: appName, + Usage: "Generate mock NVIDIA driver filesystem for testing", + Commands: []*cli.Command{ + commands.NewFSCommand(cfg), + commands.NewCDICommand(cfg), + commands.NewVersionCommand(), + }, + Flags: []cli.Flag{ + &cli.BoolFlag{ + Name: "verbose", + Aliases: []string{"v"}, + Usage: "enable verbose logging", + Destination: &cfg.Verbose, + }, + &cli.StringFlag{ + Name: "machine", + Usage: "machine type (only dgxa100 supported)", + Value: cfg.Machine, + Destination: &cfg.Machine, + }, + }, + Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) { + // Initialize logger for subcommands + log := logger.New(appName, cfg.Verbose) + + // Initialize metadata if needed + if cmd.Metadata == nil { + cmd.Metadata = make(map[string]interface{}) + } + cmd.Metadata["logger"] = log + cmd.Metadata["config"] = cfg + + return ctx, cfg.Validate() + }, + } +} + +// getLogger retrieves logger from command context +func getLogger(cmd *cli.Command) logger.Interface { + if log, ok := cmd.Metadata["logger"].(logger.Interface); ok { + return log + } + // Fallback logger + return logger.New(appName, false) +} + +// getConfig retrieves config from command context +func getConfig(cmd *cli.Command) *gpuconfig.Config { + if cfg, ok := cmd.Metadata["config"].(*gpuconfig.Config); ok { + return cfg + } + // Fallback config + return gpuconfig.NewDefault() +} diff --git a/cmd/gpu-mockctl/root_test.go b/cmd/gpu-mockctl/root_test.go new file mode 100644 index 00000000..26a9c082 --- /dev/null +++ b/cmd/gpu-mockctl/root_test.go @@ -0,0 +1,129 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package main + +import ( + "context" + "strings" + "testing" + + "github.com/urfave/cli/v3" + + gpuconfig "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/config" + "github.com/NVIDIA/k8s-test-infra/cmd/gpu-mockctl/internal/logger" +) + +func TestNew(t *testing.T) { + cmd := New() + + // Test basic properties + if cmd.Name != "gpu-mockctl" { + t.Errorf("Expected name=gpu-mockctl, got %s", cmd.Name) + } + + // Test that subcommands are registered + expectedCommands := []string{"fs", "cdi", "version"} + if len(cmd.Commands) != len(expectedCommands) { + t.Errorf("Expected %d commands, got %d", len(expectedCommands), len(cmd.Commands)) + } + + for _, expected := range expectedCommands { + found := false + for _, c := range cmd.Commands { + if c.Name == expected { + found = true + break + } + } + if !found { + t.Errorf("Expected command %s not found", expected) + } + } + + // Test flags + hasVerbose := false + hasMachine := false + for _, f := range cmd.Flags { + switch f.Names()[0] { + case "verbose": + hasVerbose = true + case "machine": + hasMachine = true + } + } + if !hasVerbose { + t.Error("Expected verbose flag not found") + } + if !hasMachine { + t.Error("Expected machine flag not found") + } +} + +func TestGetLogger(t *testing.T) { + // Test with logger in metadata + cmd := &cli.Command{ + Metadata: map[string]interface{}{ + "logger": logger.New("test", true), + }, + } + log := getLogger(cmd) + if log == nil { + t.Error("Expected logger, got nil") + } + + // Test fallback + cmdEmpty := &cli.Command{} + logFallback := getLogger(cmdEmpty) + if logFallback == nil { + t.Error("Expected fallback logger, got nil") + } +} + +func TestGetConfig(t *testing.T) { + // Test with config in metadata + testCfg := gpuconfig.NewDefault() + testCfg.Machine = "test-machine" + cmd := &cli.Command{ + Metadata: map[string]interface{}{ + "config": testCfg, + }, + } + retrievedCfg := getConfig(cmd) + if retrievedCfg.Machine != "test-machine" { + t.Errorf("Expected machine=test-machine, got %s", retrievedCfg.Machine) + } + + // Test fallback + cmdEmpty := &cli.Command{} + cfgFallback := getConfig(cmdEmpty) + if cfgFallback == nil { + t.Error("Expected fallback config, got nil") + } +} + +func TestRootCommandValidation(t *testing.T) { + // Test that validation runs in Before hook + cmd := New() + + // Simulate running with invalid machine type + args := []string{"gpu-mockctl", "--machine", "invalid"} + err := cmd.Run(context.Background(), args) + + if err == nil { + t.Error("Expected validation error for invalid machine type") + } + if !strings.Contains(err.Error(), "unsupported machine type") { + t.Errorf("Expected unsupported machine type error, got: %v", err) + } +} diff --git a/deployments/devel/gpu-mock/00-namespace.yaml b/deployments/devel/gpu-mock/00-namespace.yaml new file mode 100644 index 00000000..fd6c5195 --- /dev/null +++ b/deployments/devel/gpu-mock/00-namespace.yaml @@ -0,0 +1,18 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apiVersion: v1 +kind: Namespace +metadata: + name: gpu-mock + diff --git a/deployments/devel/gpu-mock/10-configmap-verify-script.yaml b/deployments/devel/gpu-mock/10-configmap-verify-script.yaml new file mode 100644 index 00000000..ea5a2129 --- /dev/null +++ b/deployments/devel/gpu-mock/10-configmap-verify-script.yaml @@ -0,0 +1,41 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apiVersion: v1 +kind: ConfigMap +metadata: + name: gpu-mock-scripts + namespace: gpu-mock +immutable: true +data: + verify_gpu_mock.sh: | + #!/bin/sh + set -euo pipefail + BASE="${1:-/run/nvidia/driver}" + DEV="$BASE/dev" + PROC="$BASE/proc/driver/nvidia" + require() { test -e "$1" || { echo "MISSING: $1" >&2; exit 1; }; } + require_char() { [ -c "$1" ] || { echo "NOT-CHAR: $1" >&2; exit 1; }; } + COUNT=$(find "$PROC/gpus" -maxdepth 2 -type f -name information | wc -l | tr -d ' ') + [ "$COUNT" -gt 0 ] || { echo "No GPUs found in proc mock" >&2; exit 1; } + for i in $(seq 0 $((COUNT-1))); do require_char "$DEV/nvidia$i"; done + require_char "$DEV/nvidiactl" + require_char "$DEV/nvidia-uvm" + require_char "$DEV/nvidia-uvm-tools" + require "$PROC/version" && grep -q "NVRM version:" "$PROC/version" + for f in $(find "$PROC/gpus" -maxdepth 2 -type f -name information | sort); do + grep -q "Model:" "$f" && grep -q "GPU UUID:" "$f" && grep -q "Bus Location:" "$f" || { echo "Bad info in $f" >&2; exit 1; } + done + (cd "$BASE" && find . -maxdepth 4 -print | sort) + echo "ALL CHECKS PASSED" + diff --git a/deployments/devel/gpu-mock/20-job-gpu-mock-verify.yaml b/deployments/devel/gpu-mock/20-job-gpu-mock-verify.yaml new file mode 100644 index 00000000..7aaa1d1a --- /dev/null +++ b/deployments/devel/gpu-mock/20-job-gpu-mock-verify.yaml @@ -0,0 +1,58 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apiVersion: batch/v1 +kind: Job +metadata: + name: gpu-mock-verify + namespace: gpu-mock +spec: + backoffLimit: 0 + template: + metadata: + labels: + app: gpu-mock-verify + spec: + restartPolicy: Never + volumes: + - name: mock-driver + emptyDir: {} + - name: scripts + configMap: + name: gpu-mock-scripts + defaultMode: 0755 + initContainers: + - name: setup-mock + image: local/gpu-mockctl:dev + env: + - name: MACHINE_TYPE + value: "dgxa100" + securityContext: + privileged: true + runAsUser: 0 + volumeMounts: + - name: mock-driver + mountPath: /run/nvidia/driver + command: ["/usr/local/bin/gpu-mockctl","-mode","fs","-base","/run/nvidia/driver"] + containers: + - name: verify + image: alpine:3.20 + securityContext: + runAsUser: 0 + volumeMounts: + - name: mock-driver + mountPath: /run/nvidia/driver + - name: scripts + mountPath: /opt/mock/bin + command: ["/bin/sh","-c","/opt/mock/bin/verify_gpu_mock.sh /run/nvidia/driver"] + diff --git a/deployments/devel/gpu-mock/30-daemonset-cdi-mock.yaml b/deployments/devel/gpu-mock/30-daemonset-cdi-mock.yaml new file mode 100644 index 00000000..26358d9a --- /dev/null +++ b/deployments/devel/gpu-mock/30-daemonset-cdi-mock.yaml @@ -0,0 +1,72 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apiVersion: apps/v1 +kind: DaemonSet +metadata: + name: nvidia-cdi-mock + namespace: gpu-mock +spec: + selector: + matchLabels: + app: nvidia-cdi-mock + template: + metadata: + labels: + app: nvidia-cdi-mock + spec: + hostPID: true + tolerations: + - operator: Exists + restartPolicy: Always + volumes: + - name: host-cdi + hostPath: + path: /etc/cdi + type: DirectoryOrCreate + - name: host-driver + hostPath: + path: /var/lib/nvidia-mock/driver + type: DirectoryOrCreate + - name: host-dev + hostPath: + path: /dev + initContainers: + - name: setup + image: local/gpu-mockctl:dev + env: + - name: __NVCT_TESTING_DEVICES_ARE_FILES + value: "true" + securityContext: + privileged: true + runAsUser: 0 + volumeMounts: + - name: host-cdi + mountPath: /host/etc/cdi + - name: host-driver + mountPath: /host/var/lib/nvidia-mock/driver + - name: host-dev + mountPath: /host/dev + command: ["/usr/local/bin/gpu-mockctl"] + args: + - "-mode" + - "cdi" + - "-driver-root" + - "/host/var/lib/nvidia-mock/driver" + - "-cdi-output" + - "/host/etc/cdi/nvidia.yaml" + containers: + - name: hold + image: debian:bookworm-slim + command: ["/bin/sh", "-c", "sleep infinity"] + diff --git a/deployments/devel/gpu-mock/40-job-cdi-smoke.yaml b/deployments/devel/gpu-mock/40-job-cdi-smoke.yaml new file mode 100644 index 00000000..f6bcd044 --- /dev/null +++ b/deployments/devel/gpu-mock/40-job-cdi-smoke.yaml @@ -0,0 +1,75 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +apiVersion: batch/v1 +kind: Job +metadata: + name: cdi-smoke + namespace: gpu-mock +spec: + backoffLimit: 0 + template: + metadata: + labels: + app: cdi-smoke + spec: + restartPolicy: Never + volumes: + - name: host-cdi + hostPath: + path: /etc/cdi + - name: host-driver + hostPath: + path: /var/lib/nvidia-mock/driver + containers: + - name: check + image: debian:bookworm-slim + volumeMounts: + - name: host-cdi + mountPath: /host/etc/cdi + readOnly: true + - name: host-driver + mountPath: /host/var/lib/nvidia-mock/driver + readOnly: true + command: ["/bin/sh", "-c"] + args: + - | + set -ex + + # Check CDI spec exists + test -s /host/etc/cdi/nvidia.yaml + echo "✓ CDI spec exists" + + # Check mock driver libraries + test -f /host/var/lib/nvidia-mock/driver/lib64/libcuda.so.1 + test -L /host/var/lib/nvidia-mock/driver/lib64/libcuda.so + test -f /host/var/lib/nvidia-mock/driver/lib64/libnvidia-ml.so.1 + test -L /host/var/lib/nvidia-mock/driver/lib64/libnvidia-ml.so + echo "✓ Mock driver libraries present" + + # Check binaries + test -x /host/var/lib/nvidia-mock/driver/bin/nvidia-smi + echo "✓ Mock binaries present" + + # Show tree + echo "Mock driver tree:" + find /host/var/lib/nvidia-mock/driver -type f -o -type l | sort | head -20 + + # Show CDI spec snippet + echo "" + echo "CDI spec (first 30 lines):" + head -30 /host/etc/cdi/nvidia.yaml + + echo "" + echo "✓ CDI smoke test PASSED" + diff --git a/deployments/devel/gpu-mock/Dockerfile b/deployments/devel/gpu-mock/Dockerfile new file mode 100644 index 00000000..dbf29523 --- /dev/null +++ b/deployments/devel/gpu-mock/Dockerfile @@ -0,0 +1,29 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# builder +FROM golang:1.25 AS builder +WORKDIR /src +COPY . . +RUN --mount=type=cache,target=/go/pkg/mod \ + CGO_ENABLED=1 go build -trimpath -ldflags='-s -w' \ + -o /out/gpu-mockctl ./cmd/gpu-mockctl + +# runtime +FROM debian:bookworm-slim +RUN apt-get update && apt-get install -y --no-install-recommends \ + bash coreutils util-linux && \ + rm -rf /var/lib/apt/lists/* +COPY --from=builder /out/gpu-mockctl /usr/local/bin/gpu-mockctl +ENTRYPOINT ["/usr/local/bin/gpu-mockctl"] + diff --git a/deployments/devel/gpu-mock/Makefile b/deployments/devel/gpu-mock/Makefile new file mode 100644 index 00000000..008bb333 --- /dev/null +++ b/deployments/devel/gpu-mock/Makefile @@ -0,0 +1,77 @@ +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +SHELL := /bin/bash +APP := gpu-mockctl +IMAGE ?= local/$(APP):dev +CLUSTER ?= gpu-mock +KIND_IMAGE ?= kindest/node:v1.30.0 +KUBECTL ?= kubectl +REPO_ROOT := $(shell cd ../../.. && pwd) + +.PHONY: all kind-up image load apply wait logs clean re vendor +.PHONY: apply-cdi wait-cdi logs-cdi smoke all-cdi + +all: kind-up image load apply wait logs + +# Step 2 targets +all-cdi: all apply-cdi wait-cdi logs-cdi smoke + +vendor: + cd $(REPO_ROOT) && go mod tidy && go mod vendor + +image: vendor + cd $(REPO_ROOT) && docker build -t $(IMAGE) -f deployments/devel/gpu-mock/Dockerfile . + +load: + kind load docker-image $(IMAGE) --name $(CLUSTER) + +kind-up: + kind create cluster --name $(CLUSTER) --image $(KIND_IMAGE) || true + +apply: + $(KUBECTL) apply -f 00-namespace.yaml + $(KUBECTL) -n gpu-mock apply -f 10-configmap-verify-script.yaml + $(KUBECTL) -n gpu-mock apply -f 20-job-gpu-mock-verify.yaml + +wait: + $(KUBECTL) -n gpu-mock wait --for=condition=complete job/gpu-mock-verify --timeout=180s + +logs: + @pod=$$($(KUBECTL) -n gpu-mock get pods -l job-name=gpu-mock-verify -o jsonpath='{.items[0].metadata.name}'); \ + $(KUBECTL) -n gpu-mock logs $$pod + +apply-cdi: + $(KUBECTL) -n gpu-mock apply -f 30-daemonset-cdi-mock.yaml + +wait-cdi: + $(KUBECTL) -n gpu-mock rollout status ds/nvidia-cdi-mock --timeout=120s + +logs-cdi: + @echo "=== DaemonSet logs ===" + $(KUBECTL) -n gpu-mock logs -l app=nvidia-cdi-mock --tail=-1 --all-containers=true --prefix=true || true + +smoke: + $(KUBECTL) -n gpu-mock delete job/cdi-smoke --ignore-not-found=true + $(KUBECTL) -n gpu-mock apply -f 40-job-cdi-smoke.yaml + $(KUBECTL) -n gpu-mock wait --for=condition=complete job/cdi-smoke --timeout=120s + @echo "" + @echo "=== CDI Smoke Test Logs ===" + @pod=$$($(KUBECTL) -n gpu-mock get pods -l app=cdi-smoke -o jsonpath='{.items[0].metadata.name}'); \ + $(KUBECTL) -n gpu-mock logs $$pod + +clean: + kind delete cluster --name $(CLUSTER) || true + +re: clean all + diff --git a/deployments/devel/gpu-mock/README.md b/deployments/devel/gpu-mock/README.md new file mode 100644 index 00000000..716c6424 --- /dev/null +++ b/deployments/devel/gpu-mock/README.md @@ -0,0 +1,646 @@ +# GPU Mock on kind + +Complete mock NVIDIA driver and toolkit infrastructure for testing +GPU-aware Kubernetes applications on local kind clusters without +physical GPUs. + +## Overview + +This deployment creates a local kind cluster with a comprehensive mock +NVIDIA GPU environment that mimics both the driver filesystem and the +NVIDIA Container Toolkit (CDI) configuration typically found on +GPU-enabled nodes. It enables end-to-end testing of GPU-aware +Kubernetes workloads without requiring actual GPU hardware. + +The mock includes: + +**Step 1: Mock Driver Filesystem** +- Character device nodes (`/dev/nvidia*`, `/dev/nvidiactl`, + `/dev/nvidia-uvm*`) +- NVIDIA proc filesystem structure + (`/proc/driver/nvidia/gpus/{PCI}/information`) +- GPU topology and device information (8× A100 GPUs via `go-nvml` + dgxa100 mock) + +**Step 2: Mock Driver + Toolkit + CDI** +- Mock NVIDIA driver libraries (versioned, empty files following + nvidia-container-toolkit test conventions) +- Mock NVIDIA toolkit binaries (`nvidia-smi`, `nvidia-debugdump`, etc.) +- Production-grade CDI specification generated via + `nvidia-container-toolkit/pkg/nvcdi` +- DaemonSet deployment for node-level mock setup +- Full integration with NVIDIA's production CDI generation APIs + +## Quick Start + +### Prerequisites + +- [kind](https://kind.sigs.k8s.io/) v0.20.0+ +- [kubectl](https://kubernetes.io/docs/tasks/tools/) v1.28.0+ +- [Docker](https://www.docker.com/) 20.10+ +- [Go](https://golang.org/) 1.25+ + +### Run End-to-End (Step 1 Only) + +From the repository root: + +```bash +make -C deployments/devel/gpu-mock all +``` + +This command will: + +1. Create a kind cluster named `gpu-mock` +2. Build the `local/gpu-mockctl:dev` container image +3. Load the image into the kind cluster +4. Deploy the namespace, ConfigMap, and mock filesystem Job +5. Wait for the Job to complete (max 180s) +6. Display the Job logs + +**Expected output (last line):** + +``` +ALL CHECKS PASSED +``` + +### Run End-to-End (Steps 1 + 2 with CDI) + +For the complete mock environment including CDI: + +```bash +make -C deployments/devel/gpu-mock all-cdi +``` + +This will execute all Step 1 targets plus: +- Deploy the CDI mock DaemonSet +- Wait for DaemonSet rollout +- Run the CDI smoke test Job +- Display comprehensive results + +**Expected output:** +``` +ALL CHECKS PASSED +✓ CDI spec exists +✓ Mock driver libraries present +✓ Mock binaries present +✓ CDI smoke test PASSED +``` + +### Step-by-Step Execution + +If you prefer to run each step manually: + +```bash +cd deployments/devel/gpu-mock + +make kind-up # Create the kind cluster +make image # Build the container image +make load # Load the image into kind +make apply # Deploy Kubernetes resources +make wait # Wait for Job completion +make logs # View Job logs +``` + +### Cleanup + +Delete the kind cluster and all resources: + +```bash +make -C deployments/devel/gpu-mock clean +``` + +Or from the `deployments/devel/gpu-mock/` directory: + +```bash +make clean +``` + +## Step 2: Mock NVIDIA Userspace + CDI + +**Step 2** extends the base mock filesystem (Step 1) to include: + +1. **Mock driver/toolkit tree**: Placeholder NVIDIA libraries and + binaries under `/var/lib/nvidia-mock/driver` +2. **CDI specification**: Valid CDI spec at `/etc/cdi/nvidia.yaml` for + CDI-enabled container runtimes +3. **DaemonSet deployment**: Runs `gpu-mockctl` on every node to create + mock files and CDI spec +4. **Smoke test**: Validates the presence of mock driver files and CDI + spec + +### Quick Start (Step 2) + +Run the full end-to-end test including CDI: + +```bash +make -C deployments/devel/gpu-mock all-cdi +``` + +This will: +1. Execute all Step 1 targets (cluster, image, fs mock, verify) +2. Deploy the CDI mock DaemonSet +3. Wait for DaemonSet rollout +4. Run the CDI smoke test Job +5. Display results + +**Expected output:** +``` +✓ CDI spec exists +✓ Mock driver libraries present +✓ Mock binaries present +✓ CDI smoke test PASSED +``` + +### Individual Step 2 Targets + +```bash +make -C deployments/devel/gpu-mock apply-cdi # Deploy DaemonSet +make -C deployments/devel/gpu-mock wait-cdi # Wait for rollout +make -C deployments/devel/gpu-mock logs-cdi # View DaemonSet logs +make -C deployments/devel/gpu-mock smoke # Run smoke test +``` + +### Step 2 CLI Flags + +The `gpu-mockctl` tool now supports CDI mode: + +```bash +gpu-mockctl [flags] + +Flags: + --mode string Operation mode: fs, cdi, or all (default: "all") + --base string Mock driver root for fs mode (default: "/run/nvidia/driver") + --driver-root string Host mock driver tree root (default: "/var/lib/nvidia-mock/driver") + --cdi-output string CDI spec output path (default: "/etc/cdi/nvidia.yaml") + --machine string Machine type (default: "dgxa100") + --with-dri Include DRI render node (/dev/dri/renderD128) + --with-hook Include CDI hook references (requires toolkit) + --toolkit-root string Toolkit root for hook paths (default: "/usr/local/nvidia-container-toolkit") +``` + +**Mode behavior:** +- **`fs`**: Create Step 1 mock filesystem only (proc/dev under `--base`) +- **`cdi`**: Create mock driver tree + CDI spec (host paths) +- **`all`**: Run both fs and cdi modes (default) + +### Mock Driver Tree Structure + +Located at `/var/lib/nvidia-mock/driver` on each node: + +``` +/var/lib/nvidia-mock/driver/ +├── lib64/ +│ ├── libcuda.so.550.54.15 # Empty file (0 bytes) +│ ├── libcuda.so.1 -> libcuda.so.550.54.15 +│ ├── libcuda.so -> libcuda.so.1 +│ ├── libnvidia-ml.so.550.54.15 # Empty file (0 bytes) +│ ├── libnvidia-ml.so.1 -> libnvidia-ml.so.550.54.15 +│ ├── libnvidia-ml.so -> libnvidia-ml.so.1 +│ ├── libnvidia-encode.so.550.54.15 # Empty file (0 bytes) +│ ├── libnvidia-encode.so.1 -> libnvidia-encode.so.550.54.15 +│ ├── libnvidia-encode.so -> libnvidia-encode.so.1 +│ ├── libnvcuvid.so.550.54.15 # Empty file (0 bytes) +│ ├── libnvcuvid.so.1 -> libnvcuvid.so.550.54.15 +│ ├── libnvcuvid.so -> libnvcuvid.so.1 +│ ├── libnvidia-ptxjitcompiler.so.550.54.15 # Empty file (0 bytes) +│ ├── libnvidia-ptxjitcompiler.so.1 -> libnvidia-ptxjitcompiler.so.550.54.15 +│ ├── libnvidia-ptxjitcompiler.so -> libnvidia-ptxjitcompiler.so.1 +│ ├── libnvidia-fatbinaryloader.so.550.54.15 # Empty file (0 bytes) +│ ├── libnvidia-fatbinaryloader.so.1 -> libnvidia-fatbinaryloader.so.550.54.15 +│ └── libnvidia-fatbinaryloader.so -> libnvidia-fatbinaryloader.so.1 +├── bin/ +│ ├── nvidia-smi # Shell stub script +│ ├── nvidia-debugdump # Shell stub script +│ ├── nvidia-persistenced # Shell stub script +│ └── nvidia-modprobe # Shell stub script +├── dev/ # Mock device nodes (regular files) +│ ├── nvidia0..nvidia7 # 8 GPU devices +│ ├── nvidiactl +│ ├── nvidia-uvm +│ └── nvidia-uvm-tools +└── etc/ + └── nvidia-container-runtime/ + └── config.toml # Placeholder config +``` + +**Note**: Libraries are **empty files** (following the nvidia-container-toolkit's +own testdata convention for testing). Binaries are shell script stubs. They +do **not** contain real NVML or CUDA functionality. Step 3 will introduce +NVML mocking. + +**CDI Generation**: The CDI spec is generated using **nvidia-container-toolkit's +production `nvcdi` library** with: +- `go-nvml` dgxa100 mock for GPU topology +- `__NVCT_TESTING_DEVICES_ARE_FILES=true` environment variable (from + nvidia-container-toolkit's own testing infrastructure) +- Empty files with proper version naming (`libcuda.so.550.54.15`) + +This ensures our mock CDI specs match real-world NVIDIA deployments. + +### CDI Specification + +Generated at `/etc/cdi/nvidia.yaml`: + +```yaml +cdiVersion: 1.0.0 +kind: nvidia.com/gpu +containerEdits: + env: + - NVIDIA_VISIBLE_DEVICES=void + hooks: + - args: + - nvidia-cdi-hook + - create-symlinks + - --link + - libcuda.so.1::/lib64/libcuda.so + hookName: createContainer + path: /usr/local/nvidia-container-toolkit/bin/nvidia-cdi-hook + - args: + - nvidia-cdi-hook + - enable-cuda-compat + - --host-driver-version=550.54.15 + hookName: createContainer + path: /usr/local/nvidia-container-toolkit/bin/nvidia-cdi-hook + - args: + - nvidia-cdi-hook + - update-ldcache + - --folder + - /lib64 + hookName: createContainer + path: /usr/local/nvidia-container-toolkit/bin/nvidia-cdi-hook + mounts: + - containerPath: /bin/nvidia-smi + hostPath: /host/var/lib/nvidia-mock/driver/bin/nvidia-smi + options: [ro, nosuid, nodev, bind] + - containerPath: /lib64/libcuda.so.550.54.15 + hostPath: /host/var/lib/nvidia-mock/driver/lib64/libcuda.so.550.54.15 + options: [ro, nosuid, nodev, bind] + - containerPath: /lib64/libnvidia-ml.so.550.54.15 + hostPath: /host/var/lib/nvidia-mock/driver/lib64/libnvidia-ml.so.550.54.15 + options: [ro, nosuid, nodev, bind] + # ... (other library mounts) +devices: +- name: "0" + containerEdits: {} +- name: "1" + containerEdits: {} +# ... (devices 2-7) +``` + +**Note**: The actual CDI spec is generated by +`nvidia-container-toolkit/pkg/nvcdi` and includes proper device mounts, +library paths, and hook configurations for production compatibility. + +### Enabling CDI in containerd (Optional) + +To test CDI device injection with a real CDI-aware runtime, enable CDI +in containerd inside the kind node: + +1. Access the kind node: + ```bash + docker exec -it gpu-mock-control-plane /bin/bash + ``` + +2. Edit `/etc/containerd/config.toml`: + ```toml + [plugins."io.containerd.grpc.v1.cri"] + enable_cdi = true + cdi_spec_dirs = ["/etc/cdi"] + ``` + +3. Restart containerd: + ```bash + systemctl restart containerd + ``` + +4. Test with a pod using CDI device annotation: + ```yaml + annotations: + cdi.k8s.io/nvidia: nvidia.com/gpu=all + ``` + +**Note**: This is **not** required for Step 2 acceptance; the smoke test +validates file presence and CDI spec syntax only. + +## Technical Details: nvidia-container-toolkit Integration + +### How We Use Production nvcdi APIs + +Step 2 uses the **same CDI generation library** that NVIDIA uses in +production (`github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi`): + +```go +// Create mock NVML interface (dgxa100 with MIG stub overrides) +mockNVML := newNVMLWrapper() + +// Pass it to nvidia-container-toolkit's nvcdi +lib, err := nvcdi.New( + nvcdi.WithMode(nvcdi.ModeNvml), + nvcdi.WithNvmlLib(mockNVML), // Our mock! + nvcdi.WithDriverRoot(driverRoot), + nvcdi.WithDevRoot(devRoot), +) + +spec, err := lib.GetSpec() +``` + +### Testing Environment Variable + +We use `__NVCT_TESTING_DEVICES_ARE_FILES=true` - the **same flag +nvidia-container-toolkit uses in its own test suite** (see +[testdata/](https://github.com/NVIDIA/nvidia-container-toolkit/tree/main/testdata)). + +This flag tells nvcdi to: +- Accept regular files as device nodes (instead of character devices) +- Skip ELF binary validation +- Work with empty placeholder files + +### File Structure Compatibility + +Our mock follows nvidia-container-toolkit's testdata conventions: +- **Empty files** (0 bytes) for `.so` libraries +- **Versioned naming**: `libcuda.so.550.54.15` (matching dgxa100 mock version) +- **Proper symlink chains**: `libcuda.so` → `libcuda.so.1` → `libcuda.so.550.54.15` +- **Device nodes as files** when `__NVCT_TESTING_DEVICES_ARE_FILES=true` + +### NVML Mock Wrapper + +We extend `go-nvml/pkg/nvml/mock/dgxa100` with MIG method stubs (see +`pkg/gpu/mocktopo/nvmlwrapper.go`): + +```go +// nvcdi requires these methods for device discovery +dev.GetMaxMigDeviceCountFunc = func() (int, nvml.Return) { + return 0, nvml.SUCCESS // No MIG support in mock +} +dev.GetMigModeFunc = func() (int, int, nvml.Return) { + return 0, 0, nvml.ERROR_NOT_SUPPORTED +} +``` + +This approach ensures **Step 2 CDI specs are production-ready** and will work +seamlessly with real NVIDIA Container Toolkit deployments. + +## Architecture + +### Components + +- **`gpu-mockctl`**: CLI tool that generates the mock NVIDIA driver + filesystem structure using topology data from + [go-nvml](https://github.com/NVIDIA/go-nvml) mock providers. + +- **Kubernetes Job**: Two-container Job that creates and verifies the + mock filesystem: + - **initContainer (`setup-mock`)**: Runs `gpu-mockctl` with + privileged permissions to create character device nodes via + `mknod(2)`. + - **container (`verify`)**: Executes a shell script to validate the + filesystem structure and device nodes. + +- **Shared Volume**: An `emptyDir` volume mounted at + `/run/nvidia/driver` allows the initContainer to write and the verify + container to read the mock filesystem. + +### Mock Filesystem Structure + +``` +/run/nvidia/driver/ +├── dev/ +│ ├── nvidia0 +│ ├── nvidia1 +│ ├── nvidia2 +│ ├── nvidia3 +│ ├── nvidia4 +│ ├── nvidia5 +│ ├── nvidia6 +│ ├── nvidia7 +│ ├── nvidiactl +│ ├── nvidia-uvm +│ └── nvidia-uvm-tools +└── proc/ + └── driver/ + └── nvidia/ + ├── version + └── gpus/ + ├── 0000:00:00.0/ + │ └── information + ├── 0000:01:00.0/ + │ └── information + ├── 0000:02:00.0/ + │ └── information + ├── 0000:03:00.0/ + │ └── information + ├── 0000:04:00.0/ + │ └── information + ├── 0000:05:00.0/ + │ └── information + ├── 0000:06:00.0/ + │ └── information + └── 0000:07:00.0/ + └── information +``` + +### Machine Types + +Currently supported machine type: + +- **`dgxa100`**: DGX A100 with 8× NVIDIA A100-SXM4-40GB GPUs + +Future machine types (when added to go-nvml): + +- `dgxh100`: DGX H100 with 8× H100-SXM5-80GB +- `dgxh200`: DGX H200 with 8× H200-HBM3e +- `dgxb200`: DGX B200 with 8× B200 + +## Configuration + +### Environment Variables + +The `gpu-mockctl` tool supports the following environment variables: + +- **`MACHINE_TYPE`**: Machine type for topology (default: `dgxa100`) +- **`ALLOW_UNSUPPORTED`**: If `true`, use fallback synthetic topology + when the specified machine type is unsupported (default: unset) + +### CLI Flags (Complete Reference) + +```bash +gpu-mockctl [flags] + +Flags: + --mode string Operation mode: fs, cdi, or all (default: "all") + --base string Mock driver root for fs mode (default: "/run/nvidia/driver") + --driver-root string Host mock driver tree root for cdi mode (default: "/var/lib/nvidia-mock/driver") + --cdi-output string CDI spec output path (default: "/etc/cdi/nvidia.yaml") + --machine string Machine type (default: "dgxa100") + --with-dri Include DRI render node (/dev/dri/renderD128) (default: false) + --with-hook Include CDI hook references (default: false) + --toolkit-root string Toolkit root for hook paths (default: "/usr/local/nvidia-container-toolkit") + --help, -h Show help +``` + +**Mode behavior:** +- **`fs`**: Create Step 1 mock filesystem only (proc/dev under `--base`) +- **`cdi`**: Create mock driver tree + CDI spec (host paths) +- **`all`**: Run both fs and cdi modes (default) + +## Development + +### Building Locally + +Build the `gpu-mockctl` binary: + +```bash +CGO_ENABLED=1 go build -o /tmp/gpu-mockctl ./cmd/gpu-mockctl +/tmp/gpu-mockctl --help +``` + +### Building the Container Image + +From the repository root: + +```bash +docker build -t local/gpu-mockctl:dev \ + -f deployments/devel/gpu-mock/Dockerfile . +``` + +### Running Manually + +Run `gpu-mockctl` locally (requires `CAP_MKNOD` or root): + +```bash +sudo /tmp/gpu-mockctl --base /tmp/nvidia-mock --machine dgxa100 +ls -lR /tmp/nvidia-mock +``` + +### Extending with New Machine Types + +When `go-nvml` adds new mock machine types, extend the registry: + +1. Edit `pkg/gpu/mocktopo/provider.go` +2. Add a new `Register()` call in `init()`: + +```go +Register("dgxh100", func() (*Topology, error) { + srv := dgxh100.New() + var gpus []GPUInfo + for _, d := range srv.Devices { + dev := d.(*dgxh100.Device) + gpus = append(gpus, GPUInfo{ + PCI: dev.PciBusID, + UUID: dev.UUID, + Model: dev.Name, + }) + } + if len(gpus) == 0 { + return nil, errors.New("dgxh100 mock returned zero GPUs") + } + return &Topology{GPUs: gpus}, nil +}) +``` + +3. Update the Job manifest to use the new machine type: + +```yaml +env: + - name: MACHINE_TYPE + value: "dgxh100" +``` + +No changes are needed to `gpu-mockctl`, `mockfs`, or the verify script. + +## Troubleshooting + +### Job fails with "MISSING: " + +**Cause**: The initContainer failed to create the filesystem structure. + +**Solution**: + +1. Check initContainer logs: + ```bash + kubectl -n gpu-mock logs -c setup-mock + ``` +2. Verify `privileged: true` is set in the Job manifest for the + initContainer. + +### Build fails with "undefined: Return" + +**Cause**: `go-nvml` requires CGO, but `CGO_ENABLED=0` was set. + +**Solution**: Ensure `CGO_ENABLED=1` in the Dockerfile builder stage +(already configured). + +### kind load hangs or fails + +**Cause**: Docker daemon is not running or kind cluster doesn't exist. + +**Solution**: + +1. Verify Docker is running: `docker ps` +2. Check kind clusters: `kind get clusters` +3. Recreate the cluster: `make clean && make kind-up` + +### Job times out waiting for completion + +**Cause**: The verify container may be failing repeatedly. + +**Solution**: + +1. Check Job status: + ```bash + kubectl -n gpu-mock get jobs + kubectl -n gpu-mock describe job gpu-mock-verify + ``` +2. Check pod status: + ```bash + kubectl -n gpu-mock get pods + kubectl -n gpu-mock logs -c verify + ``` + +## Files + +**Step 1 (Mock Filesystem):** +- **`00-namespace.yaml`**: Creates the `gpu-mock` namespace +- **`10-configmap-verify-script.yaml`**: Shell script that validates the + mock filesystem +- **`20-job-gpu-mock-verify.yaml`**: Kubernetes Job with initContainer + (setup) and container (verify) + +**Step 2 (CDI + Toolkit):** +- **`30-daemonset-cdi-mock.yaml`**: DaemonSet that runs `gpu-mockctl` in + CDI mode on every node +- **`40-job-cdi-smoke.yaml`**: Smoke test Job for CDI validation + +**Common:** +- **`Dockerfile`**: Multi-stage build for `gpu-mockctl` (CGO-enabled + binary) +- **`Makefile`**: Convenience targets for build/deploy/test workflow +- **`README.md`**: This file + +## Summary + +This mock infrastructure provides: + +✅ **Step 1**: Mock NVIDIA driver filesystem (device nodes + procfs) +✅ **Step 2**: Mock NVIDIA toolkit + production-grade CDI specs + +**Key Features:** +- Uses `go-nvml` dgxa100 mock for authentic A100 topology (8 GPUs) +- Integrates `nvidia-container-toolkit/pkg/nvcdi` for CDI generation +- Follows NVIDIA's own testing conventions (empty files, versioned libs) +- Supports both isolated testing (Step 1) and full CDI integration (Step 2) +- Extensible design for future H100/H200/B200 flavors + +**What's Next (Step 3):** +- NVIDIA Device Plugin integration +- NVIDIA DRA (Dynamic Resource Allocation) Driver integration +- Live GPU device allocation to pods + +## License + +Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. + +Licensed under the Apache License, Version 2.0. See the repository root +`LICENSE` file for details. + diff --git a/go.mod b/go.mod index a479dea0..7c8333da 100644 --- a/go.mod +++ b/go.mod @@ -3,8 +3,12 @@ module github.com/NVIDIA/k8s-test-infra go 1.25.0 require ( + github.com/NVIDIA/go-nvml v0.13.0-1 + github.com/NVIDIA/nvidia-container-toolkit v1.17.8 github.com/onsi/ginkgo/v2 v2.26.0 github.com/onsi/gomega v1.38.2 + github.com/urfave/cli/v3 v3.4.1 + golang.org/x/sys v0.36.0 k8s.io/api v0.34.1 k8s.io/apiextensions-apiserver v0.34.1 k8s.io/apimachinery v0.34.1 @@ -13,12 +17,15 @@ require ( sigs.k8s.io/node-feature-discovery v0.18.1 sigs.k8s.io/node-feature-discovery/api/nfd v0.18.1 sigs.k8s.io/yaml v1.6.0 + tags.cncf.io/container-device-interface/specs-go v1.0.0 ) require ( github.com/Masterminds/semver/v3 v3.4.0 // indirect + github.com/NVIDIA/go-nvlib v0.7.2 // indirect github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect github.com/emicklei/go-restful/v3 v3.12.2 // indirect + github.com/fsnotify/fsnotify v1.9.0 // indirect github.com/fxamacker/cbor/v2 v2.9.0 // indirect github.com/go-logr/logr v1.4.3 // indirect github.com/go-openapi/jsonpointer v0.21.0 // indirect @@ -36,7 +43,11 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee // indirect github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect + github.com/opencontainers/runtime-spec v1.2.1 // indirect + github.com/opencontainers/runtime-tools v0.9.1-0.20221107090550-2e043c6bd626 // indirect github.com/pkg/errors v0.9.1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 // indirect github.com/x448/float16 v0.8.4 // indirect go.uber.org/automaxprocs v1.6.0 // indirect go.yaml.in/yaml/v2 v2.4.2 // indirect @@ -45,7 +56,6 @@ require ( golang.org/x/net v0.44.0 // indirect golang.org/x/oauth2 v0.30.0 // indirect golang.org/x/sync v0.17.0 // indirect - golang.org/x/sys v0.36.0 // indirect golang.org/x/term v0.35.0 // indirect golang.org/x/text v0.29.0 // indirect golang.org/x/time v0.13.0 // indirect @@ -59,4 +69,5 @@ require ( sigs.k8s.io/json v0.0.0-20241014173422-cfa47c3a1cc8 // indirect sigs.k8s.io/randfill v1.0.0 // indirect sigs.k8s.io/structured-merge-diff/v6 v6.3.0 // indirect + tags.cncf.io/container-device-interface v0.8.1 // indirect ) diff --git a/go.sum b/go.sum index 97322fc7..137cc907 100644 --- a/go.sum +++ b/go.sum @@ -1,11 +1,21 @@ github.com/Masterminds/semver/v3 v3.4.0 h1:Zog+i5UMtVoCU8oKka5P7i9q9HgrJeGzI9SA1Xbatp0= github.com/Masterminds/semver/v3 v3.4.0/go.mod h1:4V+yj/TJE1HU9XfppCwVMZq3I84lprf4nC11bSS5beM= +github.com/NVIDIA/go-nvlib v0.7.2 h1:7sy/NVUa4sM9FLKwH6CjBfHSWrJUmv8emVyxLTzjfOA= +github.com/NVIDIA/go-nvlib v0.7.2/go.mod h1:2Kh2kYSP5IJ8EKf0/SYDzHiQKb9EJkwOf2LQzu6pXzY= +github.com/NVIDIA/go-nvml v0.13.0-1 h1:OLX8Jq3dONuPOQPC7rndB6+iDmDakw0XTYgzMxObkEw= +github.com/NVIDIA/go-nvml v0.13.0-1/go.mod h1:+KNA7c7gIBH7SKSJ1ntlwkfN80zdx8ovl4hrK3LmPt4= +github.com/NVIDIA/nvidia-container-toolkit v1.17.8 h1:ndE23TKvQBicsZT88mzZudygn6JNOe6+UsIgqk6gGvw= +github.com/NVIDIA/nvidia-container-toolkit v1.17.8/go.mod h1:khOgMW80+g8eX/1zPlO4demLShHht9I0YEm8ngcPgwk= +github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM= +github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/emicklei/go-restful/v3 v3.12.2 h1:DhwDP0vY3k8ZzE0RunuJy8GhNpPL6zqLkDf9B/a0/xU= github.com/emicklei/go-restful/v3 v3.12.2/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= +github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= github.com/fxamacker/cbor/v2 v2.9.0 h1:NpKPmjDBgUfBms6tr6JZkTHtfFGcMKsw3eGcmD/sapM= github.com/fxamacker/cbor/v2 v2.9.0/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/gkampitakis/ciinfo v0.3.2 h1:JcuOPk8ZU7nZQjdUhctuhQofk7BGHuIy0c9Ez8BNhXs= @@ -35,8 +45,14 @@ github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6 h1:EEHtgt9IwisQ2AZ4pIsMjahcegHh6rmhqxzIRQIyepY= github.com/google/pprof v0.0.0-20250820193118-f64d9cf942d6/go.mod h1:I6V7YzU0XDpsHqbsyrghnFZLO1gwK6NPTNvmetQIk9U= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I= +github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= +github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= +github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY= github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y= github.com/joshdk/go-junit v1.0.0 h1:S86cUKIdwBHWwA6xCmFlf3RTLfVXYQfvanM5Uh+K6GE= @@ -55,18 +71,27 @@ github.com/maruel/natural v1.1.1 h1:Hja7XhhmvEFhcByqDoHz9QZbkWey+COd9xWfCfn1ioo= github.com/maruel/natural v1.1.1/go.mod h1:v+Rfd79xlw1AgVBjbO0BEQmptqb5HvL/k9GRHB7ZKEg= github.com/mfridman/tparse v0.18.0 h1:wh6dzOKaIwkUGyKgOntDW4liXSo37qg5AXbIhkMV3vE= github.com/mfridman/tparse v0.18.0/go.mod h1:gEvqZTuCgEhPbYk/2lS3Kcxg1GmTxxU7kTC8DvP0i/A= +github.com/mndrix/tap-go v0.0.0-20171203230836-629fa407e90b/go.mod h1:pzzDgJWZ34fGzaAZGFW22KVZDfyrYW+QABMrWnJBnSs= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/mrunalp/fileutils v0.5.0/go.mod h1:M1WthSahJixYnrXQl/DFQuteStB1weuxD2QJNHXfbSQ= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA= github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ= github.com/onsi/ginkgo/v2 v2.26.0 h1:1J4Wut1IlYZNEAWIV3ALrT9NfiaGW2cDCJQSFQMs/gE= github.com/onsi/ginkgo/v2 v2.26.0/go.mod h1:qhEywmzWTBUY88kfO0BRvX4py7scov9yR+Az2oavUzw= github.com/onsi/gomega v1.38.2 h1:eZCjf2xjZAqe+LeWvKb5weQ+NcPwX84kqJ0cZNxok2A= github.com/onsi/gomega v1.38.2/go.mod h1:W2MJcYxRGV63b418Ai34Ud0hEdTVXq9NW9+Sx6uXf3k= +github.com/opencontainers/runtime-spec v1.0.3-0.20220825212826-86290f6a00fb/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-spec v1.2.1 h1:S4k4ryNgEpxW1dzyqffOmhI1BHYcjzU8lpJfSlR0xww= +github.com/opencontainers/runtime-spec v1.2.1/go.mod h1:jwyrGlmzljRJv/Fgzds9SsS/C5hL+LL3ko9hs6T5lQ0= +github.com/opencontainers/runtime-tools v0.9.1-0.20221107090550-2e043c6bd626 h1:DmNGcqH3WDbV5k8OJ+esPWbqUOX5rMLR2PMvziDMJi0= +github.com/opencontainers/runtime-tools v0.9.1-0.20221107090550-2e043c6bd626/go.mod h1:BRHJJd0E+cx42OybVYSgUvZmU0B8P9gZuRXlZUP7TKI= +github.com/opencontainers/selinux v1.9.1 h1:b4VPEF3O5JLZgdTDBmGepaaIbAo0GqoF6EBRq5f/g3Y= +github.com/opencontainers/selinux v1.9.1/go.mod h1:2i0OySw99QjzBBQByd1Gr9gSjvuho1lHsJxIJ3gGbJI= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -76,14 +101,21 @@ github.com/prashantv/gostub v1.1.0 h1:BTyx3RfQjRHnUWaGF9oQos79AlQ5k8WNktv7VGvVH4 github.com/prashantv/gostub v1.1.0/go.mod h1:A5zLQHz7ieHGG7is6LLXLz7I8+3LZzsrV0P1IAHhP5U= github.com/rogpeppe/go-internal v1.13.1 h1:KvO1DLK/DRN07sQ1LQKScxyZJuNnedQ5/wKSR38lUII= github.com/rogpeppe/go-internal v1.13.1/go.mod h1:uMEvuHeurkdAXX61udpOXGD/AzZDWNMNyH2VO9fmH0o= +github.com/sirupsen/logrus v1.8.1/go.mod h1:yWOB1SBYBC5VeMP7gHvWumXLIWorT60ONWic61uBYv0= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.2 h1:xuMeJ0Sdp5ZMRXx/aWO6RZxdr3beISkG5/G/aIRr3pY= github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 h1:kdXcSzyDtseVEc4yCz2qF8ZrQvIDBJLl4S1c3GCXmoI= +github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635/go.mod h1:hkRG7XYTFWNJGYcbNJQlaLq0fg1yr4J4t/NcTQtrfww= github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY= github.com/tidwall/gjson v1.18.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= @@ -92,8 +124,18 @@ github.com/tidwall/pretty v1.2.1 h1:qjsOFOWWQl+N3RsoF5/ssm1pHmJJwhjlSbZ51I6wMl4= github.com/tidwall/pretty v1.2.1/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY= github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28= +github.com/urfave/cli v1.19.1/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA= +github.com/urfave/cli/v3 v3.4.1 h1:1M9UOCy5bLmGnuu1yn3t3CB4rG79Rtoxuv1sPhnm6qM= +github.com/urfave/cli/v3 v3.4.1/go.mod h1:FJSKtM/9AiiTOJL4fJ6TbMUkxBXn7GO9guZqoZtpYpo= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= go.uber.org/automaxprocs v1.6.0 h1:O3y2/QNTOdbF+e/dpXNNW7Rx2hZ4sTIPyybbxyNqTUs= @@ -124,7 +166,10 @@ golang.org/x/sync v0.17.0 h1:l60nONMj9l5drqw6jlhIELNv9I0A4OFgRsG9k2oT9Ug= golang.org/x/sync v0.17.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20191115151921-52ab43148777/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.36.0 h1:KVRy2GtZBrk1cBYA7MKu5bEZFxQk4NIDV6RLVcC8o0k= golang.org/x/sys v0.36.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= golang.org/x/term v0.35.0 h1:bZBVKBudEyhRcajGcNc3jIfWPqV4y/Kt2XcoigOWtDQ= @@ -154,6 +199,8 @@ gopkg.in/evanphx/json-patch.v4 v4.12.0 h1:n6jtcsulIzXPJaxegRbvFNNrZDjbij7ny3gmSP gopkg.in/evanphx/json-patch.v4 v4.12.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= k8s.io/api v0.34.1 h1:jC+153630BMdlFukegoEL8E/yT7aLyQkIVuwhmwDgJM= @@ -182,3 +229,7 @@ sigs.k8s.io/structured-merge-diff/v6 v6.3.0 h1:jTijUJbW353oVOd9oTlifJqOGEkUw2jB/ sigs.k8s.io/structured-merge-diff/v6 v6.3.0/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= sigs.k8s.io/yaml v1.6.0 h1:G8fkbMSAFqgEFgh4b1wmtzDnioxFCUgTZhlbj5P9QYs= sigs.k8s.io/yaml v1.6.0/go.mod h1:796bPqUfzR/0jLAl6XjHl3Ck7MiyVv8dbTdyT3/pMf4= +tags.cncf.io/container-device-interface v0.8.1 h1:c0jN4Mt6781jD67NdPajmZlD1qrqQyov/Xfoab37lj0= +tags.cncf.io/container-device-interface v0.8.1/go.mod h1:Apb7N4VdILW0EVdEMRYXIDVRZfNJZ+kmEUss2kRRQ6Y= +tags.cncf.io/container-device-interface/specs-go v1.0.0 h1:8gLw29hH1ZQP9K1YtAzpvkHCjjyIxHZYzBAvlQ+0vD8= +tags.cncf.io/container-device-interface/specs-go v1.0.0/go.mod h1:u86hoFWqnh3hWz3esofRFKbI261bUlvUfLKGrDhJkgQ= diff --git a/hack/kind-up-gpu-mock.sh b/hack/kind-up-gpu-mock.sh new file mode 100755 index 00000000..454532cb --- /dev/null +++ b/hack/kind-up-gpu-mock.sh @@ -0,0 +1,21 @@ +#!/usr/bin/env bash +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +make -C "${REPO_ROOT}/deployments/devel/gpu-mock" all + diff --git a/pkg/gpu/cdi/paths.go b/pkg/gpu/cdi/paths.go new file mode 100644 index 00000000..29fd0719 --- /dev/null +++ b/pkg/gpu/cdi/paths.go @@ -0,0 +1,25 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cdi + +const ( + // DefaultCDIRoot is the standard location for CDI specifications. + DefaultCDIRoot = "/etc/cdi" + + // DefaultSpecPath is the default output path for the NVIDIA CDI spec. + DefaultSpecPath = "/etc/cdi/nvidia.yaml" + + // VarRunCDI is an alternative CDI root location. + VarRunCDI = "/var/run/cdi" +) diff --git a/pkg/gpu/cdi/specgen.go b/pkg/gpu/cdi/specgen.go new file mode 100644 index 00000000..1db19361 --- /dev/null +++ b/pkg/gpu/cdi/specgen.go @@ -0,0 +1,103 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi" + + "sigs.k8s.io/yaml" +) + +// Options contains configuration for CDI spec generation using the +// nvidia-container-toolkit nvcdi library. +type Options struct { + // NVMLLib is the NVML library implementation to use for device + // discovery. Typically a mock implementation for testing. + NVMLLib nvml.Interface + + // DriverRoot is the root directory where the mock NVIDIA driver + // files are located. + DriverRoot string + + // DevRoot is the root directory where device nodes are located + // (typically /dev or /host/dev). + DevRoot string + + // NVIDIACDIHookPath is the path to the nvidia-cdi-hook binary. + NVIDIACDIHookPath string + + // Vendor is the CDI vendor name (default: nvidia.com). + Vendor string + + // Class is the CDI class name (default: gpu). + Class string +} + +// Generate creates a CDI specification using the nvidia-container-toolkit's +// nvcdi library with the provided NVML implementation (typically a mock). +// +// This leverages the production-grade CDI generation logic from +// nvidia-container-toolkit, ensuring consistency with real deployments. +func Generate(o Options) ([]byte, error) { + if o.NVMLLib == nil { + return nil, fmt.Errorf("NVMLLib is required") + } + + if o.DriverRoot == "" { + o.DriverRoot = "/" + } + + if o.DevRoot == "" { + o.DevRoot = o.DriverRoot + } + + if o.NVIDIACDIHookPath == "" { + o.NVIDIACDIHookPath = "/usr/bin/nvidia-cdi-hook" + } + + // Build nvcdi options + opts := []nvcdi.Option{ + nvcdi.WithMode(nvcdi.ModeNvml), + nvcdi.WithNvmlLib(o.NVMLLib), + nvcdi.WithDriverRoot(o.DriverRoot), + nvcdi.WithDevRoot(o.DevRoot), + nvcdi.WithNVIDIACDIHookPath(o.NVIDIACDIHookPath), + } + + if o.Vendor != "" { + opts = append(opts, nvcdi.WithVendor(o.Vendor)) + } + if o.Class != "" { + opts = append(opts, nvcdi.WithClass(o.Class)) + } + + // Create the nvcdi library with our mock NVML + lib, err := nvcdi.New(opts...) + if err != nil { + return nil, fmt.Errorf("failed to create nvcdi library: %w", err) + } + + // Generate the CDI spec + spec, err := lib.GetSpec() + if err != nil { + return nil, fmt.Errorf("failed to generate CDI spec: %w", err) + } + + // Get the raw spec and marshal to YAML + rawSpec := spec.Raw() + return yaml.Marshal(rawSpec) +} diff --git a/pkg/gpu/cdi/validate.go b/pkg/gpu/cdi/validate.go new file mode 100644 index 00000000..e17146a3 --- /dev/null +++ b/pkg/gpu/cdi/validate.go @@ -0,0 +1,44 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package cdi + +import ( + "fmt" + + specgo "tags.cncf.io/container-device-interface/specs-go" + + "sigs.k8s.io/yaml" +) + +// Validate performs basic validation on a CDI specification YAML. +// It checks that the YAML can be unmarshaled and contains required fields. +func Validate(b []byte) error { + var spec specgo.Spec + if err := yaml.Unmarshal(b, &spec); err != nil { + return fmt.Errorf("invalid YAML: %w", err) + } + + // Basic validation + if spec.Version == "" { + return fmt.Errorf("missing CDI version") + } + if spec.Kind == "" { + return fmt.Errorf("missing CDI kind") + } + if len(spec.Devices) == 0 { + return fmt.Errorf("no devices defined") + } + + return nil +} diff --git a/pkg/gpu/mockdriver/tree.go b/pkg/gpu/mockdriver/tree.go new file mode 100644 index 00000000..d2146e02 --- /dev/null +++ b/pkg/gpu/mockdriver/tree.go @@ -0,0 +1,145 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mockdriver + +import ( + "fmt" + "path/filepath" +) + +// FileSpec describes a file to be created: either a regular file with +// content or a symlink. +type FileSpec struct { + Path string + SymlinkTo string + Content string + Mode uint32 + IsCharDev bool + DevMajor uint32 + DevMinor uint32 + EmptyFile bool // If true, create an empty file (for nvcdi testing) +} + +// DefaultFiles returns the mock driver/toolkit tree files under the +// specified root directory. Following nvidia-container-toolkit's testdata +// convention, we create empty files for libraries to work with nvcdi's +// library discovery when __NVCT_TESTING_DEVICES_ARE_FILES=true. +func DefaultFiles(root string) []FileSpec { + // Match dgxa100 mock driver version + driverVer := "550.54.15" + + files := []FileSpec{ + // Libraries with versioned naming (empty files like testdata) + {Path: filepath.Join(root, "lib64", "libcuda.so."+driverVer), + Mode: 0644, EmptyFile: true}, + {Path: filepath.Join(root, "lib64", "libcuda.so.1"), + SymlinkTo: "libcuda.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libcuda.so"), + SymlinkTo: "libcuda.so.1"}, + + {Path: filepath.Join(root, "lib64", "libnvidia-ml.so."+driverVer), + Mode: 0644, EmptyFile: true}, + {Path: filepath.Join(root, "lib64", "libnvidia-ml.so.1"), + SymlinkTo: "libnvidia-ml.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libnvidia-ml.so"), + SymlinkTo: "libnvidia-ml.so.1"}, + + {Path: filepath.Join(root, "lib64", + "libnvidia-encode.so."+driverVer), Mode: 0644, EmptyFile: true}, + {Path: filepath.Join(root, "lib64", "libnvidia-encode.so.1"), + SymlinkTo: "libnvidia-encode.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libnvidia-encode.so"), + SymlinkTo: "libnvidia-encode.so.1"}, + + {Path: filepath.Join(root, "lib64", "libnvcuvid.so."+driverVer), + Mode: 0644, EmptyFile: true}, + {Path: filepath.Join(root, "lib64", "libnvcuvid.so.1"), + SymlinkTo: "libnvcuvid.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libnvcuvid.so"), + SymlinkTo: "libnvcuvid.so.1"}, + + {Path: filepath.Join(root, "lib64", + "libnvidia-ptxjitcompiler.so."+driverVer), Mode: 0644, + EmptyFile: true}, + {Path: filepath.Join(root, "lib64", "libnvidia-ptxjitcompiler.so.1"), + SymlinkTo: "libnvidia-ptxjitcompiler.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libnvidia-ptxjitcompiler.so"), + SymlinkTo: "libnvidia-ptxjitcompiler.so.1"}, + + {Path: filepath.Join(root, "lib64", + "libnvidia-fatbinaryloader.so."+driverVer), Mode: 0644, + EmptyFile: true}, + {Path: filepath.Join(root, "lib64", + "libnvidia-fatbinaryloader.so.1"), + SymlinkTo: "libnvidia-fatbinaryloader.so." + driverVer}, + {Path: filepath.Join(root, "lib64", "libnvidia-fatbinaryloader.so"), + SymlinkTo: "libnvidia-fatbinaryloader.so.1"}, + + // Binaries (shell scripts) + {Path: filepath.Join(root, "bin", "nvidia-smi"), Mode: 0755, + Content: "#!/bin/sh\necho 'NVIDIA-SMI (mock)'\n"}, + {Path: filepath.Join(root, "bin", "nvidia-debugdump"), Mode: 0755, + Content: "#!/bin/sh\necho 'nvidia-debugdump (mock)'\n"}, + {Path: filepath.Join(root, "bin", "nvidia-persistenced"), + Mode: 0755, + Content: "#!/bin/sh\necho 'nvidia-persistenced (mock)'\n"}, + {Path: filepath.Join(root, "bin", "nvidia-modprobe"), Mode: 0755, + Content: "#!/bin/sh\necho 'nvidia-modprobe (mock)'\n"}, + + // Config + {Path: filepath.Join(root, "etc", "nvidia-container-runtime", + "config.toml"), Mode: 0644, + Content: "# mock nvidia-container-runtime config\n"}, + } + + return files +} + +// DeviceNodes returns device node specs. When +// __NVCT_TESTING_DEVICES_ARE_FILES=true, these will be created as empty +// files instead of character devices (following nvidia-container-toolkit's +// testdata convention). +func DeviceNodes(root string, gpuCount int, withDRI bool) []FileSpec { + specs := []FileSpec{ + // When __NVCT_TESTING_DEVICES_ARE_FILES=true, use empty files + {Path: filepath.Join(root, "dev", "nvidiactl"), Mode: 0666, + EmptyFile: true}, + {Path: filepath.Join(root, "dev", "nvidia-uvm"), Mode: 0666, + EmptyFile: true}, + {Path: filepath.Join(root, "dev", "nvidia-uvm-tools"), Mode: 0666, + EmptyFile: true}, + } + + for i := 0; i < gpuCount; i++ { + specs = append(specs, FileSpec{ + Path: filepath.Join(root, "dev", "nvidia"+itoa(i)), + Mode: 0666, + EmptyFile: true, + }) + } + + if withDRI { + specs = append(specs, FileSpec{ + Path: filepath.Join(root, "dev", "dri", "renderD128"), + Mode: 0666, + EmptyFile: true, + }) + } + + return specs +} + +func itoa(i int) string { + return fmt.Sprintf("%d", i) +} diff --git a/pkg/gpu/mockdriver/write.go b/pkg/gpu/mockdriver/write.go new file mode 100644 index 00000000..6697a69f --- /dev/null +++ b/pkg/gpu/mockdriver/write.go @@ -0,0 +1,75 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mockdriver + +import ( + "fmt" + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) + +// WriteAll writes all file specs to disk, creating directories, +// symlinks, regular files, and character devices as specified. +func WriteAll(files []FileSpec) error { + for _, f := range files { + if err := os.MkdirAll(filepath.Dir(f.Path), 0o755); err != nil { + return fmt.Errorf("mkdir %s: %w", filepath.Dir(f.Path), err) + } + + if f.IsCharDev { + if err := mkChar(f.Path, f.DevMajor, f.DevMinor, + os.FileMode(f.Mode)); err != nil { + return err + } + continue + } + + if f.SymlinkTo != "" { + // Remove existing file/symlink first + _ = os.Remove(f.Path) + if err := os.Symlink(f.SymlinkTo, f.Path); err != nil { + return fmt.Errorf("symlink %s->%s: %w", + f.Path, f.SymlinkTo, err) + } + continue + } + + // Create empty file or file with content + var content []byte + if !f.EmptyFile { + content = []byte(f.Content) + } + // EmptyFile: content remains nil/empty + + if err := os.WriteFile(f.Path, content, + os.FileMode(f.Mode)); err != nil { + return fmt.Errorf("write %s: %w", f.Path, err) + } + } + return nil +} + +func mkChar(path string, major, minor uint32, perm os.FileMode) error { + // Remove existing device node if present + _ = os.Remove(path) + + dev := int(unix.Mkdev(major, minor)) + mode := uint32(unix.S_IFCHR | uint32(perm)) + if err := unix.Mknod(path, mode, dev); err != nil { + return fmt.Errorf("mknod %s: %w", path, err) + } + return nil +} diff --git a/pkg/gpu/mockfs/devnodes.go b/pkg/gpu/mockfs/devnodes.go new file mode 100644 index 00000000..3c1a93a6 --- /dev/null +++ b/pkg/gpu/mockfs/devnodes.go @@ -0,0 +1,36 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mockfs + +import ( + "fmt" + "os" + "path/filepath" + + "golang.org/x/sys/unix" +) + +// MkChar creates a character device node at the specified path with the +// given major and minor numbers. +func MkChar(path string, major, minor uint32, perm os.FileMode) error { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + return err + } + dev := int(unix.Mkdev(major, minor)) + mode := uint32(unix.S_IFCHR | uint32(perm)) + if err := unix.Mknod(path, mode, dev); err != nil { + return fmt.Errorf("mknod %s: %w", path, err) + } + return nil +} diff --git a/pkg/gpu/mockfs/procfs.go b/pkg/gpu/mockfs/procfs.go new file mode 100644 index 00000000..65633e9e --- /dev/null +++ b/pkg/gpu/mockfs/procfs.go @@ -0,0 +1,89 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mockfs + +import ( + "fmt" + "os" + "path/filepath" +) + +// GPU represents a single GPU device in the mock filesystem. +type GPU struct { + PCI string + UUID string + Model string +} + +// Layout represents the complete mock NVIDIA driver filesystem layout. +type Layout struct { + Base string + GPUs []GPU +} + +// Write creates the mock NVIDIA driver filesystem structure under Base, +// including device nodes in dev/ and proc entries in proc/driver/nvidia/. +func (l Layout) Write() error { + dev := filepath.Join(l.Base, "dev") + proc := filepath.Join(l.Base, "proc/driver/nvidia") + + if err := os.MkdirAll(dev, 0o755); err != nil { + return err + } + if err := os.MkdirAll(proc, 0o755); err != nil { + return err + } + + // Create device nodes for each GPU + for i := range l.GPUs { + devPath := filepath.Join(dev, fmt.Sprintf("nvidia%d", i)) + if err := MkChar(devPath, 195, uint32(i), 0o666); err != nil { + return err + } + } + + // Create control and UVM device nodes + if err := MkChar(filepath.Join(dev, "nvidiactl"), 195, 255, 0o666); err != nil { + return err + } + if err := MkChar(filepath.Join(dev, "nvidia-uvm"), 235, 0, 0o666); err != nil { + return err + } + if err := MkChar(filepath.Join(dev, "nvidia-uvm-tools"), 235, 1, 0o666); err != nil { + return err + } + + // Write proc version file + versionContent := []byte("NVRM version: mock (go-nvml dgxa100)\n") + versionPath := filepath.Join(proc, "version") + if err := os.WriteFile(versionPath, versionContent, 0o644); err != nil { + return err + } + + // Write GPU information files + for _, g := range l.GPUs { + gpuDir := filepath.Join(proc, "gpus", g.PCI) + if err := os.MkdirAll(gpuDir, 0o755); err != nil { + return err + } + info := fmt.Sprintf("Model: %s\nGPU UUID: %s\nBus Location: %s\n", + g.Model, g.UUID, g.PCI) + infoPath := filepath.Join(gpuDir, "information") + if err := os.WriteFile(infoPath, []byte(info), 0o644); err != nil { + return err + } + } + + return nil +} diff --git a/pkg/gpu/mockfs/util.go b/pkg/gpu/mockfs/util.go new file mode 100644 index 00000000..e0f9a3da --- /dev/null +++ b/pkg/gpu/mockfs/util.go @@ -0,0 +1,21 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mockfs + +import "strings" + +// NormPCI normalizes a PCI bus ID by trimming whitespace. +func NormPCI(p string) string { + return strings.TrimSpace(p) +} diff --git a/pkg/gpu/mocktopo/localmock.go b/pkg/gpu/mocktopo/localmock.go new file mode 100644 index 00000000..a94a1cf1 --- /dev/null +++ b/pkg/gpu/mocktopo/localmock.go @@ -0,0 +1,46 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mocktopo + +import "fmt" + +// NewFallback creates a synthetic Topology with n GPUs of the specified +// model. This is used when a machine type is not supported but +// ALLOW_UNSUPPORTED=true is set. +// +// Note: Currently uses dgxa100 mock as the underlying NVML implementation +// regardless of the requested GPU count or model name, to ensure CDI +// generation works correctly. +func NewFallback(n int, model string) *Topology { + // Use wrapped NVML interface with MIG support stubs + nvmlImpl := newNVMLWrapper() + + gpus := make([]GPUInfo, 0, n) + for i := 0; i < n; i++ { + pci := fmt.Sprintf("0000:%02x:00.0", 0x81+i) + uuid := fmt.Sprintf( + "GPU-%08d-%04d-%04d-%04d-%012d", + i+1, i+1, i+1, i+1, i+1, + ) + gpus = append(gpus, GPUInfo{ + PCI: pci, + UUID: uuid, + Model: model, + }) + } + return &Topology{ + GPUs: gpus, + nvmlImpl: nvmlImpl, // Use wrapped NVML interface + } +} diff --git a/pkg/gpu/mocktopo/nvmlwrapper.go b/pkg/gpu/mocktopo/nvmlwrapper.go new file mode 100644 index 00000000..81122bcf --- /dev/null +++ b/pkg/gpu/mocktopo/nvmlwrapper.go @@ -0,0 +1,49 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mocktopo + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + dgxa100 "github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100" +) + +// nvmlWrapper wraps the dgxa100.Server and adds MIG-related methods +// that are required by nvcdi but not implemented in the base mock. +type nvmlWrapper struct { + *dgxa100.Server +} + +// newNVMLWrapper creates an NVML interface wrapper that adds missing +// methods required by nvidia-container-toolkit's nvcdi library. +func newNVMLWrapper() nvml.Interface { + srv := dgxa100.New() + + // Add GetMaxMigDeviceCount implementation to all devices + // (return 0 to indicate no MIG support) + for i := range srv.Devices { + if dev, ok := srv.Devices[i].(*dgxa100.Device); ok { + dev.GetMaxMigDeviceCountFunc = func() (int, nvml.Return) { + return 0, nvml.SUCCESS + } + dev.GetMigModeFunc = func() (int, int, nvml.Return) { + return 0, 0, nvml.ERROR_NOT_SUPPORTED + } + dev.GetGpuInstancesFunc = func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { + return nil, nvml.ERROR_NOT_SUPPORTED + } + } + } + + return &nvmlWrapper{Server: srv} +} diff --git a/pkg/gpu/mocktopo/provider.go b/pkg/gpu/mocktopo/provider.go new file mode 100644 index 00000000..6bd7dbe3 --- /dev/null +++ b/pkg/gpu/mocktopo/provider.go @@ -0,0 +1,93 @@ +// Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package mocktopo + +import ( + "errors" + "fmt" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + dgxa100 "github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100" +) + +// GPUInfo holds identifying information for a single GPU. +type GPUInfo struct { + PCI string + UUID string + Model string +} + +// Topology represents the GPU topology for a given machine type. +// It includes both high-level GPU information and the underlying NVML +// interface for integration with nvidia-container-toolkit. +type Topology struct { + GPUs []GPUInfo + nvmlImpl nvml.Interface +} + +// NVMLInterface returns the underlying NVML implementation. +// This is used by the CDI generator to query device information. +func (t *Topology) NVMLInterface() nvml.Interface { + return t.nvmlImpl +} + +// FlavorProvider is a function that constructs a Topology for a specific +// machine flavor (e.g., dgxa100, dgxh100). +type FlavorProvider func() (*Topology, error) + +var registry = map[string]FlavorProvider{} + +// Register adds a new flavor provider to the registry. +func Register(name string, fn FlavorProvider) { + registry[name] = fn +} + +func init() { + Register("dgxa100", func() (*Topology, error) { + // Create wrapped NVML interface with MIG support stubs + nvmlImpl := newNVMLWrapper() + + // Extract GPU info from the underlying dgxa100 server + srv := dgxa100.New() + var gpus []GPUInfo + for _, d := range srv.Devices { + dev := d.(*dgxa100.Device) + gpus = append(gpus, GPUInfo{ + PCI: dev.PciBusID, + UUID: dev.UUID, + Model: dev.Name, + }) + } + if len(gpus) == 0 { + return nil, errors.New("dgxa100 mock returned zero GPUs") + } + return &Topology{ + GPUs: gpus, + nvmlImpl: nvmlImpl, // Store the wrapped NVML interface + }, nil + }) +} + +// New returns a Topology for the specified machine type, or an error if +// the machine type is unsupported. +func New(machine string) (*Topology, error) { + if fn, ok := registry[machine]; ok { + return fn() + } + return nil, fmt.Errorf( + "unsupported MACHINE_TYPE %q (only 'dgxa100'); set "+ + "ALLOW_UNSUPPORTED=true to use fallback", + machine, + ) +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/LICENSE b/vendor/github.com/NVIDIA/go-nvlib/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/NVIDIA/go-nvlib/NOTICE b/vendor/github.com/NVIDIA/go-nvlib/NOTICE new file mode 100644 index 00000000..76760105 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/NOTICE @@ -0,0 +1,4 @@ +The file pkg/pciids/default_pci.ids is distributed under the 3-clause BSD License. +Maintained by Albert Pool, Martin Mares, and other volunteers from +the PCI ID Project at https://pci-ids.ucw.cz/. + diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/api.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/api.go new file mode 100644 index 00000000..c2a6517d --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/api.go @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package device + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// Interface provides the API to the 'device' package. +type Interface interface { + AssertValidMigProfileFormat(profile string) error + GetDevices() ([]Device, error) + GetMigDevices() ([]MigDevice, error) + GetMigProfiles() ([]MigProfile, error) + NewDevice(d nvml.Device) (Device, error) + NewDeviceByUUID(uuid string) (Device, error) + NewMigDevice(d nvml.Device) (MigDevice, error) + NewMigDeviceByUUID(uuid string) (MigDevice, error) + NewMigProfile(giProfileID, ciProfileID, ciEngProfileID int, migMemorySizeMB, deviceMemorySizeBytes uint64) (MigProfile, error) + ParseMigProfile(profile string) (MigProfile, error) + VisitDevices(func(i int, d Device) error) error + VisitMigDevices(func(i int, d Device, j int, m MigDevice) error) error + VisitMigProfiles(func(p MigProfile) error) error +} + +type devicelib struct { + nvmllib nvml.Interface + skippedDevices map[string]struct{} + verifySymbols *bool + migProfiles []MigProfile +} + +var _ Interface = &devicelib{} + +// New creates a new instance of the 'device' interface. +func New(nvmllib nvml.Interface, opts ...Option) Interface { + d := &devicelib{ + nvmllib: nvmllib, + } + for _, opt := range opts { + opt(d) + } + if d.verifySymbols == nil { + verify := true + d.verifySymbols = &verify + } + if d.skippedDevices == nil { + WithSkippedDevices( + "DGX Display", + "NVIDIA DGX Display", + )(d) + } + return d +} + +// WithVerifySymbols provides an option to toggle whether to verify select symbols exist in dynamic libraries before calling them. +func WithVerifySymbols(verify bool) Option { + return func(d *devicelib) { + d.verifySymbols = &verify + } +} + +// WithSkippedDevices provides an Option to set devices to be skipped by model name. +func WithSkippedDevices(names ...string) Option { + return func(d *devicelib) { + if d.skippedDevices == nil { + d.skippedDevices = make(map[string]struct{}) + } + for _, name := range names { + d.skippedDevices[name] = struct{}{} + } + } +} + +// Option defines a function for passing options to the New() call. +type Option func(*devicelib) diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/device.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/device.go new file mode 100644 index 00000000..ea3332fd --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/device.go @@ -0,0 +1,546 @@ +/* + * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package device + +import ( + "fmt" + "strings" + + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// Device defines the set of extended functions associated with a device.Device. +type Device interface { + nvml.Device + GetArchitectureAsString() (string, error) + GetBrandAsString() (string, error) + GetCudaComputeCapabilityAsString() (string, error) + GetMigDevices() ([]MigDevice, error) + GetMigProfiles() ([]MigProfile, error) + GetPCIBusID() (string, error) + IsFabricAttached() (bool, error) + IsMigCapable() (bool, error) + IsMigEnabled() (bool, error) + VisitMigDevices(func(j int, m MigDevice) error) error + VisitMigProfiles(func(p MigProfile) error) error +} + +type device struct { + nvml.Device + lib *devicelib + migProfiles []MigProfile +} + +var _ Device = &device{} + +// NewDevice builds a new Device from an nvml.Device. +func (d *devicelib) NewDevice(dev nvml.Device) (Device, error) { + return d.newDevice(dev) +} + +// NewDeviceByUUID builds a new Device from a UUID. +func (d *devicelib) NewDeviceByUUID(uuid string) (Device, error) { + dev, ret := d.nvmllib.DeviceGetHandleByUUID(uuid) + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting device handle for uuid '%v': %v", uuid, ret) + } + return d.newDevice(dev) +} + +// newDevice creates a device from an nvml.Device. +func (d *devicelib) newDevice(dev nvml.Device) (*device, error) { + return &device{dev, d, nil}, nil +} + +// GetArchitectureAsString returns the Device architecture as a string. +func (d *device) GetArchitectureAsString() (string, error) { + arch, ret := d.GetArchitecture() + if ret != nvml.SUCCESS { + return "", fmt.Errorf("error getting device architecture: %v", ret) + } + switch arch { + case nvml.DEVICE_ARCH_KEPLER: + return "Kepler", nil + case nvml.DEVICE_ARCH_MAXWELL: + return "Maxwell", nil + case nvml.DEVICE_ARCH_PASCAL: + return "Pascal", nil + case nvml.DEVICE_ARCH_VOLTA: + return "Volta", nil + case nvml.DEVICE_ARCH_TURING: + return "Turing", nil + case nvml.DEVICE_ARCH_AMPERE: + return "Ampere", nil + case nvml.DEVICE_ARCH_ADA: + return "Ada Lovelace", nil + case nvml.DEVICE_ARCH_HOPPER: + return "Hopper", nil + case nvml.DEVICE_ARCH_UNKNOWN: + return "Unknown", nil + } + return "", fmt.Errorf("error interpreting device architecture as string: %v", arch) +} + +// GetBrandAsString returns the Device architecture as a string. +func (d *device) GetBrandAsString() (string, error) { + brand, ret := d.GetBrand() + if ret != nvml.SUCCESS { + return "", fmt.Errorf("error getting device brand: %v", ret) + } + switch brand { + case nvml.BRAND_UNKNOWN: + return "Unknown", nil + case nvml.BRAND_QUADRO: + return "Quadro", nil + case nvml.BRAND_TESLA: + return "Tesla", nil + case nvml.BRAND_NVS: + return "NVS", nil + case nvml.BRAND_GRID: + return "Grid", nil + case nvml.BRAND_GEFORCE: + return "GeForce", nil + case nvml.BRAND_TITAN: + return "Titan", nil + case nvml.BRAND_NVIDIA_VAPPS: + return "NvidiaVApps", nil + case nvml.BRAND_NVIDIA_VPC: + return "NvidiaVPC", nil + case nvml.BRAND_NVIDIA_VCS: + return "NvidiaVCS", nil + case nvml.BRAND_NVIDIA_VWS: + return "NvidiaVWS", nil + // Deprecated in favor of nvml.BRAND_NVIDIA_CLOUD_GAMING + // case nvml.BRAND_NVIDIA_VGAMING: + // return "VGaming", nil + case nvml.BRAND_NVIDIA_CLOUD_GAMING: + return "NvidiaCloudGaming", nil + case nvml.BRAND_QUADRO_RTX: + return "QuadroRTX", nil + case nvml.BRAND_NVIDIA_RTX: + return "NvidiaRTX", nil + case nvml.BRAND_NVIDIA: + return "Nvidia", nil + case nvml.BRAND_GEFORCE_RTX: + return "GeForceRTX", nil + case nvml.BRAND_TITAN_RTX: + return "TitanRTX", nil + } + return "", fmt.Errorf("error interpreting device brand as string: %v", brand) +} + +// GetPCIBusID returns the string representation of the bus ID. +func (d *device) GetPCIBusID() (string, error) { + info, ret := d.GetPciInfo() + if ret != nvml.SUCCESS { + return "", fmt.Errorf("error getting PCI info: %w", ret) + } + + var bytes []byte + for _, b := range info.BusId { + if byte(b) == '\x00' { + break + } + bytes = append(bytes, byte(b)) + } + id := strings.ToLower(string(bytes)) + + if id != "0000" { + id = strings.TrimPrefix(id, "0000") + } + + return id, nil +} + +// GetCudaComputeCapabilityAsString returns the Device's CUDA compute capability as a version string. +func (d *device) GetCudaComputeCapabilityAsString() (string, error) { + major, minor, ret := d.GetCudaComputeCapability() + if ret != nvml.SUCCESS { + return "", fmt.Errorf("error getting CUDA compute capability: %v", ret) + } + return fmt.Sprintf("%d.%d", major, minor), nil +} + +// IsMigCapable checks if a device is capable of having MIG paprtitions created on it. +func (d *device) IsMigCapable() (bool, error) { + if !d.lib.hasSymbol("nvmlDeviceGetMigMode") { + return false, nil + } + + _, _, ret := nvml.Device(d).GetMigMode() + if ret == nvml.ERROR_NOT_SUPPORTED { + return false, nil + } + if ret != nvml.SUCCESS { + return false, fmt.Errorf("error getting MIG mode: %v", ret) + } + + return true, nil +} + +// IsMigEnabled checks if a device has MIG mode currently enabled on it. +func (d *device) IsMigEnabled() (bool, error) { + if !d.lib.hasSymbol("nvmlDeviceGetMigMode") { + return false, nil + } + + mode, _, ret := nvml.Device(d).GetMigMode() + if ret == nvml.ERROR_NOT_SUPPORTED { + return false, nil + } + if ret != nvml.SUCCESS { + return false, fmt.Errorf("error getting MIG mode: %v", ret) + } + + return (mode == nvml.DEVICE_MIG_ENABLE), nil +} + +// IsFabricAttached checks if a device is attached to a GPU fabric. +func (d *device) IsFabricAttached() (bool, error) { + if d.lib.hasSymbol("nvmlDeviceGetGpuFabricInfo") { + info, ret := d.GetGpuFabricInfo() + if ret == nvml.ERROR_NOT_SUPPORTED { + return false, nil + } + if ret != nvml.SUCCESS { + return false, fmt.Errorf("error getting GPU Fabric Info: %v", ret) + } + if info.State != nvml.GPU_FABRIC_STATE_COMPLETED { + return false, nil + } + if info.ClusterUuid == [16]uint8{} { + return false, nil + } + if nvml.Return(info.Status) != nvml.SUCCESS { + return false, nil + } + + return true, nil + } + + if d.lib.hasSymbol("nvmlDeviceGetGpuFabricInfoV") { + info, ret := d.GetGpuFabricInfoV().V2() + if ret == nvml.ERROR_NOT_SUPPORTED { + return false, nil + } + if ret != nvml.SUCCESS { + return false, fmt.Errorf("error getting GPU Fabric Info: %v", ret) + } + if info.State != nvml.GPU_FABRIC_STATE_COMPLETED { + return false, nil + } + if info.ClusterUuid == [16]uint8{} { + return false, nil + } + if nvml.Return(info.Status) != nvml.SUCCESS { + return false, nil + } + + return true, nil + } + + return false, nil +} + +// VisitMigDevices walks a top-level device and invokes a callback function for each MIG device configured on it. +func (d *device) VisitMigDevices(visit func(int, MigDevice) error) error { + capable, err := d.IsMigCapable() + if err != nil { + return fmt.Errorf("error checking if GPU is MIG capable: %v", err) + } + if !capable { + return nil + } + + count, ret := nvml.Device(d).GetMaxMigDeviceCount() + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting max MIG device count: %v", ret) + } + + for i := 0; i < count; i++ { + device, ret := nvml.Device(d).GetMigDeviceHandleByIndex(i) + if ret == nvml.ERROR_NOT_FOUND { + continue + } + if ret == nvml.ERROR_INVALID_ARGUMENT { + continue + } + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting MIG device handle at index '%v': %v", i, ret) + } + mig, err := d.lib.NewMigDevice(device) + if err != nil { + return fmt.Errorf("error creating new MIG device wrapper: %v", err) + } + err = visit(i, mig) + if err != nil { + return fmt.Errorf("error visiting MIG device: %v", err) + } + } + return nil +} + +// VisitMigProfiles walks a top-level device and invokes a callback function for each unique MIG Profile that can be configured on it. +func (d *device) VisitMigProfiles(visit func(MigProfile) error) error { + capable, err := d.IsMigCapable() + if err != nil { + return fmt.Errorf("error checking if GPU is MIG capable: %v", err) + } + + if !capable { + return nil + } + + memory, ret := d.GetMemoryInfo() + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting device memory info: %v", ret) + } + + for i := 0; i < nvml.GPU_INSTANCE_PROFILE_COUNT; i++ { + giProfileInfo, ret := d.GetGpuInstanceProfileInfo(i) + if ret == nvml.ERROR_NOT_SUPPORTED { + continue + } + if ret == nvml.ERROR_INVALID_ARGUMENT { + continue + } + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting GPU Instance profile info: %v", ret) + } + + for j := 0; j < nvml.COMPUTE_INSTANCE_PROFILE_COUNT; j++ { + for k := 0; k < nvml.COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT; k++ { + p, err := d.lib.NewMigProfile(i, j, k, giProfileInfo.MemorySizeMB, memory.Total) + if err != nil { + return fmt.Errorf("error creating MIG profile: %v", err) + } + + // NOTE: The NVML API doesn't currently let us query the set of + // valid Compute Instance profiles without first instantiating + // a GPU Instance to check against. In theory, it should be + // possible to get this information without a reference to a + // GPU instance, but no API is provided for that at the moment. + // We run the checks below to weed out invalid profiles + // heuristically, given what we know about how they are + // physically constructed. In the future we should do this via + // NVML once a proper API for this exists. + pi := p.GetInfo() + if pi.C > pi.G { + continue + } + if (pi.C < pi.G) && ((pi.C * 2) > (pi.G + 1)) { + continue + } + + err = visit(p) + if err != nil { + return fmt.Errorf("error visiting MIG profile: %v", err) + } + } + } + } + return nil +} + +// GetMigDevices gets the set of MIG devices associated with a top-level device. +func (d *device) GetMigDevices() ([]MigDevice, error) { + var migs []MigDevice + err := d.VisitMigDevices(func(j int, m MigDevice) error { + migs = append(migs, m) + return nil + }) + if err != nil { + return nil, err + } + return migs, nil +} + +// GetMigProfiles gets the set of unique MIG profiles associated with a top-level device. +func (d *device) GetMigProfiles() ([]MigProfile, error) { + // Return the cached list if available + if d.migProfiles != nil { + return d.migProfiles, nil + } + + // Otherwise generate it... + var profiles []MigProfile + err := d.VisitMigProfiles(func(p MigProfile) error { + profiles = append(profiles, p) + return nil + }) + if err != nil { + return nil, err + } + + // And cache it before returning. + d.migProfiles = profiles + return profiles, nil +} + +// isSkipped checks whether the device should be skipped. +func (d *device) isSkipped() (bool, error) { + name, ret := d.GetName() + if ret != nvml.SUCCESS { + return false, fmt.Errorf("error getting device name: %v", ret) + } + + if _, exists := d.lib.skippedDevices[name]; exists { + return true, nil + } + + return false, nil +} + +// VisitDevices visits each top-level device and invokes a callback function for it. +func (d *devicelib) VisitDevices(visit func(int, Device) error) error { + count, ret := d.nvmllib.DeviceGetCount() + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting device count: %v", ret) + } + + for i := 0; i < count; i++ { + device, ret := d.nvmllib.DeviceGetHandleByIndex(i) + if ret != nvml.SUCCESS { + return fmt.Errorf("error getting device handle for index '%v': %v", i, ret) + } + dev, err := d.newDevice(device) + if err != nil { + return fmt.Errorf("error creating new device wrapper: %v", err) + } + + isSkipped, err := dev.isSkipped() + if err != nil { + return fmt.Errorf("error checking whether device is skipped: %v", err) + } + if isSkipped { + continue + } + + err = visit(i, dev) + if err != nil { + return fmt.Errorf("error visiting device: %v", err) + } + } + return nil +} + +// VisitMigDevices walks a top-level device and invokes a callback function for each MIG device configured on it. +func (d *devicelib) VisitMigDevices(visit func(int, Device, int, MigDevice) error) error { + err := d.VisitDevices(func(i int, dev Device) error { + err := dev.VisitMigDevices(func(j int, mig MigDevice) error { + err := visit(i, dev, j, mig) + if err != nil { + return fmt.Errorf("error visiting MIG device: %v", err) + } + return nil + }) + if err != nil { + return fmt.Errorf("error visiting device: %v", err) + } + return nil + }) + if err != nil { + return fmt.Errorf("error visiting devices: %v", err) + } + return nil +} + +// VisitMigProfiles walks a top-level device and invokes a callback function for each unique MIG profile found on them. +func (d *devicelib) VisitMigProfiles(visit func(MigProfile) error) error { + visited := make(map[string]bool) + err := d.VisitDevices(func(i int, dev Device) error { + err := dev.VisitMigProfiles(func(p MigProfile) error { + if visited[p.String()] { + return nil + } + + err := visit(p) + if err != nil { + return fmt.Errorf("error visiting MIG profile: %v", err) + } + + visited[p.String()] = true + return nil + }) + if err != nil { + return fmt.Errorf("error visiting device: %v", err) + } + return nil + }) + if err != nil { + return fmt.Errorf("error visiting devices: %v", err) + } + return nil +} + +// GetDevices gets the set of all top-level devices. +func (d *devicelib) GetDevices() ([]Device, error) { + var devs []Device + err := d.VisitDevices(func(i int, dev Device) error { + devs = append(devs, dev) + return nil + }) + if err != nil { + return nil, err + } + return devs, nil +} + +// GetMigDevices gets the set of MIG devices across all top-level devices. +func (d *devicelib) GetMigDevices() ([]MigDevice, error) { + var migs []MigDevice + err := d.VisitMigDevices(func(i int, dev Device, j int, m MigDevice) error { + migs = append(migs, m) + return nil + }) + if err != nil { + return nil, err + } + return migs, nil +} + +// GetMigProfiles gets the set of unique MIG profiles across all top-level devices. +func (d *devicelib) GetMigProfiles() ([]MigProfile, error) { + // Return the cached list if available + if d.migProfiles != nil { + return d.migProfiles, nil + } + + // Otherwise generate it... + var profiles []MigProfile + err := d.VisitMigProfiles(func(p MigProfile) error { + profiles = append(profiles, p) + return nil + }) + if err != nil { + return nil, err + } + + // And cache it before returning. + d.migProfiles = profiles + return profiles, nil +} + +// hasSymbol checks to see if the given symbol is present in the NVML library. +// If devicelib is configured to not verify symbols, then all symbols are assumed to exist. +func (d *devicelib) hasSymbol(symbol string) bool { + if !*d.verifySymbols { + return true + } + + return d.nvmllib.Extensions().LookupSymbol(symbol) == nil +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/identifier.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/identifier.go new file mode 100644 index 00000000..114e9cd5 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/identifier.go @@ -0,0 +1,94 @@ +/* + * Copyright (c) NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package device + +import ( + "strconv" + "strings" + + "github.com/google/uuid" +) + +// Identifier can be used to refer to a GPU or MIG device. +// This includes a device index or UUID. +type Identifier string + +// IsGpuIndex checks if an identifier is a full GPU index. +func (i Identifier) IsGpuIndex() bool { + if _, err := strconv.ParseUint(string(i), 10, 0); err != nil { + return false + } + return true +} + +// IsMigIndex checks if an identifier is a MIG index. +func (i Identifier) IsMigIndex() bool { + split := strings.Split(string(i), ":") + if len(split) != 2 { + return false + } + for _, s := range split { + if !Identifier(s).IsGpuIndex() { + return false + } + } + return true +} + +// IsUUID checks if an identifier is a UUID. +func (i Identifier) IsUUID() bool { + return i.IsGpuUUID() || i.IsMigUUID() +} + +// IsGpuUUID checks if an identifier is a GPU UUID. +// A GPU UUID must be of the form GPU-b1028956-cfa2-0990-bf4a-5da9abb51763. +func (i Identifier) IsGpuUUID() bool { + if !strings.HasPrefix(string(i), "GPU-") { + return false + } + _, err := uuid.Parse(strings.TrimPrefix(string(i), "GPU-")) + return err == nil +} + +// IsMigUUID checks if an identifier is a MIG UUID. +// A MIG UUID can be of one of two forms: +// - MIG-b1028956-cfa2-0990-bf4a-5da9abb51763 +// - MIG-GPU-b1028956-cfa2-0990-bf4a-5da9abb51763/3/0 +func (i Identifier) IsMigUUID() bool { + if !strings.HasPrefix(string(i), "MIG-") { + return false + } + suffix := strings.TrimPrefix(string(i), "MIG-") + _, err := uuid.Parse(suffix) + if err == nil { + return true + } + split := strings.Split(suffix, "/") + if len(split) != 3 { + return false + } + if !Identifier(split[0]).IsGpuUUID() { + return false + } + for _, s := range split[1:] { + _, err := strconv.ParseUint(s, 10, 0) + if err != nil { + return false + } + } + return true +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_device.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_device.go new file mode 100644 index 00000000..cf485a4b --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_device.go @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package device + +import ( + "fmt" + + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// MigDevice defines the set of extended functions associated with a MIG device. +type MigDevice interface { + nvml.Device + GetProfile() (MigProfile, error) +} + +type migdevice struct { + nvml.Device + lib *devicelib + profile MigProfile +} + +var _ MigDevice = &migdevice{} + +// NewMigDevice builds a new MigDevice from an nvml.Device. +func (d *devicelib) NewMigDevice(handle nvml.Device) (MigDevice, error) { + isMig, ret := handle.IsMigDeviceHandle() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error checking if device is a MIG device: %v", ret) + } + if !isMig { + return nil, fmt.Errorf("not a MIG device") + } + return &migdevice{handle, d, nil}, nil +} + +// NewMigDeviceByUUID builds a new MigDevice from a UUID. +func (d *devicelib) NewMigDeviceByUUID(uuid string) (MigDevice, error) { + dev, ret := d.nvmllib.DeviceGetHandleByUUID(uuid) + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting device handle for uuid '%v': %v", uuid, ret) + } + return d.NewMigDevice(dev) +} + +// GetProfile returns the MIG profile associated with a MIG device. +func (m *migdevice) GetProfile() (MigProfile, error) { + if m.profile != nil { + return m.profile, nil + } + + parent, ret := m.GetDeviceHandleFromMigDeviceHandle() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting parent device handle: %v", ret) + } + + parentMemoryInfo, ret := parent.GetMemoryInfo() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting parent memory info: %v", ret) + } + + attributes, ret := m.GetAttributes() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting MIG device attributes: %v", ret) + } + + giID, ret := m.GetGpuInstanceId() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting MIG device GPU Instance ID: %v", ret) + } + + ciID, ret := m.GetComputeInstanceId() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting MIG device Compute Instance ID: %v", ret) + } + + gi, ret := parent.GetGpuInstanceById(giID) + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting GPU Instance: %v", ret) + } + + ci, ret := gi.GetComputeInstanceById(ciID) + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting Compute Instance: %v", ret) + } + + giInfo, ret := gi.GetInfo() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting GPU Instance info: %v", ret) + } + + ciInfo, ret := ci.GetInfo() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting Compute Instance info: %v", ret) + } + + for i := 0; i < nvml.GPU_INSTANCE_PROFILE_COUNT; i++ { + giProfileInfo, ret := parent.GetGpuInstanceProfileInfo(i) + if ret == nvml.ERROR_NOT_SUPPORTED { + continue + } + if ret == nvml.ERROR_INVALID_ARGUMENT { + continue + } + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting GPU Instance profile info: %v", ret) + } + + if giProfileInfo.Id != giInfo.ProfileId { + continue + } + + for j := 0; j < nvml.COMPUTE_INSTANCE_PROFILE_COUNT; j++ { + for k := 0; k < nvml.COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT; k++ { + ciProfileInfo, ret := gi.GetComputeInstanceProfileInfo(j, k) + if ret == nvml.ERROR_NOT_SUPPORTED { + continue + } + if ret == nvml.ERROR_INVALID_ARGUMENT { + continue + } + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("error getting Compute Instance profile info: %v", ret) + + } + + if ciProfileInfo.Id != ciInfo.ProfileId { + continue + } + + p, err := m.lib.NewMigProfile(i, j, k, attributes.MemorySizeMB, parentMemoryInfo.Total) + if err != nil { + return nil, fmt.Errorf("error creating MIG profile: %v", err) + } + + m.profile = p + return p, nil + } + } + } + + return nil, fmt.Errorf("no matching profile IDs found") +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_profile.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_profile.go new file mode 100644 index 00000000..c1f0190f --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/device/mig_profile.go @@ -0,0 +1,331 @@ +/* + * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package device + +import ( + "fmt" + "math" + "sort" + "strconv" + "strings" + + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +const ( + // AttributeMediaExtensions holds the string representation for the media extension MIG profile attribute. + AttributeMediaExtensions = "me" +) + +// MigProfile represents a specific MIG profile. +// Examples include "1g.5gb", "2g.10gb", "1c.2g.10gb", or "1c.1g.5gb+me", etc. +type MigProfile interface { + String() string + GetInfo() MigProfileInfo + Equals(other MigProfile) bool + Matches(profile string) bool +} + +// MigProfileInfo holds all info associated with a specific MIG profile. +type MigProfileInfo struct { + C int + G int + GB int + Attributes []string + GIProfileID int + CIProfileID int + CIEngProfileID int +} + +var _ MigProfile = &MigProfileInfo{} + +// NewProfile constructs a new Profile struct using info from the giProfiles and ciProfiles used to create it. +func (d *devicelib) NewMigProfile(giProfileID, ciProfileID, ciEngProfileID int, migMemorySizeMB, deviceMemorySizeBytes uint64) (MigProfile, error) { + giSlices := 0 + switch giProfileID { + case nvml.GPU_INSTANCE_PROFILE_1_SLICE, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2: + giSlices = 1 + case nvml.GPU_INSTANCE_PROFILE_2_SLICE, + nvml.GPU_INSTANCE_PROFILE_2_SLICE_REV1: + giSlices = 2 + case nvml.GPU_INSTANCE_PROFILE_3_SLICE: + giSlices = 3 + case nvml.GPU_INSTANCE_PROFILE_4_SLICE: + giSlices = 4 + case nvml.GPU_INSTANCE_PROFILE_6_SLICE: + giSlices = 6 + case nvml.GPU_INSTANCE_PROFILE_7_SLICE: + giSlices = 7 + case nvml.GPU_INSTANCE_PROFILE_8_SLICE: + giSlices = 8 + default: + return nil, fmt.Errorf("invalid GPU Instance Profile ID: %v", giProfileID) + } + + ciSlices := 0 + switch ciProfileID { + case nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE_REV1: + ciSlices = 1 + case nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: + ciSlices = 2 + case nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE: + ciSlices = 3 + case nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE: + ciSlices = 4 + case nvml.COMPUTE_INSTANCE_PROFILE_6_SLICE: + ciSlices = 6 + case nvml.COMPUTE_INSTANCE_PROFILE_7_SLICE: + ciSlices = 7 + case nvml.COMPUTE_INSTANCE_PROFILE_8_SLICE: + ciSlices = 8 + default: + return nil, fmt.Errorf("invalid Compute Instance Profile ID: %v", ciProfileID) + } + + var attrs []string + switch giProfileID { + case nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1, + nvml.GPU_INSTANCE_PROFILE_2_SLICE_REV1: + attrs = append(attrs, AttributeMediaExtensions) + } + + p := &MigProfileInfo{ + C: ciSlices, + G: giSlices, + GB: int(getMigMemorySizeGB(deviceMemorySizeBytes, migMemorySizeMB)), + Attributes: attrs, + GIProfileID: giProfileID, + CIProfileID: ciProfileID, + CIEngProfileID: ciEngProfileID, + } + + return p, nil +} + +// AssertValidMigProfileFormat checks if the string is in the proper format to represent a MIG profile. +func (d *devicelib) AssertValidMigProfileFormat(profile string) error { + _, _, _, _, err := parseMigProfile(profile) + return err +} + +// ParseMigProfile converts a string representation of a MigProfile into an object. +func (d *devicelib) ParseMigProfile(profile string) (MigProfile, error) { + profiles, err := d.GetMigProfiles() + if err != nil { + return nil, fmt.Errorf("error getting list of possible MIG profiles: %v", err) + } + + for _, p := range profiles { + if p.Matches(profile) { + return p, nil + } + } + + return nil, fmt.Errorf("unable to parse profile string into a valid profile") +} + +// String returns the string representation of a Profile. +func (p MigProfileInfo) String() string { + var suffix string + if len(p.Attributes) > 0 { + suffix = "+" + strings.Join(p.Attributes, ",") + } + if p.C == p.G { + return fmt.Sprintf("%dg.%dgb%s", p.G, p.GB, suffix) + } + return fmt.Sprintf("%dc.%dg.%dgb%s", p.C, p.G, p.GB, suffix) +} + +// GetInfo returns detailed info about a Profile. +func (p MigProfileInfo) GetInfo() MigProfileInfo { + return p +} + +// Equals checks if two Profiles are identical or not. +func (p MigProfileInfo) Equals(other MigProfile) bool { + o := other.GetInfo() + if p.C != o.C { + return false + } + if p.G != o.G { + return false + } + if p.GB != o.GB { + return false + } + if p.GIProfileID != o.GIProfileID { + return false + } + if p.CIProfileID != o.CIProfileID { + return false + } + if p.CIEngProfileID != o.CIEngProfileID { + return false + } + return true +} + +// Matches checks if a MigProfile matches the string passed in. +func (p MigProfileInfo) Matches(profile string) bool { + c, g, gb, attrs, err := parseMigProfile(profile) + if err != nil { + return false + } + if c != p.C { + return false + } + if g != p.G { + return false + } + if gb != p.GB { + return false + } + if len(attrs) != len(p.Attributes) { + return false + } + sort.Strings(attrs) + sort.Strings(p.Attributes) + for i, a := range p.Attributes { + if a != attrs[i] { + return false + } + } + return true +} + +func parseMigProfile(profile string) (int, int, int, []string, error) { + // If we are handed the empty string, we cannot parse it. + if profile == "" { + return -1, -1, -1, nil, fmt.Errorf("profile is the empty string") + } + + // Split by + to separate out attributes. + split := strings.SplitN(profile, "+", 2) + + // Check to make sure the c, g, and gb values match. + c, g, gb, err := parseMigProfileFields(split[0]) + if err != nil { + return -1, -1, -1, nil, fmt.Errorf("cannot parse fields of '%v': %v", profile, err) + } + + // If we have no attributes we are done. + if len(split) == 1 { + return c, g, gb, nil, nil + } + + // Make sure we have the same set of attributes. + attrs, err := parseMigProfileAttributes(split[1]) + if err != nil { + return -1, -1, -1, nil, fmt.Errorf("cannot parse attributes of '%v': %v", profile, err) + } + + return c, g, gb, attrs, nil +} + +func parseMigProfileField(s string, field string) (int, error) { + if strings.TrimSpace(s) != s { + return -1, fmt.Errorf("leading or trailing spaces on '%%d%s'", field) + } + + if !strings.HasSuffix(s, field) { + return -1, fmt.Errorf("missing '%s' from '%%d%s'", field, field) + } + + v, err := strconv.Atoi(strings.TrimSuffix(s, field)) + if err != nil { + return -1, fmt.Errorf("malformed number in '%%d%s'", field) + } + + return v, nil +} + +func parseMigProfileFields(s string) (int, int, int, error) { + var err error + var c, g, gb int + + split := strings.SplitN(s, ".", 3) + if len(split) == 3 { + c, err = parseMigProfileField(split[0], "c") + if err != nil { + return -1, -1, -1, err + } + g, err = parseMigProfileField(split[1], "g") + if err != nil { + return -1, -1, -1, err + } + gb, err = parseMigProfileField(split[2], "gb") + if err != nil { + return -1, -1, -1, err + } + return c, g, gb, err + } + if len(split) == 2 { + g, err = parseMigProfileField(split[0], "g") + if err != nil { + return -1, -1, -1, err + } + gb, err = parseMigProfileField(split[1], "gb") + if err != nil { + return -1, -1, -1, err + } + return g, g, gb, nil + } + + return -1, -1, -1, fmt.Errorf("parsed wrong number of fields, expected 2 or 3") +} + +func parseMigProfileAttributes(s string) ([]string, error) { + attr := strings.Split(s, ",") + if len(attr) == 0 { + return nil, fmt.Errorf("empty attribute list") + } + unique := make(map[string]int) + for _, a := range attr { + if unique[a] > 0 { + return nil, fmt.Errorf("non unique attribute in list") + } + if a == "" { + return nil, fmt.Errorf("empty attribute in list") + } + if strings.TrimSpace(a) != a { + return nil, fmt.Errorf("leading or trailing spaces in attribute") + } + if a[0] >= '0' && a[0] <= '9' { + return nil, fmt.Errorf("attribute begins with a number") + } + for _, c := range a { + if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') { + return nil, fmt.Errorf("non alpha-numeric character or digit in attribute") + } + } + unique[a]++ + } + return attr, nil +} + +func getMigMemorySizeGB(totalDeviceMemory, migMemorySizeMB uint64) uint64 { + const fracDenominator = 8 + const oneMB = 1024 * 1024 + const oneGB = 1024 * 1024 * 1024 + fractionalGpuMem := (float64(migMemorySizeMB) * oneMB) / float64(totalDeviceMemory) + fractionalGpuMem = math.Ceil(fractionalGpuMem*fracDenominator) / fracDenominator + totalMemGB := float64((totalDeviceMemory + oneGB - 1) / oneGB) + return uint64(math.Round(fractionalGpuMem * totalMemGB)) +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/api.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/api.go new file mode 100644 index 00000000..bcc9cb69 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/api.go @@ -0,0 +1,43 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +// Interface provides the API to the info package. +type Interface interface { + PlatformResolver + PropertyExtractor +} + +// PlatformResolver defines a function to resolve the current platform. +type PlatformResolver interface { + ResolvePlatform() Platform +} + +// PropertyExtractor provides a set of functions to query capabilities of the +// system. +// +//go:generate moq -rm -fmt=goimports -out property-extractor_mock.go . PropertyExtractor +type PropertyExtractor interface { + HasDXCore() (bool, string) + HasNvml() (bool, string) + HasTegraFiles() (bool, string) + // Deprecated: Use HasTegraFiles instead. + IsTegraSystem() (bool, string) + // Deprecated: Use HasOnlyIntegratedGPUs + UsesOnlyNVGPUModule() (bool, string) + HasOnlyIntegratedGPUs() (bool, string) +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/builder.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/builder.go new file mode 100644 index 00000000..61684407 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/builder.go @@ -0,0 +1,78 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" +) + +type infolib struct { + PropertyExtractor + PlatformResolver +} + +type options struct { + logger basicLogger + root root + nvmllib nvml.Interface + devicelib device.Interface + + platform Platform + propertyExtractor PropertyExtractor +} + +// New creates a new instance of the 'info' interface. +func New(opts ...Option) Interface { + o := &options{} + for _, opt := range opts { + opt(o) + } + if o.logger == nil { + o.logger = &nullLogger{} + } + if o.root == "" { + o.root = "/" + } + if o.nvmllib == nil { + o.nvmllib = nvml.New( + nvml.WithLibraryPath(o.root.tryResolveLibrary("libnvidia-ml.so.1")), + ) + } + if o.devicelib == nil { + o.devicelib = device.New(o.nvmllib) + } + if o.platform == "" { + o.platform = PlatformAuto + } + if o.propertyExtractor == nil { + o.propertyExtractor = &propertyExtractor{ + root: o.root, + nvmllib: o.nvmllib, + devicelib: o.devicelib, + } + } + return &infolib{ + PlatformResolver: &platformResolver{ + logger: o.logger, + platform: o.platform, + propertyExtractor: o.propertyExtractor, + }, + PropertyExtractor: o.propertyExtractor, + } +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/logger.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/logger.go new file mode 100644 index 00000000..6a6f74ee --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/logger.go @@ -0,0 +1,28 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +type basicLogger interface { + Debugf(string, ...interface{}) + Infof(string, ...interface{}) +} + +type nullLogger struct{} + +func (n *nullLogger) Debugf(string, ...interface{}) {} + +func (n *nullLogger) Infof(string, ...interface{}) {} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/options.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/options.go new file mode 100644 index 00000000..e05c2bf7 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/options.go @@ -0,0 +1,70 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" +) + +// Option defines a function for passing options to the New() call. +type Option func(*options) + +// WithDeviceLib sets the device library for the library. +func WithDeviceLib(devicelib device.Interface) Option { + return func(i *options) { + i.devicelib = devicelib + } +} + +// WithLogger sets the logger for the library. +func WithLogger(logger basicLogger) Option { + return func(i *options) { + i.logger = logger + } +} + +// WithNvmlLib sets the nvml library for the library. +func WithNvmlLib(nvmllib nvml.Interface) Option { + return func(i *options) { + i.nvmllib = nvmllib + } +} + +// WithRoot provides a Option to set the root of the 'info' interface. +func WithRoot(r string) Option { + return func(i *options) { + i.root = root(r) + } +} + +// WithPropertyExtractor provides an Option to set the PropertyExtractor +// interface implementation. +// This is predominantly used for testing. +func WithPropertyExtractor(propertyExtractor PropertyExtractor) Option { + return func(i *options) { + i.propertyExtractor = propertyExtractor + } +} + +// WithPlatform provides an option to set the platform explicitly. +func WithPlatform(platform Platform) Option { + return func(i *options) { + i.platform = platform + } +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor.go new file mode 100644 index 00000000..20204713 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor.go @@ -0,0 +1,161 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +import ( + "fmt" + "os" + "strings" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" +) + +type propertyExtractor struct { + root root + nvmllib nvml.Interface + devicelib device.Interface +} + +var _ PropertyExtractor = &propertyExtractor{} + +// HasDXCore returns true if DXCore is detected on the system. +func (i *propertyExtractor) HasDXCore() (bool, string) { + const ( + libraryName = "libdxcore.so" + ) + if err := i.root.assertHasLibrary(libraryName); err != nil { + return false, fmt.Sprintf("could not load DXCore library: %v", err) + } + + return true, "found DXCore library" +} + +// HasNvml returns true if NVML is detected on the system. +func (i *propertyExtractor) HasNvml() (bool, string) { + const ( + libraryName = "libnvidia-ml.so.1" + ) + if err := i.root.assertHasLibrary(libraryName); err != nil { + return false, fmt.Sprintf("could not load NVML library: %v", err) + } + + return true, "found NVML library" +} + +// IsTegraSystem returns true if the system is detected as a Tegra-based system. +// Deprecated: Use HasTegraFiles instead. +func (i *propertyExtractor) IsTegraSystem() (bool, string) { + return i.HasTegraFiles() +} + +// HasTegraFiles returns true if tegra-based files are detected on the system. +func (i *propertyExtractor) HasTegraFiles() (bool, string) { + tegraReleaseFile := i.root.join("/etc/nv_tegra_release") + tegraFamilyFile := i.root.join("/sys/devices/soc0/family") + + if info, err := os.Stat(tegraReleaseFile); err == nil && !info.IsDir() { + return true, fmt.Sprintf("%v found", tegraReleaseFile) + } + + if info, err := os.Stat(tegraFamilyFile); err != nil || info.IsDir() { + return false, fmt.Sprintf("%v file not found", tegraFamilyFile) + } + + contents, err := os.ReadFile(tegraFamilyFile) + if err != nil { + return false, fmt.Sprintf("could not read %v", tegraFamilyFile) + } + + if strings.HasPrefix(strings.ToLower(string(contents)), "tegra") { + return true, fmt.Sprintf("%v has 'tegra' prefix", tegraFamilyFile) + } + + return false, fmt.Sprintf("%v has no 'tegra' prefix", tegraFamilyFile) +} + +// UsesOnlyNVGPUModule checks whether the only the nvgpu module is used. +// +// Deprecated: UsesOnlyNVGPUModule is deprecated, use HasOnlyIntegratedGPUs instead. +func (i *propertyExtractor) UsesOnlyNVGPUModule() (uses bool, reason string) { + return i.HasOnlyIntegratedGPUs() +} + +// HasOnlyIntegratedGPUs checks whether all GPUs are iGPUs that use NVML. +// +// As of Orin-based systems iGPUs also support limited NVML queries. +// In the absence of a robust API, we rely on heuristics to make this decision. +// +// The following device names are checked: +// +// GPU 0: Orin (nvgpu) (UUID: 54d0709b-558d-5a59-9c65-0c5fc14a21a4) +// GPU 0: NVIDIA Thor (UUID: 54d0709b-558d-5a59-9c65-0c5fc14a21a4) +// +// This function returns true if ALL devices are detected as iGPUs. +func (i *propertyExtractor) HasOnlyIntegratedGPUs() (uses bool, reason string) { + // We ensure that this function never panics + defer func() { + if err := recover(); err != nil { + uses = false + reason = fmt.Sprintf("panic: %v", err) + } + }() + + ret := i.nvmllib.Init() + if ret != nvml.SUCCESS { + return false, fmt.Sprintf("failed to initialize nvml: %v", ret) + } + defer func() { + _ = i.nvmllib.Shutdown() + }() + + var names []string + + err := i.devicelib.VisitDevices(func(i int, d device.Device) error { + name, ret := d.GetName() + if ret != nvml.SUCCESS { + return fmt.Errorf("device %v: %v", i, ret) + } + names = append(names, name) + return nil + }) + if err != nil { + return false, fmt.Sprintf("failed to get device names: %v", err) + } + + if len(names) == 0 { + return false, "no devices found" + } + + for _, name := range names { + if !isIntegratedGPUName(name) { + return false, fmt.Sprintf("device %q does not use nvgpu module", name) + } + } + return true, "all devices use nvgpu module" +} + +func isIntegratedGPUName(name string) bool { + if strings.Contains(name, "(nvgpu)") { + return true + } + if strings.Contains(name, "NVIDIA Thor") { + return true + } + return false +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor_mock.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor_mock.go new file mode 100644 index 00000000..bd7d4135 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/property-extractor_mock.go @@ -0,0 +1,252 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package info + +import ( + "sync" +) + +// Ensure, that PropertyExtractorMock does implement PropertyExtractor. +// If this is not the case, regenerate this file with moq. +var _ PropertyExtractor = &PropertyExtractorMock{} + +// PropertyExtractorMock is a mock implementation of PropertyExtractor. +// +// func TestSomethingThatUsesPropertyExtractor(t *testing.T) { +// +// // make and configure a mocked PropertyExtractor +// mockedPropertyExtractor := &PropertyExtractorMock{ +// HasDXCoreFunc: func() (bool, string) { +// panic("mock out the HasDXCore method") +// }, +// HasNvmlFunc: func() (bool, string) { +// panic("mock out the HasNvml method") +// }, +// HasOnlyIntegratedGPUsFunc: func() (bool, string) { +// panic("mock out the HasOnlyIntegratedGPUs method") +// }, +// HasTegraFilesFunc: func() (bool, string) { +// panic("mock out the HasTegraFiles method") +// }, +// IsTegraSystemFunc: func() (bool, string) { +// panic("mock out the IsTegraSystem method") +// }, +// UsesOnlyNVGPUModuleFunc: func() (bool, string) { +// panic("mock out the UsesOnlyNVGPUModule method") +// }, +// } +// +// // use mockedPropertyExtractor in code that requires PropertyExtractor +// // and then make assertions. +// +// } +type PropertyExtractorMock struct { + // HasDXCoreFunc mocks the HasDXCore method. + HasDXCoreFunc func() (bool, string) + + // HasNvmlFunc mocks the HasNvml method. + HasNvmlFunc func() (bool, string) + + // HasOnlyIntegratedGPUsFunc mocks the HasOnlyIntegratedGPUs method. + HasOnlyIntegratedGPUsFunc func() (bool, string) + + // HasTegraFilesFunc mocks the HasTegraFiles method. + HasTegraFilesFunc func() (bool, string) + + // IsTegraSystemFunc mocks the IsTegraSystem method. + IsTegraSystemFunc func() (bool, string) + + // UsesOnlyNVGPUModuleFunc mocks the UsesOnlyNVGPUModule method. + UsesOnlyNVGPUModuleFunc func() (bool, string) + + // calls tracks calls to the methods. + calls struct { + // HasDXCore holds details about calls to the HasDXCore method. + HasDXCore []struct { + } + // HasNvml holds details about calls to the HasNvml method. + HasNvml []struct { + } + // HasOnlyIntegratedGPUs holds details about calls to the HasOnlyIntegratedGPUs method. + HasOnlyIntegratedGPUs []struct { + } + // HasTegraFiles holds details about calls to the HasTegraFiles method. + HasTegraFiles []struct { + } + // IsTegraSystem holds details about calls to the IsTegraSystem method. + IsTegraSystem []struct { + } + // UsesOnlyNVGPUModule holds details about calls to the UsesOnlyNVGPUModule method. + UsesOnlyNVGPUModule []struct { + } + } + lockHasDXCore sync.RWMutex + lockHasNvml sync.RWMutex + lockHasOnlyIntegratedGPUs sync.RWMutex + lockHasTegraFiles sync.RWMutex + lockIsTegraSystem sync.RWMutex + lockUsesOnlyNVGPUModule sync.RWMutex +} + +// HasDXCore calls HasDXCoreFunc. +func (mock *PropertyExtractorMock) HasDXCore() (bool, string) { + if mock.HasDXCoreFunc == nil { + panic("PropertyExtractorMock.HasDXCoreFunc: method is nil but PropertyExtractor.HasDXCore was just called") + } + callInfo := struct { + }{} + mock.lockHasDXCore.Lock() + mock.calls.HasDXCore = append(mock.calls.HasDXCore, callInfo) + mock.lockHasDXCore.Unlock() + return mock.HasDXCoreFunc() +} + +// HasDXCoreCalls gets all the calls that were made to HasDXCore. +// Check the length with: +// +// len(mockedPropertyExtractor.HasDXCoreCalls()) +func (mock *PropertyExtractorMock) HasDXCoreCalls() []struct { +} { + var calls []struct { + } + mock.lockHasDXCore.RLock() + calls = mock.calls.HasDXCore + mock.lockHasDXCore.RUnlock() + return calls +} + +// HasNvml calls HasNvmlFunc. +func (mock *PropertyExtractorMock) HasNvml() (bool, string) { + if mock.HasNvmlFunc == nil { + panic("PropertyExtractorMock.HasNvmlFunc: method is nil but PropertyExtractor.HasNvml was just called") + } + callInfo := struct { + }{} + mock.lockHasNvml.Lock() + mock.calls.HasNvml = append(mock.calls.HasNvml, callInfo) + mock.lockHasNvml.Unlock() + return mock.HasNvmlFunc() +} + +// HasNvmlCalls gets all the calls that were made to HasNvml. +// Check the length with: +// +// len(mockedPropertyExtractor.HasNvmlCalls()) +func (mock *PropertyExtractorMock) HasNvmlCalls() []struct { +} { + var calls []struct { + } + mock.lockHasNvml.RLock() + calls = mock.calls.HasNvml + mock.lockHasNvml.RUnlock() + return calls +} + +// HasOnlyIntegratedGPUs calls HasOnlyIntegratedGPUsFunc. +func (mock *PropertyExtractorMock) HasOnlyIntegratedGPUs() (bool, string) { + if mock.HasOnlyIntegratedGPUsFunc == nil { + panic("PropertyExtractorMock.HasOnlyIntegratedGPUsFunc: method is nil but PropertyExtractor.HasOnlyIntegratedGPUs was just called") + } + callInfo := struct { + }{} + mock.lockHasOnlyIntegratedGPUs.Lock() + mock.calls.HasOnlyIntegratedGPUs = append(mock.calls.HasOnlyIntegratedGPUs, callInfo) + mock.lockHasOnlyIntegratedGPUs.Unlock() + return mock.HasOnlyIntegratedGPUsFunc() +} + +// HasOnlyIntegratedGPUsCalls gets all the calls that were made to HasOnlyIntegratedGPUs. +// Check the length with: +// +// len(mockedPropertyExtractor.HasOnlyIntegratedGPUsCalls()) +func (mock *PropertyExtractorMock) HasOnlyIntegratedGPUsCalls() []struct { +} { + var calls []struct { + } + mock.lockHasOnlyIntegratedGPUs.RLock() + calls = mock.calls.HasOnlyIntegratedGPUs + mock.lockHasOnlyIntegratedGPUs.RUnlock() + return calls +} + +// HasTegraFiles calls HasTegraFilesFunc. +func (mock *PropertyExtractorMock) HasTegraFiles() (bool, string) { + if mock.HasTegraFilesFunc == nil { + panic("PropertyExtractorMock.HasTegraFilesFunc: method is nil but PropertyExtractor.HasTegraFiles was just called") + } + callInfo := struct { + }{} + mock.lockHasTegraFiles.Lock() + mock.calls.HasTegraFiles = append(mock.calls.HasTegraFiles, callInfo) + mock.lockHasTegraFiles.Unlock() + return mock.HasTegraFilesFunc() +} + +// HasTegraFilesCalls gets all the calls that were made to HasTegraFiles. +// Check the length with: +// +// len(mockedPropertyExtractor.HasTegraFilesCalls()) +func (mock *PropertyExtractorMock) HasTegraFilesCalls() []struct { +} { + var calls []struct { + } + mock.lockHasTegraFiles.RLock() + calls = mock.calls.HasTegraFiles + mock.lockHasTegraFiles.RUnlock() + return calls +} + +// IsTegraSystem calls IsTegraSystemFunc. +func (mock *PropertyExtractorMock) IsTegraSystem() (bool, string) { + if mock.IsTegraSystemFunc == nil { + panic("PropertyExtractorMock.IsTegraSystemFunc: method is nil but PropertyExtractor.IsTegraSystem was just called") + } + callInfo := struct { + }{} + mock.lockIsTegraSystem.Lock() + mock.calls.IsTegraSystem = append(mock.calls.IsTegraSystem, callInfo) + mock.lockIsTegraSystem.Unlock() + return mock.IsTegraSystemFunc() +} + +// IsTegraSystemCalls gets all the calls that were made to IsTegraSystem. +// Check the length with: +// +// len(mockedPropertyExtractor.IsTegraSystemCalls()) +func (mock *PropertyExtractorMock) IsTegraSystemCalls() []struct { +} { + var calls []struct { + } + mock.lockIsTegraSystem.RLock() + calls = mock.calls.IsTegraSystem + mock.lockIsTegraSystem.RUnlock() + return calls +} + +// UsesOnlyNVGPUModule calls UsesOnlyNVGPUModuleFunc. +func (mock *PropertyExtractorMock) UsesOnlyNVGPUModule() (bool, string) { + if mock.UsesOnlyNVGPUModuleFunc == nil { + panic("PropertyExtractorMock.UsesOnlyNVGPUModuleFunc: method is nil but PropertyExtractor.UsesOnlyNVGPUModule was just called") + } + callInfo := struct { + }{} + mock.lockUsesOnlyNVGPUModule.Lock() + mock.calls.UsesOnlyNVGPUModule = append(mock.calls.UsesOnlyNVGPUModule, callInfo) + mock.lockUsesOnlyNVGPUModule.Unlock() + return mock.UsesOnlyNVGPUModuleFunc() +} + +// UsesOnlyNVGPUModuleCalls gets all the calls that were made to UsesOnlyNVGPUModule. +// Check the length with: +// +// len(mockedPropertyExtractor.UsesOnlyNVGPUModuleCalls()) +func (mock *PropertyExtractorMock) UsesOnlyNVGPUModuleCalls() []struct { +} { + var calls []struct { + } + mock.lockUsesOnlyNVGPUModule.RLock() + calls = mock.calls.UsesOnlyNVGPUModule + mock.lockUsesOnlyNVGPUModule.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/resolver.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/resolver.go new file mode 100644 index 00000000..0454d8a6 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/resolver.go @@ -0,0 +1,64 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +// Platform represents a supported plaform. +type Platform string + +const ( + PlatformAuto = Platform("auto") + PlatformNVML = Platform("nvml") + PlatformTegra = Platform("tegra") + PlatformWSL = Platform("wsl") + PlatformUnknown = Platform("unknown") +) + +type platformResolver struct { + logger basicLogger + platform Platform + propertyExtractor PropertyExtractor +} + +func (p platformResolver) ResolvePlatform() Platform { + if p.platform != PlatformAuto { + p.logger.Infof("Using requested platform '%s'", p.platform) + return p.platform + } + + hasDXCore, reason := p.propertyExtractor.HasDXCore() + p.logger.Debugf("Is WSL-based system? %v: %v", hasDXCore, reason) + + hasTegraFiles, reason := p.propertyExtractor.HasTegraFiles() + p.logger.Debugf("Is Tegra-based system? %v: %v", hasTegraFiles, reason) + + hasNVML, reason := p.propertyExtractor.HasNvml() + p.logger.Debugf("Is NVML-based system? %v: %v", hasNVML, reason) + + hasOnlyIntegratedGPUs, reason := p.propertyExtractor.HasOnlyIntegratedGPUs() + p.logger.Debugf("Has only integrated GPUs? %v: %v", hasOnlyIntegratedGPUs, reason) + + switch { + case hasDXCore: + return PlatformWSL + case (hasTegraFiles && !hasNVML), hasOnlyIntegratedGPUs: + return PlatformTegra + case hasNVML: + return PlatformNVML + default: + return PlatformUnknown + } +} diff --git a/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/root.go b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/root.go new file mode 100644 index 00000000..d38dc735 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvlib/pkg/nvlib/info/root.go @@ -0,0 +1,86 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package info + +import ( + "fmt" + "path/filepath" + + "github.com/NVIDIA/go-nvml/pkg/dl" +) + +// root represents a directory on the filesystem relative to which libraries +// such as the NVIDIA driver libraries can be found. +type root string + +func (r root) join(parts ...string) string { + return filepath.Join(append([]string{string(r)}, parts...)...) +} + +// assertHasLibrary returns an error if the specified library cannot be loaded. +func (r root) assertHasLibrary(libraryName string) error { + const ( + libraryLoadFlags = dl.RTLD_LAZY + ) + lib := dl.New(r.tryResolveLibrary(libraryName), libraryLoadFlags) + if err := lib.Open(); err != nil { + return err + } + defer lib.Close() + + return nil +} + +// tryResolveLibrary attempts to locate the specified library in the root. +// If the root is not specified, is "/", or the library cannot be found in the +// set of predefined paths, the input is returned as is. +func (r root) tryResolveLibrary(libraryName string) string { + if r == "" || r == "/" { + return libraryName + } + + librarySearchPaths := []string{ + "/usr/lib64", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib/aarch64-linux-gnu", + "/lib64", + "/lib/x86_64-linux-gnu", + "/lib/aarch64-linux-gnu", + } + + for _, d := range librarySearchPaths { + l := r.join(d, libraryName) + resolved, err := resolveLink(l) + if err != nil { + continue + } + return resolved + } + + return libraryName +} + +// resolveLink finds the target of a symlink or the file itself in the +// case of a regular file. +// This is equivalent to running `readlink -f ${l}`. +func resolveLink(l string) (string, error) { + resolved, err := filepath.EvalSymlinks(l) + if err != nil { + return "", fmt.Errorf("error resolving link '%v': %w", l, err) + } + return resolved, nil +} diff --git a/vendor/github.com/NVIDIA/go-nvml/LICENSE b/vendor/github.com/NVIDIA/go-nvml/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl.go b/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl.go new file mode 100644 index 00000000..34948a72 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl.go @@ -0,0 +1,117 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package dl + +import ( + "errors" + "fmt" + "runtime" + "unsafe" +) + +// #cgo LDFLAGS: -ldl +// #include +// #include +import "C" + +const ( + RTLD_LAZY = C.RTLD_LAZY + RTLD_NOW = C.RTLD_NOW + RTLD_GLOBAL = C.RTLD_GLOBAL + RTLD_LOCAL = C.RTLD_LOCAL + RTLD_NODELETE = C.RTLD_NODELETE + RTLD_NOLOAD = C.RTLD_NOLOAD +) + +type DynamicLibrary struct { + Name string + Flags int + handle unsafe.Pointer +} + +func New(name string, flags int) *DynamicLibrary { + return &DynamicLibrary{ + Name: name, + Flags: flags, + handle: nil, + } +} + +func withOSLock(action func() error) error { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + + return action() +} + +func dlError() error { + lastErr := C.dlerror() + if lastErr == nil { + return nil + } + return errors.New(C.GoString(lastErr)) +} + +func (dl *DynamicLibrary) Open() error { + name := C.CString(dl.Name) + defer C.free(unsafe.Pointer(name)) + + if err := withOSLock(func() error { + handle := C.dlopen(name, C.int(dl.Flags)) + if handle == nil { + return dlError() + } + dl.handle = handle + return nil + }); err != nil { + return err + } + return nil +} + +func (dl *DynamicLibrary) Close() error { + if dl.handle == nil { + return nil + } + if err := withOSLock(func() error { + if C.dlclose(dl.handle) != 0 { + return dlError() + } + dl.handle = nil + return nil + }); err != nil { + return err + } + return nil +} + +func (dl *DynamicLibrary) Lookup(symbol string) error { + sym := C.CString(symbol) + defer C.free(unsafe.Pointer(sym)) + + var pointer unsafe.Pointer + if err := withOSLock(func() error { + // Call dlError() to clear out any previous errors. + _ = dlError() + pointer = C.dlsym(dl.handle, sym) + if pointer == nil { + return fmt.Errorf("symbol %q not found: %w", symbol, dlError()) + } + return nil + }); err != nil { + return err + } + return nil +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl_linux.go b/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl_linux.go new file mode 100644 index 00000000..ae3acd07 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/dl/dl_linux.go @@ -0,0 +1,26 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dl + +// #cgo LDFLAGS: -ldl +// #include +// #include +import "C" + +const ( + RTLD_DEEPBIND = C.RTLD_DEEPBIND +) diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/api.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/api.go new file mode 100644 index 00000000..fdf27bda --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/api.go @@ -0,0 +1,56 @@ +/** +# Copyright 2023 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvml + +// ExtendedInterface defines a set of extensions to the core NVML API. +// +// TODO: For now the list of methods in this interface need to be kept in sync +// with the list of excluded methods for the Interface type in +// gen/nvml/generateapi.go. In the future we should automate this. +// +//go:generate moq -out mock/extendedinterface.go -pkg mock . ExtendedInterface:ExtendedInterface +type ExtendedInterface interface { + LookupSymbol(string) error +} + +// libraryOptions hold the paramaters than can be set by a LibraryOption +type libraryOptions struct { + path string + flags int +} + +// LibraryOption represents a functional option to configure the underlying NVML library +type LibraryOption func(*libraryOptions) + +// WithLibraryPath provides an option to set the library name to be used by the NVML library. +func WithLibraryPath(path string) LibraryOption { + return func(o *libraryOptions) { + o.path = path + } +} + +// SetLibraryOptions applies the specified options to the NVML library. +// If this is called when a library is already loaded, an error is raised. +func SetLibraryOptions(opts ...LibraryOption) error { + libnvml.Lock() + defer libnvml.Unlock() + if libnvml.refcount != 0 { + return errLibraryAlreadyLoaded + } + libnvml.init(opts...) + return nil +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers.h b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers.h new file mode 100644 index 00000000..b25c5e5d --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers.h @@ -0,0 +1,23 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +#include "nvml.h" +#include +#pragma once + +#define __CGOGEN 1 + diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers_static.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers_static.go new file mode 100644 index 00000000..1f30eaae --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/cgo_helpers_static.go @@ -0,0 +1,75 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import ( + "unsafe" +) + +import "C" + +var cgoAllocsUnknown = new(struct{}) + +type stringHeader struct { + Data unsafe.Pointer + Len int +} + +func clen(n []byte) int { + for i := 0; i < len(n); i++ { + if n[i] == 0 { + return i + } + } + return len(n) +} + +func uint32SliceToIntSlice(s []uint32) []int { + ret := make([]int, len(s)) + for i := range s { + ret[i] = int(s[i]) + } + return ret +} + +func convertSlice[T any, I any](input []T) []I { + output := make([]I, len(input)) + for i, obj := range input { + switch v := any(obj).(type) { + case I: + output[i] = v + } + } + return output +} + +// packPCharString creates a Go string backed by *C.char and avoids copying. +func packPCharString(p *C.char) (raw string) { + if p != nil && *p != 0 { + h := (*stringHeader)(unsafe.Pointer(&raw)) + h.Data = unsafe.Pointer(p) + for *p != 0 { + p = (*C.char)(unsafe.Pointer(uintptr(unsafe.Pointer(p)) + 1)) // p++ + } + h.Len = int(uintptr(unsafe.Pointer(p)) - uintptr(h.Data)) + } + return +} + +// unpackPCharString represents the data from Go string as *C.char and avoids copying. +func unpackPCharString(str string) (*C.char, *struct{}) { + h := (*stringHeader)(unsafe.Pointer(&str)) + return (*C.char)(h.Data), cgoAllocsUnknown +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const.go new file mode 100644 index 00000000..8a6a93c2 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const.go @@ -0,0 +1,2104 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +package nvml + +/* +#cgo linux LDFLAGS: -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files +#cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup +#cgo CFLAGS: -DNVML_NO_UNVERSIONED_FUNC_DEFS=1 +#include "nvml.h" +#include +#include "cgo_helpers.h" +*/ +import "C" + +const ( + // NO_UNVERSIONED_FUNC_DEFS as defined in go-nvml/:24 + NO_UNVERSIONED_FUNC_DEFS = 1 + // API_VERSION as defined in nvml/nvml.h + API_VERSION = 13 + // API_VERSION_STR as defined in nvml/nvml.h + API_VERSION_STR = "13" + // VALUE_NOT_AVAILABLE as defined in nvml/nvml.h + VALUE_NOT_AVAILABLE = -1 + // DEVICE_PCI_BUS_ID_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_PCI_BUS_ID_BUFFER_SIZE = 32 + // DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE as defined in nvml/nvml.h + DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE = 16 + // DEVICE_PCI_BUS_ID_LEGACY_FMT as defined in nvml/nvml.h + DEVICE_PCI_BUS_ID_LEGACY_FMT = "%04X:%02X:%02X.0" + // DEVICE_PCI_BUS_ID_FMT as defined in nvml/nvml.h + DEVICE_PCI_BUS_ID_FMT = "%08X:%02X:%02X.0" + // NVLINK_MAX_LINKS as defined in nvml/nvml.h + NVLINK_MAX_LINKS = 18 + // TOPOLOGY_CPU as defined in nvml/nvml.h + TOPOLOGY_CPU = 0 + // MAX_PHYSICAL_BRIDGE as defined in nvml/nvml.h + MAX_PHYSICAL_BRIDGE = 128 + // MAX_THERMAL_SENSORS_PER_GPU as defined in nvml/nvml.h + MAX_THERMAL_SENSORS_PER_GPU = 3 + // DEVICE_UUID_ASCII_LEN as defined in nvml/nvml.h + DEVICE_UUID_ASCII_LEN = 41 + // DEVICE_UUID_BINARY_LEN as defined in nvml/nvml.h + DEVICE_UUID_BINARY_LEN = 16 + // FlagDefault as defined in nvml/nvml.h + FlagDefault = 0 + // FlagForce as defined in nvml/nvml.h + FlagForce = 1 + // SINGLE_BIT_ECC as defined in nvml/nvml.h + SINGLE_BIT_ECC = 0 + // DOUBLE_BIT_ECC as defined in nvml/nvml.h + DOUBLE_BIT_ECC = 0 + // MAX_GPU_PERF_PSTATES as defined in nvml/nvml.h + MAX_GPU_PERF_PSTATES = 16 + // PERF_MODES_BUFFER_SIZE as defined in nvml/nvml.h + PERF_MODES_BUFFER_SIZE = 2048 + // POWER_MIZER_MODE_ADAPTIVE as defined in nvml/nvml.h + POWER_MIZER_MODE_ADAPTIVE = 0 + // POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE as defined in nvml/nvml.h + POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE = 1 + // POWER_MIZER_MODE_AUTO as defined in nvml/nvml.h + POWER_MIZER_MODE_AUTO = 2 + // POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE as defined in nvml/nvml.h + POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE = 3 + // GSP_FIRMWARE_VERSION_BUF_SIZE as defined in nvml/nvml.h + GSP_FIRMWARE_VERSION_BUF_SIZE = 64 + // DEVICE_ARCH_KEPLER as defined in nvml/nvml.h + DEVICE_ARCH_KEPLER = 2 + // DEVICE_ARCH_MAXWELL as defined in nvml/nvml.h + DEVICE_ARCH_MAXWELL = 3 + // DEVICE_ARCH_PASCAL as defined in nvml/nvml.h + DEVICE_ARCH_PASCAL = 4 + // DEVICE_ARCH_VOLTA as defined in nvml/nvml.h + DEVICE_ARCH_VOLTA = 5 + // DEVICE_ARCH_TURING as defined in nvml/nvml.h + DEVICE_ARCH_TURING = 6 + // DEVICE_ARCH_AMPERE as defined in nvml/nvml.h + DEVICE_ARCH_AMPERE = 7 + // DEVICE_ARCH_ADA as defined in nvml/nvml.h + DEVICE_ARCH_ADA = 8 + // DEVICE_ARCH_HOPPER as defined in nvml/nvml.h + DEVICE_ARCH_HOPPER = 9 + // DEVICE_ARCH_BLACKWELL as defined in nvml/nvml.h + DEVICE_ARCH_BLACKWELL = 10 + // DEVICE_ARCH_UNKNOWN as defined in nvml/nvml.h + DEVICE_ARCH_UNKNOWN = 4294967295 + // BUS_TYPE_UNKNOWN as defined in nvml/nvml.h + BUS_TYPE_UNKNOWN = 0 + // BUS_TYPE_PCI as defined in nvml/nvml.h + BUS_TYPE_PCI = 1 + // BUS_TYPE_PCIE as defined in nvml/nvml.h + BUS_TYPE_PCIE = 2 + // BUS_TYPE_FPCI as defined in nvml/nvml.h + BUS_TYPE_FPCI = 3 + // BUS_TYPE_AGP as defined in nvml/nvml.h + BUS_TYPE_AGP = 4 + // FAN_POLICY_TEMPERATURE_CONTINOUS_SW as defined in nvml/nvml.h + FAN_POLICY_TEMPERATURE_CONTINOUS_SW = 0 + // FAN_POLICY_MANUAL as defined in nvml/nvml.h + FAN_POLICY_MANUAL = 1 + // POWER_SOURCE_AC as defined in nvml/nvml.h + POWER_SOURCE_AC = 0 + // POWER_SOURCE_BATTERY as defined in nvml/nvml.h + POWER_SOURCE_BATTERY = 1 + // POWER_SOURCE_UNDERSIZED as defined in nvml/nvml.h + POWER_SOURCE_UNDERSIZED = 2 + // PCIE_LINK_MAX_SPEED_INVALID as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_INVALID = 0 + // PCIE_LINK_MAX_SPEED_2500MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_2500MBPS = 1 + // PCIE_LINK_MAX_SPEED_5000MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_5000MBPS = 2 + // PCIE_LINK_MAX_SPEED_8000MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_8000MBPS = 3 + // PCIE_LINK_MAX_SPEED_16000MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_16000MBPS = 4 + // PCIE_LINK_MAX_SPEED_32000MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_32000MBPS = 5 + // PCIE_LINK_MAX_SPEED_64000MBPS as defined in nvml/nvml.h + PCIE_LINK_MAX_SPEED_64000MBPS = 6 + // ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED as defined in nvml/nvml.h + ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED = 0 + // ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED as defined in nvml/nvml.h + ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED = 1 + // MAX_GPU_UTILIZATIONS as defined in nvml/nvml.h + MAX_GPU_UTILIZATIONS = 8 + // PCIE_ATOMICS_CAP_FETCHADD32 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_FETCHADD32 = 1 + // PCIE_ATOMICS_CAP_FETCHADD64 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_FETCHADD64 = 2 + // PCIE_ATOMICS_CAP_SWAP32 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_SWAP32 = 4 + // PCIE_ATOMICS_CAP_SWAP64 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_SWAP64 = 8 + // PCIE_ATOMICS_CAP_CAS32 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_CAS32 = 16 + // PCIE_ATOMICS_CAP_CAS64 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_CAS64 = 32 + // PCIE_ATOMICS_CAP_CAS128 as defined in nvml/nvml.h + PCIE_ATOMICS_CAP_CAS128 = 64 + // PCIE_ATOMICS_OPS_MAX as defined in nvml/nvml.h + PCIE_ATOMICS_OPS_MAX = 7 + // POWER_SCOPE_GPU as defined in nvml/nvml.h + POWER_SCOPE_GPU = 0 + // POWER_SCOPE_MODULE as defined in nvml/nvml.h + POWER_SCOPE_MODULE = 1 + // POWER_SCOPE_MEMORY as defined in nvml/nvml.h + POWER_SCOPE_MEMORY = 2 + // GRID_LICENSE_EXPIRY_NOT_AVAILABLE as defined in nvml/nvml.h + GRID_LICENSE_EXPIRY_NOT_AVAILABLE = 0 + // GRID_LICENSE_EXPIRY_INVALID as defined in nvml/nvml.h + GRID_LICENSE_EXPIRY_INVALID = 1 + // GRID_LICENSE_EXPIRY_VALID as defined in nvml/nvml.h + GRID_LICENSE_EXPIRY_VALID = 2 + // GRID_LICENSE_EXPIRY_NOT_APPLICABLE as defined in nvml/nvml.h + GRID_LICENSE_EXPIRY_NOT_APPLICABLE = 3 + // GRID_LICENSE_EXPIRY_PERMANENT as defined in nvml/nvml.h + GRID_LICENSE_EXPIRY_PERMANENT = 4 + // GRID_LICENSE_BUFFER_SIZE as defined in nvml/nvml.h + GRID_LICENSE_BUFFER_SIZE = 128 + // VGPU_NAME_BUFFER_SIZE as defined in nvml/nvml.h + VGPU_NAME_BUFFER_SIZE = 64 + // GRID_LICENSE_FEATURE_MAX_COUNT as defined in nvml/nvml.h + GRID_LICENSE_FEATURE_MAX_COUNT = 3 + // INVALID_VGPU_PLACEMENT_ID as defined in nvml/nvml.h + INVALID_VGPU_PLACEMENT_ID = 65535 + // VGPU_PGPU_HETEROGENEOUS_MODE as defined in nvml/nvml.h + VGPU_PGPU_HETEROGENEOUS_MODE = 0 + // VGPU_PGPU_HOMOGENEOUS_MODE as defined in nvml/nvml.h + VGPU_PGPU_HOMOGENEOUS_MODE = 1 + // VGPU_SCHEDULER_POLICY_UNKNOWN as defined in nvml/nvml.h + VGPU_SCHEDULER_POLICY_UNKNOWN = 0 + // VGPU_SCHEDULER_POLICY_BEST_EFFORT as defined in nvml/nvml.h + VGPU_SCHEDULER_POLICY_BEST_EFFORT = 1 + // VGPU_SCHEDULER_POLICY_EQUAL_SHARE as defined in nvml/nvml.h + VGPU_SCHEDULER_POLICY_EQUAL_SHARE = 2 + // VGPU_SCHEDULER_POLICY_FIXED_SHARE as defined in nvml/nvml.h + VGPU_SCHEDULER_POLICY_FIXED_SHARE = 3 + // SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT as defined in nvml/nvml.h + SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT = 3 + // SCHEDULER_SW_MAX_LOG_ENTRIES as defined in nvml/nvml.h + SCHEDULER_SW_MAX_LOG_ENTRIES = 200 + // VGPU_SCHEDULER_ARR_DEFAULT as defined in nvml/nvml.h + VGPU_SCHEDULER_ARR_DEFAULT = 0 + // VGPU_SCHEDULER_ARR_DISABLE as defined in nvml/nvml.h + VGPU_SCHEDULER_ARR_DISABLE = 1 + // VGPU_SCHEDULER_ARR_ENABLE as defined in nvml/nvml.h + VGPU_SCHEDULER_ARR_ENABLE = 2 + // VGPU_SCHEDULER_ENGINE_TYPE_GRAPHICS as defined in nvml/nvml.h + VGPU_SCHEDULER_ENGINE_TYPE_GRAPHICS = 1 + // GRID_LICENSE_STATE_UNKNOWN as defined in nvml/nvml.h + GRID_LICENSE_STATE_UNKNOWN = 0 + // GRID_LICENSE_STATE_UNINITIALIZED as defined in nvml/nvml.h + GRID_LICENSE_STATE_UNINITIALIZED = 1 + // GRID_LICENSE_STATE_UNLICENSED_UNRESTRICTED as defined in nvml/nvml.h + GRID_LICENSE_STATE_UNLICENSED_UNRESTRICTED = 2 + // GRID_LICENSE_STATE_UNLICENSED_RESTRICTED as defined in nvml/nvml.h + GRID_LICENSE_STATE_UNLICENSED_RESTRICTED = 3 + // GRID_LICENSE_STATE_UNLICENSED as defined in nvml/nvml.h + GRID_LICENSE_STATE_UNLICENSED = 4 + // GRID_LICENSE_STATE_LICENSED as defined in nvml/nvml.h + GRID_LICENSE_STATE_LICENSED = 5 + // FI_DEV_ECC_CURRENT as defined in nvml/nvml.h + FI_DEV_ECC_CURRENT = 1 + // FI_DEV_ECC_PENDING as defined in nvml/nvml.h + FI_DEV_ECC_PENDING = 2 + // FI_DEV_ECC_SBE_VOL_TOTAL as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_TOTAL = 3 + // FI_DEV_ECC_DBE_VOL_TOTAL as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_TOTAL = 4 + // FI_DEV_ECC_SBE_AGG_TOTAL as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_TOTAL = 5 + // FI_DEV_ECC_DBE_AGG_TOTAL as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_TOTAL = 6 + // FI_DEV_ECC_SBE_VOL_L1 as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_L1 = 7 + // FI_DEV_ECC_DBE_VOL_L1 as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_L1 = 8 + // FI_DEV_ECC_SBE_VOL_L2 as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_L2 = 9 + // FI_DEV_ECC_DBE_VOL_L2 as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_L2 = 10 + // FI_DEV_ECC_SBE_VOL_DEV as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_DEV = 11 + // FI_DEV_ECC_DBE_VOL_DEV as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_DEV = 12 + // FI_DEV_ECC_SBE_VOL_REG as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_REG = 13 + // FI_DEV_ECC_DBE_VOL_REG as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_REG = 14 + // FI_DEV_ECC_SBE_VOL_TEX as defined in nvml/nvml.h + FI_DEV_ECC_SBE_VOL_TEX = 15 + // FI_DEV_ECC_DBE_VOL_TEX as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_TEX = 16 + // FI_DEV_ECC_DBE_VOL_CBU as defined in nvml/nvml.h + FI_DEV_ECC_DBE_VOL_CBU = 17 + // FI_DEV_ECC_SBE_AGG_L1 as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_L1 = 18 + // FI_DEV_ECC_DBE_AGG_L1 as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_L1 = 19 + // FI_DEV_ECC_SBE_AGG_L2 as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_L2 = 20 + // FI_DEV_ECC_DBE_AGG_L2 as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_L2 = 21 + // FI_DEV_ECC_SBE_AGG_DEV as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_DEV = 22 + // FI_DEV_ECC_DBE_AGG_DEV as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_DEV = 23 + // FI_DEV_ECC_SBE_AGG_REG as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_REG = 24 + // FI_DEV_ECC_DBE_AGG_REG as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_REG = 25 + // FI_DEV_ECC_SBE_AGG_TEX as defined in nvml/nvml.h + FI_DEV_ECC_SBE_AGG_TEX = 26 + // FI_DEV_ECC_DBE_AGG_TEX as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_TEX = 27 + // FI_DEV_ECC_DBE_AGG_CBU as defined in nvml/nvml.h + FI_DEV_ECC_DBE_AGG_CBU = 28 + // FI_DEV_RETIRED_SBE as defined in nvml/nvml.h + FI_DEV_RETIRED_SBE = 29 + // FI_DEV_RETIRED_DBE as defined in nvml/nvml.h + FI_DEV_RETIRED_DBE = 30 + // FI_DEV_RETIRED_PENDING as defined in nvml/nvml.h + FI_DEV_RETIRED_PENDING = 31 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L0 = 32 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L1 = 33 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L2 = 34 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L3 = 35 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L4 = 36 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L5 = 37 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_TOTAL = 38 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L0 = 39 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L1 = 40 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L2 = 41 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L3 = 42 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L4 = 43 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L5 = 44 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_TOTAL = 45 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L0 = 46 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L1 = 47 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L2 = 48 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L3 = 49 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L4 = 50 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L5 = 51 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_TOTAL = 52 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L0 = 53 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L1 = 54 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L2 = 55 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L3 = 56 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L4 = 57 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L5 = 58 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_TOTAL = 59 + // FI_DEV_NVLINK_BANDWIDTH_C0_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L0 = 60 + // FI_DEV_NVLINK_BANDWIDTH_C0_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L1 = 61 + // FI_DEV_NVLINK_BANDWIDTH_C0_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L2 = 62 + // FI_DEV_NVLINK_BANDWIDTH_C0_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L3 = 63 + // FI_DEV_NVLINK_BANDWIDTH_C0_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L4 = 64 + // FI_DEV_NVLINK_BANDWIDTH_C0_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L5 = 65 + // FI_DEV_NVLINK_BANDWIDTH_C0_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_TOTAL = 66 + // FI_DEV_NVLINK_BANDWIDTH_C1_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L0 = 67 + // FI_DEV_NVLINK_BANDWIDTH_C1_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L1 = 68 + // FI_DEV_NVLINK_BANDWIDTH_C1_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L2 = 69 + // FI_DEV_NVLINK_BANDWIDTH_C1_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L3 = 70 + // FI_DEV_NVLINK_BANDWIDTH_C1_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L4 = 71 + // FI_DEV_NVLINK_BANDWIDTH_C1_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L5 = 72 + // FI_DEV_NVLINK_BANDWIDTH_C1_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_TOTAL = 73 + // FI_DEV_PERF_POLICY_POWER as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_POWER = 74 + // FI_DEV_PERF_POLICY_THERMAL as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_THERMAL = 75 + // FI_DEV_PERF_POLICY_SYNC_BOOST as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_SYNC_BOOST = 76 + // FI_DEV_PERF_POLICY_BOARD_LIMIT as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_BOARD_LIMIT = 77 + // FI_DEV_PERF_POLICY_LOW_UTILIZATION as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_LOW_UTILIZATION = 78 + // FI_DEV_PERF_POLICY_RELIABILITY as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_RELIABILITY = 79 + // FI_DEV_PERF_POLICY_TOTAL_APP_CLOCKS as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_TOTAL_APP_CLOCKS = 80 + // FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS as defined in nvml/nvml.h + FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS = 81 + // FI_DEV_MEMORY_TEMP as defined in nvml/nvml.h + FI_DEV_MEMORY_TEMP = 82 + // FI_DEV_TOTAL_ENERGY_CONSUMPTION as defined in nvml/nvml.h + FI_DEV_TOTAL_ENERGY_CONSUMPTION = 83 + // FI_DEV_NVLINK_SPEED_MBPS_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L0 = 84 + // FI_DEV_NVLINK_SPEED_MBPS_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L1 = 85 + // FI_DEV_NVLINK_SPEED_MBPS_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L2 = 86 + // FI_DEV_NVLINK_SPEED_MBPS_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L3 = 87 + // FI_DEV_NVLINK_SPEED_MBPS_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L4 = 88 + // FI_DEV_NVLINK_SPEED_MBPS_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L5 = 89 + // FI_DEV_NVLINK_SPEED_MBPS_COMMON as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_COMMON = 90 + // FI_DEV_NVLINK_LINK_COUNT as defined in nvml/nvml.h + FI_DEV_NVLINK_LINK_COUNT = 91 + // FI_DEV_RETIRED_PENDING_SBE as defined in nvml/nvml.h + FI_DEV_RETIRED_PENDING_SBE = 92 + // FI_DEV_RETIRED_PENDING_DBE as defined in nvml/nvml.h + FI_DEV_RETIRED_PENDING_DBE = 93 + // FI_DEV_PCIE_REPLAY_COUNTER as defined in nvml/nvml.h + FI_DEV_PCIE_REPLAY_COUNTER = 94 + // FI_DEV_PCIE_REPLAY_ROLLOVER_COUNTER as defined in nvml/nvml.h + FI_DEV_PCIE_REPLAY_ROLLOVER_COUNTER = 95 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L6 = 96 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L7 = 97 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L8 = 98 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L9 = 99 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L10 = 100 + // FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L11 = 101 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L6 = 102 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L7 = 103 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L8 = 104 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L9 = 105 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L10 = 106 + // FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L11 = 107 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L6 = 108 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L7 = 109 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L8 = 110 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L9 = 111 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L10 = 112 + // FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L11 = 113 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L6 = 114 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L7 = 115 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L8 = 116 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L9 = 117 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L10 = 118 + // FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L11 = 119 + // FI_DEV_NVLINK_BANDWIDTH_C0_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L6 = 120 + // FI_DEV_NVLINK_BANDWIDTH_C0_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L7 = 121 + // FI_DEV_NVLINK_BANDWIDTH_C0_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L8 = 122 + // FI_DEV_NVLINK_BANDWIDTH_C0_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L9 = 123 + // FI_DEV_NVLINK_BANDWIDTH_C0_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L10 = 124 + // FI_DEV_NVLINK_BANDWIDTH_C0_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C0_L11 = 125 + // FI_DEV_NVLINK_BANDWIDTH_C1_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L6 = 126 + // FI_DEV_NVLINK_BANDWIDTH_C1_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L7 = 127 + // FI_DEV_NVLINK_BANDWIDTH_C1_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L8 = 128 + // FI_DEV_NVLINK_BANDWIDTH_C1_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L9 = 129 + // FI_DEV_NVLINK_BANDWIDTH_C1_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L10 = 130 + // FI_DEV_NVLINK_BANDWIDTH_C1_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_BANDWIDTH_C1_L11 = 131 + // FI_DEV_NVLINK_SPEED_MBPS_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L6 = 132 + // FI_DEV_NVLINK_SPEED_MBPS_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L7 = 133 + // FI_DEV_NVLINK_SPEED_MBPS_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L8 = 134 + // FI_DEV_NVLINK_SPEED_MBPS_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L9 = 135 + // FI_DEV_NVLINK_SPEED_MBPS_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L10 = 136 + // FI_DEV_NVLINK_SPEED_MBPS_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_SPEED_MBPS_L11 = 137 + // FI_DEV_NVLINK_THROUGHPUT_DATA_TX as defined in nvml/nvml.h + FI_DEV_NVLINK_THROUGHPUT_DATA_TX = 138 + // FI_DEV_NVLINK_THROUGHPUT_DATA_RX as defined in nvml/nvml.h + FI_DEV_NVLINK_THROUGHPUT_DATA_RX = 139 + // FI_DEV_NVLINK_THROUGHPUT_RAW_TX as defined in nvml/nvml.h + FI_DEV_NVLINK_THROUGHPUT_RAW_TX = 140 + // FI_DEV_NVLINK_THROUGHPUT_RAW_RX as defined in nvml/nvml.h + FI_DEV_NVLINK_THROUGHPUT_RAW_RX = 141 + // FI_DEV_REMAPPED_COR as defined in nvml/nvml.h + FI_DEV_REMAPPED_COR = 142 + // FI_DEV_REMAPPED_UNC as defined in nvml/nvml.h + FI_DEV_REMAPPED_UNC = 143 + // FI_DEV_REMAPPED_PENDING as defined in nvml/nvml.h + FI_DEV_REMAPPED_PENDING = 144 + // FI_DEV_REMAPPED_FAILURE as defined in nvml/nvml.h + FI_DEV_REMAPPED_FAILURE = 145 + // FI_DEV_NVLINK_REMOTE_NVLINK_ID as defined in nvml/nvml.h + FI_DEV_NVLINK_REMOTE_NVLINK_ID = 146 + // FI_DEV_NVSWITCH_CONNECTED_LINK_COUNT as defined in nvml/nvml.h + FI_DEV_NVSWITCH_CONNECTED_LINK_COUNT = 147 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L0 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L0 = 148 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L1 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L1 = 149 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L2 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L2 = 150 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L3 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L3 = 151 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L4 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L4 = 152 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L5 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L5 = 153 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L6 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L6 = 154 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L7 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L7 = 155 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L8 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L8 = 156 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L9 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L9 = 157 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L10 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L10 = 158 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L11 as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L11 = 159 + // FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_TOTAL as defined in nvml/nvml.h + FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_TOTAL = 160 + // FI_DEV_NVLINK_ERROR_DL_REPLAY as defined in nvml/nvml.h + FI_DEV_NVLINK_ERROR_DL_REPLAY = 161 + // FI_DEV_NVLINK_ERROR_DL_RECOVERY as defined in nvml/nvml.h + FI_DEV_NVLINK_ERROR_DL_RECOVERY = 162 + // FI_DEV_NVLINK_ERROR_DL_CRC as defined in nvml/nvml.h + FI_DEV_NVLINK_ERROR_DL_CRC = 163 + // FI_DEV_NVLINK_GET_SPEED as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_SPEED = 164 + // FI_DEV_NVLINK_GET_STATE as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_STATE = 165 + // FI_DEV_NVLINK_GET_VERSION as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_VERSION = 166 + // FI_DEV_NVLINK_GET_POWER_STATE as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_STATE = 167 + // FI_DEV_NVLINK_GET_POWER_THRESHOLD as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_THRESHOLD = 168 + // FI_DEV_PCIE_L0_TO_RECOVERY_COUNTER as defined in nvml/nvml.h + FI_DEV_PCIE_L0_TO_RECOVERY_COUNTER = 169 + // FI_DEV_C2C_LINK_COUNT as defined in nvml/nvml.h + FI_DEV_C2C_LINK_COUNT = 170 + // FI_DEV_C2C_LINK_GET_STATUS as defined in nvml/nvml.h + FI_DEV_C2C_LINK_GET_STATUS = 171 + // FI_DEV_C2C_LINK_GET_MAX_BW as defined in nvml/nvml.h + FI_DEV_C2C_LINK_GET_MAX_BW = 172 + // FI_DEV_PCIE_COUNT_CORRECTABLE_ERRORS as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_CORRECTABLE_ERRORS = 173 + // FI_DEV_PCIE_COUNT_NAKS_RECEIVED as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_NAKS_RECEIVED = 174 + // FI_DEV_PCIE_COUNT_RECEIVER_ERROR as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_RECEIVER_ERROR = 175 + // FI_DEV_PCIE_COUNT_BAD_TLP as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_BAD_TLP = 176 + // FI_DEV_PCIE_COUNT_NAKS_SENT as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_NAKS_SENT = 177 + // FI_DEV_PCIE_COUNT_BAD_DLLP as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_BAD_DLLP = 178 + // FI_DEV_PCIE_COUNT_NON_FATAL_ERROR as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_NON_FATAL_ERROR = 179 + // FI_DEV_PCIE_COUNT_FATAL_ERROR as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_FATAL_ERROR = 180 + // FI_DEV_PCIE_COUNT_UNSUPPORTED_REQ as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_UNSUPPORTED_REQ = 181 + // FI_DEV_PCIE_COUNT_LCRC_ERROR as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_LCRC_ERROR = 182 + // FI_DEV_PCIE_COUNT_LANE_ERROR as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_LANE_ERROR = 183 + // FI_DEV_IS_RESETLESS_MIG_SUPPORTED as defined in nvml/nvml.h + FI_DEV_IS_RESETLESS_MIG_SUPPORTED = 184 + // FI_DEV_POWER_AVERAGE as defined in nvml/nvml.h + FI_DEV_POWER_AVERAGE = 185 + // FI_DEV_POWER_INSTANT as defined in nvml/nvml.h + FI_DEV_POWER_INSTANT = 186 + // FI_DEV_POWER_MIN_LIMIT as defined in nvml/nvml.h + FI_DEV_POWER_MIN_LIMIT = 187 + // FI_DEV_POWER_MAX_LIMIT as defined in nvml/nvml.h + FI_DEV_POWER_MAX_LIMIT = 188 + // FI_DEV_POWER_DEFAULT_LIMIT as defined in nvml/nvml.h + FI_DEV_POWER_DEFAULT_LIMIT = 189 + // FI_DEV_POWER_CURRENT_LIMIT as defined in nvml/nvml.h + FI_DEV_POWER_CURRENT_LIMIT = 190 + // FI_DEV_ENERGY as defined in nvml/nvml.h + FI_DEV_ENERGY = 191 + // FI_DEV_POWER_REQUESTED_LIMIT as defined in nvml/nvml.h + FI_DEV_POWER_REQUESTED_LIMIT = 192 + // FI_DEV_TEMPERATURE_SHUTDOWN_TLIMIT as defined in nvml/nvml.h + FI_DEV_TEMPERATURE_SHUTDOWN_TLIMIT = 193 + // FI_DEV_TEMPERATURE_SLOWDOWN_TLIMIT as defined in nvml/nvml.h + FI_DEV_TEMPERATURE_SLOWDOWN_TLIMIT = 194 + // FI_DEV_TEMPERATURE_MEM_MAX_TLIMIT as defined in nvml/nvml.h + FI_DEV_TEMPERATURE_MEM_MAX_TLIMIT = 195 + // FI_DEV_TEMPERATURE_GPU_MAX_TLIMIT as defined in nvml/nvml.h + FI_DEV_TEMPERATURE_GPU_MAX_TLIMIT = 196 + // FI_DEV_PCIE_COUNT_TX_BYTES as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_TX_BYTES = 197 + // FI_DEV_PCIE_COUNT_RX_BYTES as defined in nvml/nvml.h + FI_DEV_PCIE_COUNT_RX_BYTES = 198 + // FI_DEV_IS_MIG_MODE_INDEPENDENT_MIG_QUERY_CAPABLE as defined in nvml/nvml.h + FI_DEV_IS_MIG_MODE_INDEPENDENT_MIG_QUERY_CAPABLE = 199 + // FI_DEV_NVLINK_GET_POWER_THRESHOLD_MAX as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_THRESHOLD_MAX = 200 + // FI_DEV_NVLINK_COUNT_XMIT_PACKETS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_XMIT_PACKETS = 201 + // FI_DEV_NVLINK_COUNT_XMIT_BYTES as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_XMIT_BYTES = 202 + // FI_DEV_NVLINK_COUNT_RCV_PACKETS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RCV_PACKETS = 203 + // FI_DEV_NVLINK_COUNT_RCV_BYTES as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RCV_BYTES = 204 + // FI_DEV_NVLINK_COUNT_VL15_DROPPED as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_VL15_DROPPED = 205 + // FI_DEV_NVLINK_COUNT_MALFORMED_PACKET_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_MALFORMED_PACKET_ERRORS = 206 + // FI_DEV_NVLINK_COUNT_BUFFER_OVERRUN_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_BUFFER_OVERRUN_ERRORS = 207 + // FI_DEV_NVLINK_COUNT_RCV_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RCV_ERRORS = 208 + // FI_DEV_NVLINK_COUNT_RCV_REMOTE_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RCV_REMOTE_ERRORS = 209 + // FI_DEV_NVLINK_COUNT_RCV_GENERAL_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RCV_GENERAL_ERRORS = 210 + // FI_DEV_NVLINK_COUNT_LOCAL_LINK_INTEGRITY_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_LOCAL_LINK_INTEGRITY_ERRORS = 211 + // FI_DEV_NVLINK_COUNT_XMIT_DISCARDS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_XMIT_DISCARDS = 212 + // FI_DEV_NVLINK_COUNT_LINK_RECOVERY_SUCCESSFUL_EVENTS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_LINK_RECOVERY_SUCCESSFUL_EVENTS = 213 + // FI_DEV_NVLINK_COUNT_LINK_RECOVERY_FAILED_EVENTS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_LINK_RECOVERY_FAILED_EVENTS = 214 + // FI_DEV_NVLINK_COUNT_LINK_RECOVERY_EVENTS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_LINK_RECOVERY_EVENTS = 215 + // FI_DEV_NVLINK_COUNT_RAW_BER_LANE0 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RAW_BER_LANE0 = 216 + // FI_DEV_NVLINK_COUNT_RAW_BER_LANE1 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RAW_BER_LANE1 = 217 + // FI_DEV_NVLINK_COUNT_RAW_BER as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_RAW_BER = 218 + // FI_DEV_NVLINK_COUNT_EFFECTIVE_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_EFFECTIVE_ERRORS = 219 + // FI_DEV_NVLINK_COUNT_EFFECTIVE_BER as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_EFFECTIVE_BER = 220 + // FI_DEV_NVLINK_COUNT_SYMBOL_ERRORS as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_SYMBOL_ERRORS = 221 + // FI_DEV_NVLINK_COUNT_SYMBOL_BER as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_SYMBOL_BER = 222 + // FI_DEV_NVLINK_GET_POWER_THRESHOLD_MIN as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_THRESHOLD_MIN = 223 + // FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS = 224 + // FI_DEV_NVLINK_GET_POWER_THRESHOLD_SUPPORTED as defined in nvml/nvml.h + FI_DEV_NVLINK_GET_POWER_THRESHOLD_SUPPORTED = 225 + // FI_DEV_RESET_STATUS as defined in nvml/nvml.h + FI_DEV_RESET_STATUS = 226 + // FI_DEV_DRAIN_AND_RESET_STATUS as defined in nvml/nvml.h + FI_DEV_DRAIN_AND_RESET_STATUS = 227 + // FI_DEV_PCIE_OUTBOUND_ATOMICS_MASK as defined in nvml/nvml.h + FI_DEV_PCIE_OUTBOUND_ATOMICS_MASK = 228 + // FI_DEV_PCIE_INBOUND_ATOMICS_MASK as defined in nvml/nvml.h + FI_DEV_PCIE_INBOUND_ATOMICS_MASK = 229 + // FI_DEV_GET_GPU_RECOVERY_ACTION as defined in nvml/nvml.h + FI_DEV_GET_GPU_RECOVERY_ACTION = 230 + // FI_DEV_C2C_LINK_ERROR_INTR as defined in nvml/nvml.h + FI_DEV_C2C_LINK_ERROR_INTR = 231 + // FI_DEV_C2C_LINK_ERROR_REPLAY as defined in nvml/nvml.h + FI_DEV_C2C_LINK_ERROR_REPLAY = 232 + // FI_DEV_C2C_LINK_ERROR_REPLAY_B2B as defined in nvml/nvml.h + FI_DEV_C2C_LINK_ERROR_REPLAY_B2B = 233 + // FI_DEV_C2C_LINK_POWER_STATE as defined in nvml/nvml.h + FI_DEV_C2C_LINK_POWER_STATE = 234 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_0 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_0 = 235 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_1 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_1 = 236 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_2 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_2 = 237 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_3 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_3 = 238 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_4 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_4 = 239 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_5 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_5 = 240 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_6 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_6 = 241 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_7 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_7 = 242 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_8 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_8 = 243 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_9 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_9 = 244 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_10 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_10 = 245 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_11 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_11 = 246 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_12 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_12 = 247 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_13 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_13 = 248 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_14 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_14 = 249 + // FI_DEV_NVLINK_COUNT_FEC_HISTORY_15 as defined in nvml/nvml.h + FI_DEV_NVLINK_COUNT_FEC_HISTORY_15 = 250 + // FI_DEV_CLOCKS_EVENT_REASON_SW_POWER_CAP as defined in nvml/nvml.h + FI_DEV_CLOCKS_EVENT_REASON_SW_POWER_CAP = 74 + // FI_DEV_CLOCKS_EVENT_REASON_SYNC_BOOST as defined in nvml/nvml.h + FI_DEV_CLOCKS_EVENT_REASON_SYNC_BOOST = 76 + // FI_DEV_CLOCKS_EVENT_REASON_SW_THERM_SLOWDOWN as defined in nvml/nvml.h + FI_DEV_CLOCKS_EVENT_REASON_SW_THERM_SLOWDOWN = 251 + // FI_DEV_CLOCKS_EVENT_REASON_HW_THERM_SLOWDOWN as defined in nvml/nvml.h + FI_DEV_CLOCKS_EVENT_REASON_HW_THERM_SLOWDOWN = 252 + // FI_DEV_CLOCKS_EVENT_REASON_HW_POWER_BRAKE_SLOWDOWN as defined in nvml/nvml.h + FI_DEV_CLOCKS_EVENT_REASON_HW_POWER_BRAKE_SLOWDOWN = 253 + // FI_DEV_POWER_SYNC_BALANCING_FREQ as defined in nvml/nvml.h + FI_DEV_POWER_SYNC_BALANCING_FREQ = 254 + // FI_DEV_POWER_SYNC_BALANCING_AF as defined in nvml/nvml.h + FI_DEV_POWER_SYNC_BALANCING_AF = 255 + // FI_PWR_SMOOTHING_ENABLED as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ENABLED = 256 + // FI_PWR_SMOOTHING_PRIV_LVL as defined in nvml/nvml.h + FI_PWR_SMOOTHING_PRIV_LVL = 257 + // FI_PWR_SMOOTHING_IMM_RAMP_DOWN_ENABLED as defined in nvml/nvml.h + FI_PWR_SMOOTHING_IMM_RAMP_DOWN_ENABLED = 258 + // FI_PWR_SMOOTHING_APPLIED_TMP_CEIL as defined in nvml/nvml.h + FI_PWR_SMOOTHING_APPLIED_TMP_CEIL = 259 + // FI_PWR_SMOOTHING_APPLIED_TMP_FLOOR as defined in nvml/nvml.h + FI_PWR_SMOOTHING_APPLIED_TMP_FLOOR = 260 + // FI_PWR_SMOOTHING_MAX_PERCENT_TMP_FLOOR_SETTING as defined in nvml/nvml.h + FI_PWR_SMOOTHING_MAX_PERCENT_TMP_FLOOR_SETTING = 261 + // FI_PWR_SMOOTHING_MIN_PERCENT_TMP_FLOOR_SETTING as defined in nvml/nvml.h + FI_PWR_SMOOTHING_MIN_PERCENT_TMP_FLOOR_SETTING = 262 + // FI_PWR_SMOOTHING_HW_CIRCUITRY_PERCENT_LIFETIME_REMAINING as defined in nvml/nvml.h + FI_PWR_SMOOTHING_HW_CIRCUITRY_PERCENT_LIFETIME_REMAINING = 263 + // FI_PWR_SMOOTHING_MAX_NUM_PRESET_PROFILES as defined in nvml/nvml.h + FI_PWR_SMOOTHING_MAX_NUM_PRESET_PROFILES = 264 + // FI_PWR_SMOOTHING_PROFILE_PERCENT_TMP_FLOOR as defined in nvml/nvml.h + FI_PWR_SMOOTHING_PROFILE_PERCENT_TMP_FLOOR = 265 + // FI_PWR_SMOOTHING_PROFILE_RAMP_UP_RATE as defined in nvml/nvml.h + FI_PWR_SMOOTHING_PROFILE_RAMP_UP_RATE = 266 + // FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_RATE as defined in nvml/nvml.h + FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_RATE = 267 + // FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_HYST_VAL as defined in nvml/nvml.h + FI_PWR_SMOOTHING_PROFILE_RAMP_DOWN_HYST_VAL = 268 + // FI_PWR_SMOOTHING_ACTIVE_PRESET_PROFILE as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ACTIVE_PRESET_PROFILE = 269 + // FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PERCENT_TMP_FLOOR as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ADMIN_OVERRIDE_PERCENT_TMP_FLOOR = 270 + // FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_UP_RATE as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_UP_RATE = 271 + // FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_RATE as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_RATE = 272 + // FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_HYST_VAL as defined in nvml/nvml.h + FI_PWR_SMOOTHING_ADMIN_OVERRIDE_RAMP_DOWN_HYST_VAL = 273 + // FI_MAX as defined in nvml/nvml.h + FI_MAX = 274 + // NVLINK_LOW_POWER_THRESHOLD_UNIT_100US as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_UNIT_100US = 0 + // NVLINK_LOW_POWER_THRESHOLD_UNIT_50US as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_UNIT_50US = 1 + // NVLINK_POWER_STATE_HIGH_SPEED as defined in nvml/nvml.h + NVLINK_POWER_STATE_HIGH_SPEED = 0 + // NVLINK_POWER_STATE_LOW as defined in nvml/nvml.h + NVLINK_POWER_STATE_LOW = 1 + // NVLINK_LOW_POWER_THRESHOLD_MIN as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_MIN = 1 + // NVLINK_LOW_POWER_THRESHOLD_MAX as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_MAX = 8191 + // NVLINK_LOW_POWER_THRESHOLD_RESET as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_RESET = 4294967295 + // NVLINK_LOW_POWER_THRESHOLD_DEFAULT as defined in nvml/nvml.h + NVLINK_LOW_POWER_THRESHOLD_DEFAULT = 4294967295 + // C2C_POWER_STATE_FULL_POWER as defined in nvml/nvml.h + C2C_POWER_STATE_FULL_POWER = 0 + // C2C_POWER_STATE_LOW_POWER as defined in nvml/nvml.h + C2C_POWER_STATE_LOW_POWER = 1 + // EventTypeNone as defined in nvml/nvml.h + EventTypeNone = 0 + // EventTypeSingleBitEccError as defined in nvml/nvml.h + EventTypeSingleBitEccError = 1 + // EventTypeDoubleBitEccError as defined in nvml/nvml.h + EventTypeDoubleBitEccError = 2 + // EventTypePState as defined in nvml/nvml.h + EventTypePState = 4 + // EventTypeXidCriticalError as defined in nvml/nvml.h + EventTypeXidCriticalError = 8 + // EventTypeClock as defined in nvml/nvml.h + EventTypeClock = 16 + // EventTypePowerSourceChange as defined in nvml/nvml.h + EventTypePowerSourceChange = 128 + // EventMigConfigChange as defined in nvml/nvml.h + EventMigConfigChange = 256 + // EventTypeSingleBitEccErrorStorm as defined in nvml/nvml.h + EventTypeSingleBitEccErrorStorm = 512 + // EventTypeDramRetirementEvent as defined in nvml/nvml.h + EventTypeDramRetirementEvent = 1024 + // EventTypeDramRetirementFailure as defined in nvml/nvml.h + EventTypeDramRetirementFailure = 2048 + // EventTypeNonFatalPoisonError as defined in nvml/nvml.h + EventTypeNonFatalPoisonError = 4096 + // EventTypeFatalPoisonError as defined in nvml/nvml.h + EventTypeFatalPoisonError = 8192 + // EventTypeGpuUnavailableError as defined in nvml/nvml.h + EventTypeGpuUnavailableError = 16384 + // EventTypeGpuRecoveryAction as defined in nvml/nvml.h + EventTypeGpuRecoveryAction = 32768 + // EventTypeAll as defined in nvml/nvml.h + EventTypeAll = 65439 + // SystemEventTypeGpuDriverUnbind as defined in nvml/nvml.h + SystemEventTypeGpuDriverUnbind = 1 + // SystemEventTypeGpuDriverBind as defined in nvml/nvml.h + SystemEventTypeGpuDriverBind = 2 + // SystemEventTypeCount as defined in nvml/nvml.h + SystemEventTypeCount = 2 + // ClocksEventReasonGpuIdle as defined in nvml/nvml.h + ClocksEventReasonGpuIdle = 1 + // ClocksEventReasonApplicationsClocksSetting as defined in nvml/nvml.h + ClocksEventReasonApplicationsClocksSetting = 2 + // ClocksThrottleReasonUserDefinedClocks as defined in nvml/nvml.h + ClocksThrottleReasonUserDefinedClocks = 2 + // ClocksEventReasonSwPowerCap as defined in nvml/nvml.h + ClocksEventReasonSwPowerCap = 4 + // ClocksThrottleReasonHwSlowdown as defined in nvml/nvml.h + ClocksThrottleReasonHwSlowdown = 8 + // ClocksEventReasonSyncBoost as defined in nvml/nvml.h + ClocksEventReasonSyncBoost = 16 + // ClocksEventReasonSwThermalSlowdown as defined in nvml/nvml.h + ClocksEventReasonSwThermalSlowdown = 32 + // ClocksThrottleReasonHwThermalSlowdown as defined in nvml/nvml.h + ClocksThrottleReasonHwThermalSlowdown = 64 + // ClocksThrottleReasonHwPowerBrakeSlowdown as defined in nvml/nvml.h + ClocksThrottleReasonHwPowerBrakeSlowdown = 128 + // ClocksEventReasonDisplayClockSetting as defined in nvml/nvml.h + ClocksEventReasonDisplayClockSetting = 256 + // ClocksEventReasonNone as defined in nvml/nvml.h + ClocksEventReasonNone = 0 + // ClocksEventReasonAll as defined in nvml/nvml.h + ClocksEventReasonAll = 511 + // ClocksThrottleReasonGpuIdle as defined in nvml/nvml.h + ClocksThrottleReasonGpuIdle = 1 + // ClocksThrottleReasonApplicationsClocksSetting as defined in nvml/nvml.h + ClocksThrottleReasonApplicationsClocksSetting = 2 + // ClocksThrottleReasonSyncBoost as defined in nvml/nvml.h + ClocksThrottleReasonSyncBoost = 16 + // ClocksThrottleReasonSwPowerCap as defined in nvml/nvml.h + ClocksThrottleReasonSwPowerCap = 4 + // ClocksThrottleReasonSwThermalSlowdown as defined in nvml/nvml.h + ClocksThrottleReasonSwThermalSlowdown = 32 + // ClocksThrottleReasonDisplayClockSetting as defined in nvml/nvml.h + ClocksThrottleReasonDisplayClockSetting = 256 + // ClocksThrottleReasonNone as defined in nvml/nvml.h + ClocksThrottleReasonNone = 0 + // ClocksThrottleReasonAll as defined in nvml/nvml.h + ClocksThrottleReasonAll = 511 + // NVFBC_SESSION_FLAG_DIFFMAP_ENABLED as defined in nvml/nvml.h + NVFBC_SESSION_FLAG_DIFFMAP_ENABLED = 1 + // NVFBC_SESSION_FLAG_CLASSIFICATIONMAP_ENABLED as defined in nvml/nvml.h + NVFBC_SESSION_FLAG_CLASSIFICATIONMAP_ENABLED = 2 + // NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_NO_WAIT as defined in nvml/nvml.h + NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_NO_WAIT = 4 + // NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_INFINITE as defined in nvml/nvml.h + NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_INFINITE = 8 + // NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_TIMEOUT as defined in nvml/nvml.h + NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_TIMEOUT = 16 + // CC_SYSTEM_CPU_CAPS_NONE as defined in nvml/nvml.h + CC_SYSTEM_CPU_CAPS_NONE = 0 + // CC_SYSTEM_CPU_CAPS_AMD_SEV as defined in nvml/nvml.h + CC_SYSTEM_CPU_CAPS_AMD_SEV = 1 + // CC_SYSTEM_CPU_CAPS_INTEL_TDX as defined in nvml/nvml.h + CC_SYSTEM_CPU_CAPS_INTEL_TDX = 2 + // CC_SYSTEM_CPU_CAPS_AMD_SEV_SNP as defined in nvml/nvml.h + CC_SYSTEM_CPU_CAPS_AMD_SEV_SNP = 3 + // CC_SYSTEM_CPU_CAPS_AMD_SNP_VTOM as defined in nvml/nvml.h + CC_SYSTEM_CPU_CAPS_AMD_SNP_VTOM = 4 + // CC_SYSTEM_GPUS_CC_NOT_CAPABLE as defined in nvml/nvml.h + CC_SYSTEM_GPUS_CC_NOT_CAPABLE = 0 + // CC_SYSTEM_GPUS_CC_CAPABLE as defined in nvml/nvml.h + CC_SYSTEM_GPUS_CC_CAPABLE = 1 + // CC_SYSTEM_DEVTOOLS_MODE_OFF as defined in nvml/nvml.h + CC_SYSTEM_DEVTOOLS_MODE_OFF = 0 + // CC_SYSTEM_DEVTOOLS_MODE_ON as defined in nvml/nvml.h + CC_SYSTEM_DEVTOOLS_MODE_ON = 1 + // CC_SYSTEM_ENVIRONMENT_UNAVAILABLE as defined in nvml/nvml.h + CC_SYSTEM_ENVIRONMENT_UNAVAILABLE = 0 + // CC_SYSTEM_ENVIRONMENT_SIM as defined in nvml/nvml.h + CC_SYSTEM_ENVIRONMENT_SIM = 1 + // CC_SYSTEM_ENVIRONMENT_PROD as defined in nvml/nvml.h + CC_SYSTEM_ENVIRONMENT_PROD = 2 + // CC_SYSTEM_FEATURE_DISABLED as defined in nvml/nvml.h + CC_SYSTEM_FEATURE_DISABLED = 0 + // CC_SYSTEM_FEATURE_ENABLED as defined in nvml/nvml.h + CC_SYSTEM_FEATURE_ENABLED = 1 + // CC_SYSTEM_MULTIGPU_NONE as defined in nvml/nvml.h + CC_SYSTEM_MULTIGPU_NONE = 0 + // CC_SYSTEM_MULTIGPU_PROTECTED_PCIE as defined in nvml/nvml.h + CC_SYSTEM_MULTIGPU_PROTECTED_PCIE = 1 + // CC_SYSTEM_MULTIGPU_NVLE as defined in nvml/nvml.h + CC_SYSTEM_MULTIGPU_NVLE = 2 + // CC_ACCEPTING_CLIENT_REQUESTS_FALSE as defined in nvml/nvml.h + CC_ACCEPTING_CLIENT_REQUESTS_FALSE = 0 + // CC_ACCEPTING_CLIENT_REQUESTS_TRUE as defined in nvml/nvml.h + CC_ACCEPTING_CLIENT_REQUESTS_TRUE = 1 + // GPU_CERT_CHAIN_SIZE as defined in nvml/nvml.h + GPU_CERT_CHAIN_SIZE = 4096 + // GPU_ATTESTATION_CERT_CHAIN_SIZE as defined in nvml/nvml.h + GPU_ATTESTATION_CERT_CHAIN_SIZE = 5120 + // CC_GPU_CEC_NONCE_SIZE as defined in nvml/nvml.h + CC_GPU_CEC_NONCE_SIZE = 32 + // CC_GPU_ATTESTATION_REPORT_SIZE as defined in nvml/nvml.h + CC_GPU_ATTESTATION_REPORT_SIZE = 8192 + // CC_GPU_CEC_ATTESTATION_REPORT_SIZE as defined in nvml/nvml.h + CC_GPU_CEC_ATTESTATION_REPORT_SIZE = 4096 + // CC_CEC_ATTESTATION_REPORT_NOT_PRESENT as defined in nvml/nvml.h + CC_CEC_ATTESTATION_REPORT_NOT_PRESENT = 0 + // CC_CEC_ATTESTATION_REPORT_PRESENT as defined in nvml/nvml.h + CC_CEC_ATTESTATION_REPORT_PRESENT = 1 + // CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MIN as defined in nvml/nvml.h + CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MIN = 50 + // CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MAX as defined in nvml/nvml.h + CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MAX = 65 + // GPU_FABRIC_UUID_LEN as defined in nvml/nvml.h + GPU_FABRIC_UUID_LEN = 16 + // GPU_FABRIC_STATE_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_STATE_NOT_SUPPORTED = 0 + // GPU_FABRIC_STATE_NOT_STARTED as defined in nvml/nvml.h + GPU_FABRIC_STATE_NOT_STARTED = 1 + // GPU_FABRIC_STATE_IN_PROGRESS as defined in nvml/nvml.h + GPU_FABRIC_STATE_IN_PROGRESS = 2 + // GPU_FABRIC_STATE_COMPLETED as defined in nvml/nvml.h + GPU_FABRIC_STATE_COMPLETED = 3 + // GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_TRUE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_TRUE = 1 + // GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_FALSE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_FALSE = 2 + // GPU_FABRIC_HEALTH_MASK_SHIFT_DEGRADED_BW as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_SHIFT_DEGRADED_BW = 0 + // GPU_FABRIC_HEALTH_MASK_WIDTH_DEGRADED_BW as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_WIDTH_DEGRADED_BW = 3 + // GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_TRUE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_TRUE = 1 + // GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_FALSE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_FALSE = 2 + // GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_RECOVERY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_RECOVERY = 2 + // GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_RECOVERY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_RECOVERY = 3 + // GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_TRUE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_TRUE = 1 + // GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_FALSE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_FALSE = 2 + // GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_UNHEALTHY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_UNHEALTHY = 4 + // GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_UNHEALTHY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_UNHEALTHY = 3 + // GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_TRUE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_TRUE = 1 + // GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_FALSE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_FALSE = 2 + // GPU_FABRIC_HEALTH_MASK_SHIFT_ACCESS_TIMEOUT_RECOVERY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_SHIFT_ACCESS_TIMEOUT_RECOVERY = 6 + // GPU_FABRIC_HEALTH_MASK_WIDTH_ACCESS_TIMEOUT_RECOVERY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_WIDTH_ACCESS_TIMEOUT_RECOVERY = 3 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NONE as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NONE = 1 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_SYSGUID as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_SYSGUID = 2 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_CHASSIS_SN as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_CHASSIS_SN = 3 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NO_PARTITION as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NO_PARTITION = 4 + // GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INSUFFICIENT_NVLINKS as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INSUFFICIENT_NVLINKS = 5 + // GPU_FABRIC_HEALTH_MASK_SHIFT_INCORRECT_CONFIGURATION as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_SHIFT_INCORRECT_CONFIGURATION = 8 + // GPU_FABRIC_HEALTH_MASK_WIDTH_INCORRECT_CONFIGURATION as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_MASK_WIDTH_INCORRECT_CONFIGURATION = 15 + // GPU_FABRIC_HEALTH_SUMMARY_NOT_SUPPORTED as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_SUMMARY_NOT_SUPPORTED = 0 + // GPU_FABRIC_HEALTH_SUMMARY_HEALTHY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_SUMMARY_HEALTHY = 1 + // GPU_FABRIC_HEALTH_SUMMARY_UNHEALTHY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_SUMMARY_UNHEALTHY = 2 + // GPU_FABRIC_HEALTH_SUMMARY_LIMITED_CAPACITY as defined in nvml/nvml.h + GPU_FABRIC_HEALTH_SUMMARY_LIMITED_CAPACITY = 3 + // INIT_FLAG_NO_GPUS as defined in nvml/nvml.h + INIT_FLAG_NO_GPUS = 1 + // INIT_FLAG_NO_ATTACH as defined in nvml/nvml.h + INIT_FLAG_NO_ATTACH = 2 + // DEVICE_INFOROM_VERSION_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_INFOROM_VERSION_BUFFER_SIZE = 16 + // DEVICE_UUID_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_UUID_BUFFER_SIZE = 80 + // DEVICE_UUID_V2_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_UUID_V2_BUFFER_SIZE = 96 + // DEVICE_PART_NUMBER_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_PART_NUMBER_BUFFER_SIZE = 80 + // SYSTEM_DRIVER_VERSION_BUFFER_SIZE as defined in nvml/nvml.h + SYSTEM_DRIVER_VERSION_BUFFER_SIZE = 80 + // SYSTEM_NVML_VERSION_BUFFER_SIZE as defined in nvml/nvml.h + SYSTEM_NVML_VERSION_BUFFER_SIZE = 80 + // DEVICE_NAME_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_NAME_BUFFER_SIZE = 64 + // DEVICE_NAME_V2_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_NAME_V2_BUFFER_SIZE = 96 + // DEVICE_SERIAL_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_SERIAL_BUFFER_SIZE = 30 + // DEVICE_VBIOS_VERSION_BUFFER_SIZE as defined in nvml/nvml.h + DEVICE_VBIOS_VERSION_BUFFER_SIZE = 32 + // AFFINITY_SCOPE_NODE as defined in nvml/nvml.h + AFFINITY_SCOPE_NODE = 0 + // AFFINITY_SCOPE_SOCKET as defined in nvml/nvml.h + AFFINITY_SCOPE_SOCKET = 1 + // NVLINK_BER_MANTISSA_SHIFT as defined in nvml/nvml.h + NVLINK_BER_MANTISSA_SHIFT = 8 + // NVLINK_BER_MANTISSA_WIDTH as defined in nvml/nvml.h + NVLINK_BER_MANTISSA_WIDTH = 15 + // NVLINK_BER_EXP_SHIFT as defined in nvml/nvml.h + NVLINK_BER_EXP_SHIFT = 0 + // NVLINK_BER_EXP_WIDTH as defined in nvml/nvml.h + NVLINK_BER_EXP_WIDTH = 255 + // NVLINK_STATE_INACTIVE as defined in nvml/nvml.h + NVLINK_STATE_INACTIVE = 0 + // NVLINK_STATE_ACTIVE as defined in nvml/nvml.h + NVLINK_STATE_ACTIVE = 1 + // NVLINK_STATE_SLEEP as defined in nvml/nvml.h + NVLINK_STATE_SLEEP = 2 + // NVLINK_TOTAL_SUPPORTED_BW_MODES as defined in nvml/nvml.h + NVLINK_TOTAL_SUPPORTED_BW_MODES = 23 + // NVLINK_FIRMWARE_UCODE_TYPE_MSE as defined in nvml/nvml.h + NVLINK_FIRMWARE_UCODE_TYPE_MSE = 1 + // NVLINK_FIRMWARE_UCODE_TYPE_NETIR as defined in nvml/nvml.h + NVLINK_FIRMWARE_UCODE_TYPE_NETIR = 2 + // NVLINK_FIRMWARE_UCODE_TYPE_NETIR_UPHY as defined in nvml/nvml.h + NVLINK_FIRMWARE_UCODE_TYPE_NETIR_UPHY = 3 + // NVLINK_FIRMWARE_UCODE_TYPE_NETIR_CLN as defined in nvml/nvml.h + NVLINK_FIRMWARE_UCODE_TYPE_NETIR_CLN = 4 + // NVLINK_FIRMWARE_UCODE_TYPE_NETIR_DLN as defined in nvml/nvml.h + NVLINK_FIRMWARE_UCODE_TYPE_NETIR_DLN = 5 + // NVLINK_FIRMWARE_VERSION_LENGTH as defined in nvml/nvml.h + NVLINK_FIRMWARE_VERSION_LENGTH = 100 + // PRM_DATA_MAX_SIZE as defined in nvml/nvml.h + PRM_DATA_MAX_SIZE = 496 + // DEVICE_MIG_DISABLE as defined in nvml/nvml.h + DEVICE_MIG_DISABLE = 0 + // DEVICE_MIG_ENABLE as defined in nvml/nvml.h + DEVICE_MIG_ENABLE = 1 + // GPU_INSTANCE_PROFILE_1_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE = 0 + // GPU_INSTANCE_PROFILE_2_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_2_SLICE = 1 + // GPU_INSTANCE_PROFILE_3_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_3_SLICE = 2 + // GPU_INSTANCE_PROFILE_4_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_4_SLICE = 3 + // GPU_INSTANCE_PROFILE_7_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_7_SLICE = 4 + // GPU_INSTANCE_PROFILE_8_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_8_SLICE = 5 + // GPU_INSTANCE_PROFILE_6_SLICE as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_6_SLICE = 6 + // GPU_INSTANCE_PROFILE_1_SLICE_REV1 as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE_REV1 = 7 + // GPU_INSTANCE_PROFILE_2_SLICE_REV1 as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_2_SLICE_REV1 = 8 + // GPU_INSTANCE_PROFILE_1_SLICE_REV2 as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE_REV2 = 9 + // GPU_INSTANCE_PROFILE_1_SLICE_GFX as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE_GFX = 10 + // GPU_INSTANCE_PROFILE_2_SLICE_GFX as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_2_SLICE_GFX = 11 + // GPU_INSTANCE_PROFILE_4_SLICE_GFX as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_4_SLICE_GFX = 12 + // GPU_INSTANCE_PROFILE_1_SLICE_NO_ME as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE_NO_ME = 13 + // GPU_INSTANCE_PROFILE_2_SLICE_NO_ME as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_2_SLICE_NO_ME = 14 + // GPU_INSTANCE_PROFILE_1_SLICE_ALL_ME as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_1_SLICE_ALL_ME = 15 + // GPU_INSTANCE_PROFILE_2_SLICE_ALL_ME as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_2_SLICE_ALL_ME = 16 + // GPU_INSTANCE_PROFILE_COUNT as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_COUNT = 17 + // GPU_INSTANCE_PROFILE_CAPS_P2P as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_CAPS_P2P = 1 + // GPU_INTSTANCE_PROFILE_CAPS_P2P as defined in nvml/nvml.h + GPU_INTSTANCE_PROFILE_CAPS_P2P = 1 + // GPU_INSTANCE_PROFILE_CAPS_GFX as defined in nvml/nvml.h + GPU_INSTANCE_PROFILE_CAPS_GFX = 2 + // COMPUTE_INSTANCE_PROFILE_CAPS_GFX as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_CAPS_GFX = 1 + // COMPUTE_INSTANCE_PROFILE_1_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_1_SLICE = 0 + // COMPUTE_INSTANCE_PROFILE_2_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_2_SLICE = 1 + // COMPUTE_INSTANCE_PROFILE_3_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_3_SLICE = 2 + // COMPUTE_INSTANCE_PROFILE_4_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_4_SLICE = 3 + // COMPUTE_INSTANCE_PROFILE_7_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_7_SLICE = 4 + // COMPUTE_INSTANCE_PROFILE_8_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_8_SLICE = 5 + // COMPUTE_INSTANCE_PROFILE_6_SLICE as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_6_SLICE = 6 + // COMPUTE_INSTANCE_PROFILE_1_SLICE_REV1 as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_1_SLICE_REV1 = 7 + // COMPUTE_INSTANCE_PROFILE_COUNT as defined in nvml/nvml.h + COMPUTE_INSTANCE_PROFILE_COUNT = 8 + // COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED as defined in nvml/nvml.h + COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED = 0 + // COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT as defined in nvml/nvml.h + COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT = 1 + // GPM_METRICS_GET_VERSION as defined in nvml/nvml.h + GPM_METRICS_GET_VERSION = 1 + // GPM_SUPPORT_VERSION as defined in nvml/nvml.h + GPM_SUPPORT_VERSION = 1 + // DEV_CAP_EGM as defined in nvml/nvml.h + DEV_CAP_EGM = 1 + // WORKLOAD_POWER_MAX_PROFILES as defined in nvml/nvml.h + WORKLOAD_POWER_MAX_PROFILES = 255 + // POWER_SMOOTHING_MAX_NUM_PROFILES as defined in nvml/nvml.h + POWER_SMOOTHING_MAX_NUM_PROFILES = 5 + // POWER_SMOOTHING_NUM_PROFILE_PARAMS as defined in nvml/nvml.h + POWER_SMOOTHING_NUM_PROFILE_PARAMS = 4 + // POWER_SMOOTHING_ADMIN_OVERRIDE_NOT_SET as defined in nvml/nvml.h + POWER_SMOOTHING_ADMIN_OVERRIDE_NOT_SET = 4294967295 + // POWER_SMOOTHING_PROFILE_PARAM_PERCENT_TMP_FLOOR as defined in nvml/nvml.h + POWER_SMOOTHING_PROFILE_PARAM_PERCENT_TMP_FLOOR = 0 + // POWER_SMOOTHING_PROFILE_PARAM_RAMP_UP_RATE as defined in nvml/nvml.h + POWER_SMOOTHING_PROFILE_PARAM_RAMP_UP_RATE = 1 + // POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_RATE as defined in nvml/nvml.h + POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_RATE = 2 + // POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_HYSTERESIS as defined in nvml/nvml.h + POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_HYSTERESIS = 3 +) + +// BridgeChipType as declared in nvml/nvml.h +type BridgeChipType int32 + +// BridgeChipType enumeration from nvml/nvml.h +const ( + BRIDGE_CHIP_PLX BridgeChipType = iota + BRIDGE_CHIP_BRO4 BridgeChipType = 1 +) + +// NvLinkUtilizationCountUnits as declared in nvml/nvml.h +type NvLinkUtilizationCountUnits int32 + +// NvLinkUtilizationCountUnits enumeration from nvml/nvml.h +const ( + NVLINK_COUNTER_UNIT_CYCLES NvLinkUtilizationCountUnits = iota + NVLINK_COUNTER_UNIT_PACKETS NvLinkUtilizationCountUnits = 1 + NVLINK_COUNTER_UNIT_BYTES NvLinkUtilizationCountUnits = 2 + NVLINK_COUNTER_UNIT_RESERVED NvLinkUtilizationCountUnits = 3 + NVLINK_COUNTER_UNIT_COUNT NvLinkUtilizationCountUnits = 4 +) + +// NvLinkUtilizationCountPktTypes as declared in nvml/nvml.h +type NvLinkUtilizationCountPktTypes int32 + +// NvLinkUtilizationCountPktTypes enumeration from nvml/nvml.h +const ( + NVLINK_COUNTER_PKTFILTER_NOP NvLinkUtilizationCountPktTypes = 1 + NVLINK_COUNTER_PKTFILTER_READ NvLinkUtilizationCountPktTypes = 2 + NVLINK_COUNTER_PKTFILTER_WRITE NvLinkUtilizationCountPktTypes = 4 + NVLINK_COUNTER_PKTFILTER_RATOM NvLinkUtilizationCountPktTypes = 8 + NVLINK_COUNTER_PKTFILTER_NRATOM NvLinkUtilizationCountPktTypes = 16 + NVLINK_COUNTER_PKTFILTER_FLUSH NvLinkUtilizationCountPktTypes = 32 + NVLINK_COUNTER_PKTFILTER_RESPDATA NvLinkUtilizationCountPktTypes = 64 + NVLINK_COUNTER_PKTFILTER_RESPNODATA NvLinkUtilizationCountPktTypes = 128 + NVLINK_COUNTER_PKTFILTER_ALL NvLinkUtilizationCountPktTypes = 255 +) + +// NvLinkCapability as declared in nvml/nvml.h +type NvLinkCapability int32 + +// NvLinkCapability enumeration from nvml/nvml.h +const ( + NVLINK_CAP_P2P_SUPPORTED NvLinkCapability = iota + NVLINK_CAP_SYSMEM_ACCESS NvLinkCapability = 1 + NVLINK_CAP_P2P_ATOMICS NvLinkCapability = 2 + NVLINK_CAP_SYSMEM_ATOMICS NvLinkCapability = 3 + NVLINK_CAP_SLI_BRIDGE NvLinkCapability = 4 + NVLINK_CAP_VALID NvLinkCapability = 5 + NVLINK_CAP_COUNT NvLinkCapability = 6 +) + +// NvLinkErrorCounter as declared in nvml/nvml.h +type NvLinkErrorCounter int32 + +// NvLinkErrorCounter enumeration from nvml/nvml.h +const ( + NVLINK_ERROR_DL_REPLAY NvLinkErrorCounter = iota + NVLINK_ERROR_DL_RECOVERY NvLinkErrorCounter = 1 + NVLINK_ERROR_DL_CRC_FLIT NvLinkErrorCounter = 2 + NVLINK_ERROR_DL_CRC_DATA NvLinkErrorCounter = 3 + NVLINK_ERROR_DL_ECC_DATA NvLinkErrorCounter = 4 + NVLINK_ERROR_COUNT NvLinkErrorCounter = 5 +) + +// IntNvLinkDeviceType as declared in nvml/nvml.h +type IntNvLinkDeviceType int32 + +// IntNvLinkDeviceType enumeration from nvml/nvml.h +const ( + NVLINK_DEVICE_TYPE_GPU IntNvLinkDeviceType = iota + NVLINK_DEVICE_TYPE_IBMNPU IntNvLinkDeviceType = 1 + NVLINK_DEVICE_TYPE_SWITCH IntNvLinkDeviceType = 2 + NVLINK_DEVICE_TYPE_UNKNOWN IntNvLinkDeviceType = 255 +) + +// GpuTopologyLevel as declared in nvml/nvml.h +type GpuTopologyLevel int32 + +// GpuTopologyLevel enumeration from nvml/nvml.h +const ( + TOPOLOGY_INTERNAL GpuTopologyLevel = iota + TOPOLOGY_SINGLE GpuTopologyLevel = 10 + TOPOLOGY_MULTIPLE GpuTopologyLevel = 20 + TOPOLOGY_HOSTBRIDGE GpuTopologyLevel = 30 + TOPOLOGY_NODE GpuTopologyLevel = 40 + TOPOLOGY_SYSTEM GpuTopologyLevel = 50 +) + +// GpuP2PStatus as declared in nvml/nvml.h +type GpuP2PStatus int32 + +// GpuP2PStatus enumeration from nvml/nvml.h +const ( + P2P_STATUS_OK GpuP2PStatus = iota + P2P_STATUS_CHIPSET_NOT_SUPPORED GpuP2PStatus = 1 + P2P_STATUS_CHIPSET_NOT_SUPPORTED GpuP2PStatus = 1 + P2P_STATUS_GPU_NOT_SUPPORTED GpuP2PStatus = 2 + P2P_STATUS_IOH_TOPOLOGY_NOT_SUPPORTED GpuP2PStatus = 3 + P2P_STATUS_DISABLED_BY_REGKEY GpuP2PStatus = 4 + P2P_STATUS_NOT_SUPPORTED GpuP2PStatus = 5 + P2P_STATUS_UNKNOWN GpuP2PStatus = 6 +) + +// GpuP2PCapsIndex as declared in nvml/nvml.h +type GpuP2PCapsIndex int32 + +// GpuP2PCapsIndex enumeration from nvml/nvml.h +const ( + P2P_CAPS_INDEX_READ GpuP2PCapsIndex = iota + P2P_CAPS_INDEX_WRITE GpuP2PCapsIndex = 1 + P2P_CAPS_INDEX_NVLINK GpuP2PCapsIndex = 2 + P2P_CAPS_INDEX_ATOMICS GpuP2PCapsIndex = 3 + P2P_CAPS_INDEX_PCI GpuP2PCapsIndex = 4 + P2P_CAPS_INDEX_PROP GpuP2PCapsIndex = 4 + P2P_CAPS_INDEX_UNKNOWN GpuP2PCapsIndex = 5 +) + +// SamplingType as declared in nvml/nvml.h +type SamplingType int32 + +// SamplingType enumeration from nvml/nvml.h +const ( + TOTAL_POWER_SAMPLES SamplingType = iota + GPU_UTILIZATION_SAMPLES SamplingType = 1 + MEMORY_UTILIZATION_SAMPLES SamplingType = 2 + ENC_UTILIZATION_SAMPLES SamplingType = 3 + DEC_UTILIZATION_SAMPLES SamplingType = 4 + PROCESSOR_CLK_SAMPLES SamplingType = 5 + MEMORY_CLK_SAMPLES SamplingType = 6 + MODULE_POWER_SAMPLES SamplingType = 7 + JPG_UTILIZATION_SAMPLES SamplingType = 8 + OFA_UTILIZATION_SAMPLES SamplingType = 9 + SAMPLINGTYPE_COUNT SamplingType = 10 +) + +// PcieUtilCounter as declared in nvml/nvml.h +type PcieUtilCounter int32 + +// PcieUtilCounter enumeration from nvml/nvml.h +const ( + PCIE_UTIL_TX_BYTES PcieUtilCounter = iota + PCIE_UTIL_RX_BYTES PcieUtilCounter = 1 + PCIE_UTIL_COUNT PcieUtilCounter = 2 +) + +// ValueType as declared in nvml/nvml.h +type ValueType int32 + +// ValueType enumeration from nvml/nvml.h +const ( + VALUE_TYPE_DOUBLE ValueType = iota + VALUE_TYPE_UNSIGNED_INT ValueType = 1 + VALUE_TYPE_UNSIGNED_LONG ValueType = 2 + VALUE_TYPE_UNSIGNED_LONG_LONG ValueType = 3 + VALUE_TYPE_SIGNED_LONG_LONG ValueType = 4 + VALUE_TYPE_SIGNED_INT ValueType = 5 + VALUE_TYPE_UNSIGNED_SHORT ValueType = 6 + VALUE_TYPE_COUNT ValueType = 7 +) + +// PerfPolicyType as declared in nvml/nvml.h +type PerfPolicyType int32 + +// PerfPolicyType enumeration from nvml/nvml.h +const ( + PERF_POLICY_POWER PerfPolicyType = iota + PERF_POLICY_THERMAL PerfPolicyType = 1 + PERF_POLICY_SYNC_BOOST PerfPolicyType = 2 + PERF_POLICY_BOARD_LIMIT PerfPolicyType = 3 + PERF_POLICY_LOW_UTILIZATION PerfPolicyType = 4 + PERF_POLICY_RELIABILITY PerfPolicyType = 5 + PERF_POLICY_TOTAL_APP_CLOCKS PerfPolicyType = 10 + PERF_POLICY_TOTAL_BASE_CLOCKS PerfPolicyType = 11 + PERF_POLICY_COUNT PerfPolicyType = 12 +) + +// CoolerControl as declared in nvml/nvml.h +type CoolerControl int32 + +// CoolerControl enumeration from nvml/nvml.h +const ( + THERMAL_COOLER_SIGNAL_NONE CoolerControl = iota + THERMAL_COOLER_SIGNAL_TOGGLE CoolerControl = 1 + THERMAL_COOLER_SIGNAL_VARIABLE CoolerControl = 2 + THERMAL_COOLER_SIGNAL_COUNT CoolerControl = 3 +) + +// CoolerTarget as declared in nvml/nvml.h +type CoolerTarget int32 + +// CoolerTarget enumeration from nvml/nvml.h +const ( + THERMAL_COOLER_TARGET_NONE CoolerTarget = 1 + THERMAL_COOLER_TARGET_GPU CoolerTarget = 2 + THERMAL_COOLER_TARGET_MEMORY CoolerTarget = 4 + THERMAL_COOLER_TARGET_POWER_SUPPLY CoolerTarget = 8 + THERMAL_COOLER_TARGET_GPU_RELATED CoolerTarget = 14 +) + +// EnableState as declared in nvml/nvml.h +type EnableState int32 + +// EnableState enumeration from nvml/nvml.h +const ( + FEATURE_DISABLED EnableState = iota + FEATURE_ENABLED EnableState = 1 +) + +// BrandType as declared in nvml/nvml.h +type BrandType int32 + +// BrandType enumeration from nvml/nvml.h +const ( + BRAND_UNKNOWN BrandType = iota + BRAND_QUADRO BrandType = 1 + BRAND_TESLA BrandType = 2 + BRAND_NVS BrandType = 3 + BRAND_GRID BrandType = 4 + BRAND_GEFORCE BrandType = 5 + BRAND_TITAN BrandType = 6 + BRAND_NVIDIA_VAPPS BrandType = 7 + BRAND_NVIDIA_VPC BrandType = 8 + BRAND_NVIDIA_VCS BrandType = 9 + BRAND_NVIDIA_VWS BrandType = 10 + BRAND_NVIDIA_CLOUD_GAMING BrandType = 11 + BRAND_NVIDIA_VGAMING BrandType = 11 + BRAND_QUADRO_RTX BrandType = 12 + BRAND_NVIDIA_RTX BrandType = 13 + BRAND_NVIDIA BrandType = 14 + BRAND_GEFORCE_RTX BrandType = 15 + BRAND_TITAN_RTX BrandType = 16 + BRAND_COUNT BrandType = 18 +) + +// TemperatureThresholds as declared in nvml/nvml.h +type TemperatureThresholds int32 + +// TemperatureThresholds enumeration from nvml/nvml.h +const ( + TEMPERATURE_THRESHOLD_SHUTDOWN TemperatureThresholds = iota + TEMPERATURE_THRESHOLD_SLOWDOWN TemperatureThresholds = 1 + TEMPERATURE_THRESHOLD_MEM_MAX TemperatureThresholds = 2 + TEMPERATURE_THRESHOLD_GPU_MAX TemperatureThresholds = 3 + TEMPERATURE_THRESHOLD_ACOUSTIC_MIN TemperatureThresholds = 4 + TEMPERATURE_THRESHOLD_ACOUSTIC_CURR TemperatureThresholds = 5 + TEMPERATURE_THRESHOLD_ACOUSTIC_MAX TemperatureThresholds = 6 + TEMPERATURE_THRESHOLD_GPS_CURR TemperatureThresholds = 7 + TEMPERATURE_THRESHOLD_COUNT TemperatureThresholds = 8 +) + +// TemperatureSensors as declared in nvml/nvml.h +type TemperatureSensors int32 + +// TemperatureSensors enumeration from nvml/nvml.h +const ( + TEMPERATURE_GPU TemperatureSensors = iota + TEMPERATURE_COUNT TemperatureSensors = 1 +) + +// ComputeMode as declared in nvml/nvml.h +type ComputeMode int32 + +// ComputeMode enumeration from nvml/nvml.h +const ( + COMPUTEMODE_DEFAULT ComputeMode = iota + COMPUTEMODE_EXCLUSIVE_THREAD ComputeMode = 1 + COMPUTEMODE_PROHIBITED ComputeMode = 2 + COMPUTEMODE_EXCLUSIVE_PROCESS ComputeMode = 3 + COMPUTEMODE_COUNT ComputeMode = 4 +) + +// MemoryErrorType as declared in nvml/nvml.h +type MemoryErrorType int32 + +// MemoryErrorType enumeration from nvml/nvml.h +const ( + MEMORY_ERROR_TYPE_CORRECTED MemoryErrorType = iota + MEMORY_ERROR_TYPE_UNCORRECTED MemoryErrorType = 1 + MEMORY_ERROR_TYPE_COUNT MemoryErrorType = 2 +) + +// NvlinkVersion as declared in nvml/nvml.h +type NvlinkVersion int32 + +// NvlinkVersion enumeration from nvml/nvml.h +const ( + NVLINK_VERSION_INVALID NvlinkVersion = iota + NVLINK_VERSION_1_0 NvlinkVersion = 1 + NVLINK_VERSION_2_0 NvlinkVersion = 2 + NVLINK_VERSION_2_2 NvlinkVersion = 3 + NVLINK_VERSION_3_0 NvlinkVersion = 4 + NVLINK_VERSION_3_1 NvlinkVersion = 5 + NVLINK_VERSION_4_0 NvlinkVersion = 6 + NVLINK_VERSION_5_0 NvlinkVersion = 7 +) + +// EccCounterType as declared in nvml/nvml.h +type EccCounterType int32 + +// EccCounterType enumeration from nvml/nvml.h +const ( + VOLATILE_ECC EccCounterType = iota + AGGREGATE_ECC EccCounterType = 1 + ECC_COUNTER_TYPE_COUNT EccCounterType = 2 +) + +// ClockType as declared in nvml/nvml.h +type ClockType int32 + +// ClockType enumeration from nvml/nvml.h +const ( + CLOCK_GRAPHICS ClockType = iota + CLOCK_SM ClockType = 1 + CLOCK_MEM ClockType = 2 + CLOCK_VIDEO ClockType = 3 + CLOCK_COUNT ClockType = 4 +) + +// ClockId as declared in nvml/nvml.h +type ClockId int32 + +// ClockId enumeration from nvml/nvml.h +const ( + CLOCK_ID_CURRENT ClockId = iota + CLOCK_ID_APP_CLOCK_TARGET ClockId = 1 + CLOCK_ID_APP_CLOCK_DEFAULT ClockId = 2 + CLOCK_ID_CUSTOMER_BOOST_MAX ClockId = 3 + CLOCK_ID_COUNT ClockId = 4 +) + +// DriverModel as declared in nvml/nvml.h +type DriverModel int32 + +// DriverModel enumeration from nvml/nvml.h +const ( + DRIVER_WDDM DriverModel = iota + DRIVER_WDM DriverModel = 1 + DRIVER_MCDM DriverModel = 2 +) + +// Pstates as declared in nvml/nvml.h +type Pstates int32 + +// Pstates enumeration from nvml/nvml.h +const ( + PSTATE_0 Pstates = iota + PSTATE_1 Pstates = 1 + PSTATE_2 Pstates = 2 + PSTATE_3 Pstates = 3 + PSTATE_4 Pstates = 4 + PSTATE_5 Pstates = 5 + PSTATE_6 Pstates = 6 + PSTATE_7 Pstates = 7 + PSTATE_8 Pstates = 8 + PSTATE_9 Pstates = 9 + PSTATE_10 Pstates = 10 + PSTATE_11 Pstates = 11 + PSTATE_12 Pstates = 12 + PSTATE_13 Pstates = 13 + PSTATE_14 Pstates = 14 + PSTATE_15 Pstates = 15 + PSTATE_UNKNOWN Pstates = 32 +) + +// GpuOperationMode as declared in nvml/nvml.h +type GpuOperationMode int32 + +// GpuOperationMode enumeration from nvml/nvml.h +const ( + GOM_ALL_ON GpuOperationMode = iota + GOM_COMPUTE GpuOperationMode = 1 + GOM_LOW_DP GpuOperationMode = 2 +) + +// InforomObject as declared in nvml/nvml.h +type InforomObject int32 + +// InforomObject enumeration from nvml/nvml.h +const ( + INFOROM_OEM InforomObject = iota + INFOROM_ECC InforomObject = 1 + INFOROM_POWER InforomObject = 2 + INFOROM_DEN InforomObject = 3 + INFOROM_COUNT InforomObject = 4 +) + +// Return as declared in nvml/nvml.h +type Return int32 + +// Return enumeration from nvml/nvml.h +const ( + SUCCESS Return = iota + ERROR_UNINITIALIZED Return = 1 + ERROR_INVALID_ARGUMENT Return = 2 + ERROR_NOT_SUPPORTED Return = 3 + ERROR_NO_PERMISSION Return = 4 + ERROR_ALREADY_INITIALIZED Return = 5 + ERROR_NOT_FOUND Return = 6 + ERROR_INSUFFICIENT_SIZE Return = 7 + ERROR_INSUFFICIENT_POWER Return = 8 + ERROR_DRIVER_NOT_LOADED Return = 9 + ERROR_TIMEOUT Return = 10 + ERROR_IRQ_ISSUE Return = 11 + ERROR_LIBRARY_NOT_FOUND Return = 12 + ERROR_FUNCTION_NOT_FOUND Return = 13 + ERROR_CORRUPTED_INFOROM Return = 14 + ERROR_GPU_IS_LOST Return = 15 + ERROR_RESET_REQUIRED Return = 16 + ERROR_OPERATING_SYSTEM Return = 17 + ERROR_LIB_RM_VERSION_MISMATCH Return = 18 + ERROR_IN_USE Return = 19 + ERROR_MEMORY Return = 20 + ERROR_NO_DATA Return = 21 + ERROR_VGPU_ECC_NOT_SUPPORTED Return = 22 + ERROR_INSUFFICIENT_RESOURCES Return = 23 + ERROR_FREQ_NOT_SUPPORTED Return = 24 + ERROR_ARGUMENT_VERSION_MISMATCH Return = 25 + ERROR_DEPRECATED Return = 26 + ERROR_NOT_READY Return = 27 + ERROR_GPU_NOT_FOUND Return = 28 + ERROR_INVALID_STATE Return = 29 + ERROR_RESET_TYPE_NOT_SUPPORTED Return = 30 + ERROR_UNKNOWN Return = 999 +) + +// MemoryLocation as declared in nvml/nvml.h +type MemoryLocation int32 + +// MemoryLocation enumeration from nvml/nvml.h +const ( + MEMORY_LOCATION_L1_CACHE MemoryLocation = iota + MEMORY_LOCATION_L2_CACHE MemoryLocation = 1 + MEMORY_LOCATION_DRAM MemoryLocation = 2 + MEMORY_LOCATION_DEVICE_MEMORY MemoryLocation = 2 + MEMORY_LOCATION_REGISTER_FILE MemoryLocation = 3 + MEMORY_LOCATION_TEXTURE_MEMORY MemoryLocation = 4 + MEMORY_LOCATION_TEXTURE_SHM MemoryLocation = 5 + MEMORY_LOCATION_CBU MemoryLocation = 6 + MEMORY_LOCATION_SRAM MemoryLocation = 7 + MEMORY_LOCATION_COUNT MemoryLocation = 8 +) + +// PageRetirementCause as declared in nvml/nvml.h +type PageRetirementCause int32 + +// PageRetirementCause enumeration from nvml/nvml.h +const ( + PAGE_RETIREMENT_CAUSE_MULTIPLE_SINGLE_BIT_ECC_ERRORS PageRetirementCause = iota + PAGE_RETIREMENT_CAUSE_DOUBLE_BIT_ECC_ERROR PageRetirementCause = 1 + PAGE_RETIREMENT_CAUSE_COUNT PageRetirementCause = 2 +) + +// RestrictedAPI as declared in nvml/nvml.h +type RestrictedAPI int32 + +// RestrictedAPI enumeration from nvml/nvml.h +const ( + RESTRICTED_API_SET_APPLICATION_CLOCKS RestrictedAPI = iota + RESTRICTED_API_SET_AUTO_BOOSTED_CLOCKS RestrictedAPI = 1 + RESTRICTED_API_COUNT RestrictedAPI = 2 +) + +// GpuUtilizationDomainId as declared in nvml/nvml.h +type GpuUtilizationDomainId int32 + +// GpuUtilizationDomainId enumeration from nvml/nvml.h +const ( + GPU_UTILIZATION_DOMAIN_GPU GpuUtilizationDomainId = iota + GPU_UTILIZATION_DOMAIN_FB GpuUtilizationDomainId = 1 + GPU_UTILIZATION_DOMAIN_VID GpuUtilizationDomainId = 2 + GPU_UTILIZATION_DOMAIN_BUS GpuUtilizationDomainId = 3 +) + +// GpuVirtualizationMode as declared in nvml/nvml.h +type GpuVirtualizationMode int32 + +// GpuVirtualizationMode enumeration from nvml/nvml.h +const ( + GPU_VIRTUALIZATION_MODE_NONE GpuVirtualizationMode = iota + GPU_VIRTUALIZATION_MODE_PASSTHROUGH GpuVirtualizationMode = 1 + GPU_VIRTUALIZATION_MODE_VGPU GpuVirtualizationMode = 2 + GPU_VIRTUALIZATION_MODE_HOST_VGPU GpuVirtualizationMode = 3 + GPU_VIRTUALIZATION_MODE_HOST_VSGA GpuVirtualizationMode = 4 +) + +// HostVgpuMode as declared in nvml/nvml.h +type HostVgpuMode int32 + +// HostVgpuMode enumeration from nvml/nvml.h +const ( + HOST_VGPU_MODE_NON_SRIOV HostVgpuMode = iota + HOST_VGPU_MODE_SRIOV HostVgpuMode = 1 +) + +// VgpuVmIdType as declared in nvml/nvml.h +type VgpuVmIdType int32 + +// VgpuVmIdType enumeration from nvml/nvml.h +const ( + VGPU_VM_ID_DOMAIN_ID VgpuVmIdType = iota + VGPU_VM_ID_UUID VgpuVmIdType = 1 +) + +// VgpuGuestInfoState as declared in nvml/nvml.h +type VgpuGuestInfoState int32 + +// VgpuGuestInfoState enumeration from nvml/nvml.h +const ( + VGPU_INSTANCE_GUEST_INFO_STATE_UNINITIALIZED VgpuGuestInfoState = iota + VGPU_INSTANCE_GUEST_INFO_STATE_INITIALIZED VgpuGuestInfoState = 1 +) + +// VgpuCapability as declared in nvml/nvml.h +type VgpuCapability int32 + +// VgpuCapability enumeration from nvml/nvml.h +const ( + VGPU_CAP_NVLINK_P2P VgpuCapability = iota + VGPU_CAP_GPUDIRECT VgpuCapability = 1 + VGPU_CAP_MULTI_VGPU_EXCLUSIVE VgpuCapability = 2 + VGPU_CAP_EXCLUSIVE_TYPE VgpuCapability = 3 + VGPU_CAP_EXCLUSIVE_SIZE VgpuCapability = 4 + VGPU_CAP_COUNT VgpuCapability = 5 +) + +// VgpuDriverCapability as declared in nvml/nvml.h +type VgpuDriverCapability int32 + +// VgpuDriverCapability enumeration from nvml/nvml.h +const ( + VGPU_DRIVER_CAP_HETEROGENEOUS_MULTI_VGPU VgpuDriverCapability = iota + VGPU_DRIVER_CAP_WARM_UPDATE VgpuDriverCapability = 1 + VGPU_DRIVER_CAP_COUNT VgpuDriverCapability = 2 +) + +// DeviceVgpuCapability as declared in nvml/nvml.h +type DeviceVgpuCapability int32 + +// DeviceVgpuCapability enumeration from nvml/nvml.h +const ( + DEVICE_VGPU_CAP_FRACTIONAL_MULTI_VGPU DeviceVgpuCapability = iota + DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_PROFILES DeviceVgpuCapability = 1 + DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_SIZES DeviceVgpuCapability = 2 + DEVICE_VGPU_CAP_READ_DEVICE_BUFFER_BW DeviceVgpuCapability = 3 + DEVICE_VGPU_CAP_WRITE_DEVICE_BUFFER_BW DeviceVgpuCapability = 4 + DEVICE_VGPU_CAP_DEVICE_STREAMING DeviceVgpuCapability = 5 + DEVICE_VGPU_CAP_MINI_QUARTER_GPU DeviceVgpuCapability = 6 + DEVICE_VGPU_CAP_COMPUTE_MEDIA_ENGINE_GPU DeviceVgpuCapability = 7 + DEVICE_VGPU_CAP_WARM_UPDATE DeviceVgpuCapability = 8 + DEVICE_VGPU_CAP_HOMOGENEOUS_PLACEMENTS DeviceVgpuCapability = 9 + DEVICE_VGPU_CAP_MIG_TIMESLICING_SUPPORTED DeviceVgpuCapability = 10 + DEVICE_VGPU_CAP_MIG_TIMESLICING_ENABLED DeviceVgpuCapability = 11 + DEVICE_VGPU_CAP_COUNT DeviceVgpuCapability = 12 +) + +// DeviceGpuRecoveryAction as declared in nvml/nvml.h +type DeviceGpuRecoveryAction int32 + +// DeviceGpuRecoveryAction enumeration from nvml/nvml.h +const ( + GPU_RECOVERY_ACTION_NONE DeviceGpuRecoveryAction = iota + GPU_RECOVERY_ACTION_GPU_RESET DeviceGpuRecoveryAction = 1 + GPU_RECOVERY_ACTION_NODE_REBOOT DeviceGpuRecoveryAction = 2 + GPU_RECOVERY_ACTION_DRAIN_P2P DeviceGpuRecoveryAction = 3 + GPU_RECOVERY_ACTION_DRAIN_AND_RESET DeviceGpuRecoveryAction = 4 +) + +// FanState as declared in nvml/nvml.h +type FanState int32 + +// FanState enumeration from nvml/nvml.h +const ( + FAN_NORMAL FanState = iota + FAN_FAILED FanState = 1 +) + +// LedColor as declared in nvml/nvml.h +type LedColor int32 + +// LedColor enumeration from nvml/nvml.h +const ( + LED_COLOR_GREEN LedColor = iota + LED_COLOR_AMBER LedColor = 1 +) + +// EncoderType as declared in nvml/nvml.h +type EncoderType int32 + +// EncoderType enumeration from nvml/nvml.h +const ( + ENCODER_QUERY_H264 EncoderType = iota + ENCODER_QUERY_HEVC EncoderType = 1 + ENCODER_QUERY_AV1 EncoderType = 2 + ENCODER_QUERY_UNKNOWN EncoderType = 255 +) + +// FBCSessionType as declared in nvml/nvml.h +type FBCSessionType int32 + +// FBCSessionType enumeration from nvml/nvml.h +const ( + FBC_SESSION_TYPE_UNKNOWN FBCSessionType = iota + FBC_SESSION_TYPE_TOSYS FBCSessionType = 1 + FBC_SESSION_TYPE_CUDA FBCSessionType = 2 + FBC_SESSION_TYPE_VID FBCSessionType = 3 + FBC_SESSION_TYPE_HWENC FBCSessionType = 4 +) + +// DetachGpuState as declared in nvml/nvml.h +type DetachGpuState int32 + +// DetachGpuState enumeration from nvml/nvml.h +const ( + DETACH_GPU_KEEP DetachGpuState = iota + DETACH_GPU_REMOVE DetachGpuState = 1 +) + +// PcieLinkState as declared in nvml/nvml.h +type PcieLinkState int32 + +// PcieLinkState enumeration from nvml/nvml.h +const ( + PCIE_LINK_KEEP PcieLinkState = iota + PCIE_LINK_SHUT_DOWN PcieLinkState = 1 +) + +// ClockLimitId as declared in nvml/nvml.h +type ClockLimitId int32 + +// ClockLimitId enumeration from nvml/nvml.h +const ( + CLOCK_LIMIT_ID_RANGE_START ClockLimitId = -256 + CLOCK_LIMIT_ID_TDP ClockLimitId = -255 + CLOCK_LIMIT_ID_UNLIMITED ClockLimitId = -254 +) + +// VgpuVmCompatibility as declared in nvml/nvml.h +type VgpuVmCompatibility int32 + +// VgpuVmCompatibility enumeration from nvml/nvml.h +const ( + VGPU_VM_COMPATIBILITY_NONE VgpuVmCompatibility = iota + VGPU_VM_COMPATIBILITY_COLD VgpuVmCompatibility = 1 + VGPU_VM_COMPATIBILITY_HIBERNATE VgpuVmCompatibility = 2 + VGPU_VM_COMPATIBILITY_SLEEP VgpuVmCompatibility = 4 + VGPU_VM_COMPATIBILITY_LIVE VgpuVmCompatibility = 8 +) + +// VgpuPgpuCompatibilityLimitCode as declared in nvml/nvml.h +type VgpuPgpuCompatibilityLimitCode int32 + +// VgpuPgpuCompatibilityLimitCode enumeration from nvml/nvml.h +const ( + VGPU_COMPATIBILITY_LIMIT_NONE VgpuPgpuCompatibilityLimitCode = iota + VGPU_COMPATIBILITY_LIMIT_HOST_DRIVER VgpuPgpuCompatibilityLimitCode = 1 + VGPU_COMPATIBILITY_LIMIT_GUEST_DRIVER VgpuPgpuCompatibilityLimitCode = 2 + VGPU_COMPATIBILITY_LIMIT_GPU VgpuPgpuCompatibilityLimitCode = 4 + VGPU_COMPATIBILITY_LIMIT_OTHER VgpuPgpuCompatibilityLimitCode = -2147483648 +) + +// DeviceAddressingModeType as declared in nvml/nvml.h +type DeviceAddressingModeType int32 + +// DeviceAddressingModeType enumeration from nvml/nvml.h +const ( + DEVICE_ADDRESSING_MODE_NONE DeviceAddressingModeType = iota + DEVICE_ADDRESSING_MODE_HMM DeviceAddressingModeType = 1 + DEVICE_ADDRESSING_MODE_ATS DeviceAddressingModeType = 2 +) + +// ThermalTarget as declared in nvml/nvml.h +type ThermalTarget int32 + +// ThermalTarget enumeration from nvml/nvml.h +const ( + THERMAL_TARGET_NONE ThermalTarget = iota + THERMAL_TARGET_GPU ThermalTarget = 1 + THERMAL_TARGET_MEMORY ThermalTarget = 2 + THERMAL_TARGET_POWER_SUPPLY ThermalTarget = 4 + THERMAL_TARGET_BOARD ThermalTarget = 8 + THERMAL_TARGET_VCD_BOARD ThermalTarget = 9 + THERMAL_TARGET_VCD_INLET ThermalTarget = 10 + THERMAL_TARGET_VCD_OUTLET ThermalTarget = 11 + THERMAL_TARGET_ALL ThermalTarget = 15 + THERMAL_TARGET_UNKNOWN ThermalTarget = -1 +) + +// ThermalController as declared in nvml/nvml.h +type ThermalController int32 + +// ThermalController enumeration from nvml/nvml.h +const ( + THERMAL_CONTROLLER_NONE ThermalController = iota + THERMAL_CONTROLLER_GPU_INTERNAL ThermalController = 1 + THERMAL_CONTROLLER_ADM1032 ThermalController = 2 + THERMAL_CONTROLLER_ADT7461 ThermalController = 3 + THERMAL_CONTROLLER_MAX6649 ThermalController = 4 + THERMAL_CONTROLLER_MAX1617 ThermalController = 5 + THERMAL_CONTROLLER_LM99 ThermalController = 6 + THERMAL_CONTROLLER_LM89 ThermalController = 7 + THERMAL_CONTROLLER_LM64 ThermalController = 8 + THERMAL_CONTROLLER_G781 ThermalController = 9 + THERMAL_CONTROLLER_ADT7473 ThermalController = 10 + THERMAL_CONTROLLER_SBMAX6649 ThermalController = 11 + THERMAL_CONTROLLER_VBIOSEVT ThermalController = 12 + THERMAL_CONTROLLER_OS ThermalController = 13 + THERMAL_CONTROLLER_NVSYSCON_CANOAS ThermalController = 14 + THERMAL_CONTROLLER_NVSYSCON_E551 ThermalController = 15 + THERMAL_CONTROLLER_MAX6649R ThermalController = 16 + THERMAL_CONTROLLER_ADT7473S ThermalController = 17 + THERMAL_CONTROLLER_UNKNOWN ThermalController = -1 +) + +// UUIDType as declared in nvml/nvml.h +type UUIDType int32 + +// UUIDType enumeration from nvml/nvml.h +const ( + UUID_TYPE_NONE UUIDType = iota + UUID_TYPE_ASCII UUIDType = 1 + UUID_TYPE_BINARY UUIDType = 2 +) + +// GridLicenseFeatureCode as declared in nvml/nvml.h +type GridLicenseFeatureCode int32 + +// GridLicenseFeatureCode enumeration from nvml/nvml.h +const ( + GRID_LICENSE_FEATURE_CODE_UNKNOWN GridLicenseFeatureCode = iota + GRID_LICENSE_FEATURE_CODE_VGPU GridLicenseFeatureCode = 1 + GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX GridLicenseFeatureCode = 2 + GRID_LICENSE_FEATURE_CODE_VWORKSTATION GridLicenseFeatureCode = 2 + GRID_LICENSE_FEATURE_CODE_GAMING GridLicenseFeatureCode = 3 + GRID_LICENSE_FEATURE_CODE_COMPUTE GridLicenseFeatureCode = 4 +) + +// GpmMetricId as declared in nvml/nvml.h +type GpmMetricId int32 + +// GpmMetricId enumeration from nvml/nvml.h +const ( + GPM_METRIC_GRAPHICS_UTIL GpmMetricId = 1 + GPM_METRIC_SM_UTIL GpmMetricId = 2 + GPM_METRIC_SM_OCCUPANCY GpmMetricId = 3 + GPM_METRIC_INTEGER_UTIL GpmMetricId = 4 + GPM_METRIC_ANY_TENSOR_UTIL GpmMetricId = 5 + GPM_METRIC_DFMA_TENSOR_UTIL GpmMetricId = 6 + GPM_METRIC_HMMA_TENSOR_UTIL GpmMetricId = 7 + GPM_METRIC_IMMA_TENSOR_UTIL GpmMetricId = 9 + GPM_METRIC_DRAM_BW_UTIL GpmMetricId = 10 + GPM_METRIC_FP64_UTIL GpmMetricId = 11 + GPM_METRIC_FP32_UTIL GpmMetricId = 12 + GPM_METRIC_FP16_UTIL GpmMetricId = 13 + GPM_METRIC_PCIE_TX_PER_SEC GpmMetricId = 20 + GPM_METRIC_PCIE_RX_PER_SEC GpmMetricId = 21 + GPM_METRIC_NVDEC_0_UTIL GpmMetricId = 30 + GPM_METRIC_NVDEC_1_UTIL GpmMetricId = 31 + GPM_METRIC_NVDEC_2_UTIL GpmMetricId = 32 + GPM_METRIC_NVDEC_3_UTIL GpmMetricId = 33 + GPM_METRIC_NVDEC_4_UTIL GpmMetricId = 34 + GPM_METRIC_NVDEC_5_UTIL GpmMetricId = 35 + GPM_METRIC_NVDEC_6_UTIL GpmMetricId = 36 + GPM_METRIC_NVDEC_7_UTIL GpmMetricId = 37 + GPM_METRIC_NVJPG_0_UTIL GpmMetricId = 40 + GPM_METRIC_NVJPG_1_UTIL GpmMetricId = 41 + GPM_METRIC_NVJPG_2_UTIL GpmMetricId = 42 + GPM_METRIC_NVJPG_3_UTIL GpmMetricId = 43 + GPM_METRIC_NVJPG_4_UTIL GpmMetricId = 44 + GPM_METRIC_NVJPG_5_UTIL GpmMetricId = 45 + GPM_METRIC_NVJPG_6_UTIL GpmMetricId = 46 + GPM_METRIC_NVJPG_7_UTIL GpmMetricId = 47 + GPM_METRIC_NVOFA_0_UTIL GpmMetricId = 50 + GPM_METRIC_NVOFA_1_UTIL GpmMetricId = 51 + GPM_METRIC_NVLINK_TOTAL_RX_PER_SEC GpmMetricId = 60 + GPM_METRIC_NVLINK_TOTAL_TX_PER_SEC GpmMetricId = 61 + GPM_METRIC_NVLINK_L0_RX_PER_SEC GpmMetricId = 62 + GPM_METRIC_NVLINK_L0_TX_PER_SEC GpmMetricId = 63 + GPM_METRIC_NVLINK_L1_RX_PER_SEC GpmMetricId = 64 + GPM_METRIC_NVLINK_L1_TX_PER_SEC GpmMetricId = 65 + GPM_METRIC_NVLINK_L2_RX_PER_SEC GpmMetricId = 66 + GPM_METRIC_NVLINK_L2_TX_PER_SEC GpmMetricId = 67 + GPM_METRIC_NVLINK_L3_RX_PER_SEC GpmMetricId = 68 + GPM_METRIC_NVLINK_L3_TX_PER_SEC GpmMetricId = 69 + GPM_METRIC_NVLINK_L4_RX_PER_SEC GpmMetricId = 70 + GPM_METRIC_NVLINK_L4_TX_PER_SEC GpmMetricId = 71 + GPM_METRIC_NVLINK_L5_RX_PER_SEC GpmMetricId = 72 + GPM_METRIC_NVLINK_L5_TX_PER_SEC GpmMetricId = 73 + GPM_METRIC_NVLINK_L6_RX_PER_SEC GpmMetricId = 74 + GPM_METRIC_NVLINK_L6_TX_PER_SEC GpmMetricId = 75 + GPM_METRIC_NVLINK_L7_RX_PER_SEC GpmMetricId = 76 + GPM_METRIC_NVLINK_L7_TX_PER_SEC GpmMetricId = 77 + GPM_METRIC_NVLINK_L8_RX_PER_SEC GpmMetricId = 78 + GPM_METRIC_NVLINK_L8_TX_PER_SEC GpmMetricId = 79 + GPM_METRIC_NVLINK_L9_RX_PER_SEC GpmMetricId = 80 + GPM_METRIC_NVLINK_L9_TX_PER_SEC GpmMetricId = 81 + GPM_METRIC_NVLINK_L10_RX_PER_SEC GpmMetricId = 82 + GPM_METRIC_NVLINK_L10_TX_PER_SEC GpmMetricId = 83 + GPM_METRIC_NVLINK_L11_RX_PER_SEC GpmMetricId = 84 + GPM_METRIC_NVLINK_L11_TX_PER_SEC GpmMetricId = 85 + GPM_METRIC_NVLINK_L12_RX_PER_SEC GpmMetricId = 86 + GPM_METRIC_NVLINK_L12_TX_PER_SEC GpmMetricId = 87 + GPM_METRIC_NVLINK_L13_RX_PER_SEC GpmMetricId = 88 + GPM_METRIC_NVLINK_L13_TX_PER_SEC GpmMetricId = 89 + GPM_METRIC_NVLINK_L14_RX_PER_SEC GpmMetricId = 90 + GPM_METRIC_NVLINK_L14_TX_PER_SEC GpmMetricId = 91 + GPM_METRIC_NVLINK_L15_RX_PER_SEC GpmMetricId = 92 + GPM_METRIC_NVLINK_L15_TX_PER_SEC GpmMetricId = 93 + GPM_METRIC_NVLINK_L16_RX_PER_SEC GpmMetricId = 94 + GPM_METRIC_NVLINK_L16_TX_PER_SEC GpmMetricId = 95 + GPM_METRIC_NVLINK_L17_RX_PER_SEC GpmMetricId = 96 + GPM_METRIC_NVLINK_L17_TX_PER_SEC GpmMetricId = 97 + GPM_METRIC_C2C_TOTAL_TX_PER_SEC GpmMetricId = 100 + GPM_METRIC_C2C_TOTAL_RX_PER_SEC GpmMetricId = 101 + GPM_METRIC_C2C_DATA_TX_PER_SEC GpmMetricId = 102 + GPM_METRIC_C2C_DATA_RX_PER_SEC GpmMetricId = 103 + GPM_METRIC_C2C_LINK0_TOTAL_TX_PER_SEC GpmMetricId = 104 + GPM_METRIC_C2C_LINK0_TOTAL_RX_PER_SEC GpmMetricId = 105 + GPM_METRIC_C2C_LINK0_DATA_TX_PER_SEC GpmMetricId = 106 + GPM_METRIC_C2C_LINK0_DATA_RX_PER_SEC GpmMetricId = 107 + GPM_METRIC_C2C_LINK1_TOTAL_TX_PER_SEC GpmMetricId = 108 + GPM_METRIC_C2C_LINK1_TOTAL_RX_PER_SEC GpmMetricId = 109 + GPM_METRIC_C2C_LINK1_DATA_TX_PER_SEC GpmMetricId = 110 + GPM_METRIC_C2C_LINK1_DATA_RX_PER_SEC GpmMetricId = 111 + GPM_METRIC_C2C_LINK2_TOTAL_TX_PER_SEC GpmMetricId = 112 + GPM_METRIC_C2C_LINK2_TOTAL_RX_PER_SEC GpmMetricId = 113 + GPM_METRIC_C2C_LINK2_DATA_TX_PER_SEC GpmMetricId = 114 + GPM_METRIC_C2C_LINK2_DATA_RX_PER_SEC GpmMetricId = 115 + GPM_METRIC_C2C_LINK3_TOTAL_TX_PER_SEC GpmMetricId = 116 + GPM_METRIC_C2C_LINK3_TOTAL_RX_PER_SEC GpmMetricId = 117 + GPM_METRIC_C2C_LINK3_DATA_TX_PER_SEC GpmMetricId = 118 + GPM_METRIC_C2C_LINK3_DATA_RX_PER_SEC GpmMetricId = 119 + GPM_METRIC_C2C_LINK4_TOTAL_TX_PER_SEC GpmMetricId = 120 + GPM_METRIC_C2C_LINK4_TOTAL_RX_PER_SEC GpmMetricId = 121 + GPM_METRIC_C2C_LINK4_DATA_TX_PER_SEC GpmMetricId = 122 + GPM_METRIC_C2C_LINK4_DATA_RX_PER_SEC GpmMetricId = 123 + GPM_METRIC_C2C_LINK5_TOTAL_TX_PER_SEC GpmMetricId = 124 + GPM_METRIC_C2C_LINK5_TOTAL_RX_PER_SEC GpmMetricId = 125 + GPM_METRIC_C2C_LINK5_DATA_TX_PER_SEC GpmMetricId = 126 + GPM_METRIC_C2C_LINK5_DATA_RX_PER_SEC GpmMetricId = 127 + GPM_METRIC_C2C_LINK6_TOTAL_TX_PER_SEC GpmMetricId = 128 + GPM_METRIC_C2C_LINK6_TOTAL_RX_PER_SEC GpmMetricId = 129 + GPM_METRIC_C2C_LINK6_DATA_TX_PER_SEC GpmMetricId = 130 + GPM_METRIC_C2C_LINK6_DATA_RX_PER_SEC GpmMetricId = 131 + GPM_METRIC_C2C_LINK7_TOTAL_TX_PER_SEC GpmMetricId = 132 + GPM_METRIC_C2C_LINK7_TOTAL_RX_PER_SEC GpmMetricId = 133 + GPM_METRIC_C2C_LINK7_DATA_TX_PER_SEC GpmMetricId = 134 + GPM_METRIC_C2C_LINK7_DATA_RX_PER_SEC GpmMetricId = 135 + GPM_METRIC_C2C_LINK8_TOTAL_TX_PER_SEC GpmMetricId = 136 + GPM_METRIC_C2C_LINK8_TOTAL_RX_PER_SEC GpmMetricId = 137 + GPM_METRIC_C2C_LINK8_DATA_TX_PER_SEC GpmMetricId = 138 + GPM_METRIC_C2C_LINK8_DATA_RX_PER_SEC GpmMetricId = 139 + GPM_METRIC_C2C_LINK9_TOTAL_TX_PER_SEC GpmMetricId = 140 + GPM_METRIC_C2C_LINK9_TOTAL_RX_PER_SEC GpmMetricId = 141 + GPM_METRIC_C2C_LINK9_DATA_TX_PER_SEC GpmMetricId = 142 + GPM_METRIC_C2C_LINK9_DATA_RX_PER_SEC GpmMetricId = 143 + GPM_METRIC_C2C_LINK10_TOTAL_TX_PER_SEC GpmMetricId = 144 + GPM_METRIC_C2C_LINK10_TOTAL_RX_PER_SEC GpmMetricId = 145 + GPM_METRIC_C2C_LINK10_DATA_TX_PER_SEC GpmMetricId = 146 + GPM_METRIC_C2C_LINK10_DATA_RX_PER_SEC GpmMetricId = 147 + GPM_METRIC_C2C_LINK11_TOTAL_TX_PER_SEC GpmMetricId = 148 + GPM_METRIC_C2C_LINK11_TOTAL_RX_PER_SEC GpmMetricId = 149 + GPM_METRIC_C2C_LINK11_DATA_TX_PER_SEC GpmMetricId = 150 + GPM_METRIC_C2C_LINK11_DATA_RX_PER_SEC GpmMetricId = 151 + GPM_METRIC_C2C_LINK12_TOTAL_TX_PER_SEC GpmMetricId = 152 + GPM_METRIC_C2C_LINK12_TOTAL_RX_PER_SEC GpmMetricId = 153 + GPM_METRIC_C2C_LINK12_DATA_TX_PER_SEC GpmMetricId = 154 + GPM_METRIC_C2C_LINK12_DATA_RX_PER_SEC GpmMetricId = 155 + GPM_METRIC_C2C_LINK13_TOTAL_TX_PER_SEC GpmMetricId = 156 + GPM_METRIC_C2C_LINK13_TOTAL_RX_PER_SEC GpmMetricId = 157 + GPM_METRIC_C2C_LINK13_DATA_TX_PER_SEC GpmMetricId = 158 + GPM_METRIC_C2C_LINK13_DATA_RX_PER_SEC GpmMetricId = 159 + GPM_METRIC_HOSTMEM_CACHE_HIT GpmMetricId = 160 + GPM_METRIC_HOSTMEM_CACHE_MISS GpmMetricId = 161 + GPM_METRIC_PEERMEM_CACHE_HIT GpmMetricId = 162 + GPM_METRIC_PEERMEM_CACHE_MISS GpmMetricId = 163 + GPM_METRIC_DRAM_CACHE_HIT GpmMetricId = 164 + GPM_METRIC_DRAM_CACHE_MISS GpmMetricId = 165 + GPM_METRIC_NVENC_0_UTIL GpmMetricId = 166 + GPM_METRIC_NVENC_1_UTIL GpmMetricId = 167 + GPM_METRIC_NVENC_2_UTIL GpmMetricId = 168 + GPM_METRIC_NVENC_3_UTIL GpmMetricId = 169 + GPM_METRIC_GR0_CTXSW_CYCLES_ELAPSED GpmMetricId = 170 + GPM_METRIC_GR0_CTXSW_CYCLES_ACTIVE GpmMetricId = 171 + GPM_METRIC_GR0_CTXSW_REQUESTS GpmMetricId = 172 + GPM_METRIC_GR0_CTXSW_CYCLES_PER_REQ GpmMetricId = 173 + GPM_METRIC_GR0_CTXSW_ACTIVE_PCT GpmMetricId = 174 + GPM_METRIC_GR1_CTXSW_CYCLES_ELAPSED GpmMetricId = 175 + GPM_METRIC_GR1_CTXSW_CYCLES_ACTIVE GpmMetricId = 176 + GPM_METRIC_GR1_CTXSW_REQUESTS GpmMetricId = 177 + GPM_METRIC_GR1_CTXSW_CYCLES_PER_REQ GpmMetricId = 178 + GPM_METRIC_GR1_CTXSW_ACTIVE_PCT GpmMetricId = 179 + GPM_METRIC_GR2_CTXSW_CYCLES_ELAPSED GpmMetricId = 180 + GPM_METRIC_GR2_CTXSW_CYCLES_ACTIVE GpmMetricId = 181 + GPM_METRIC_GR2_CTXSW_REQUESTS GpmMetricId = 182 + GPM_METRIC_GR2_CTXSW_CYCLES_PER_REQ GpmMetricId = 183 + GPM_METRIC_GR2_CTXSW_ACTIVE_PCT GpmMetricId = 184 + GPM_METRIC_GR3_CTXSW_CYCLES_ELAPSED GpmMetricId = 185 + GPM_METRIC_GR3_CTXSW_CYCLES_ACTIVE GpmMetricId = 186 + GPM_METRIC_GR3_CTXSW_REQUESTS GpmMetricId = 187 + GPM_METRIC_GR3_CTXSW_CYCLES_PER_REQ GpmMetricId = 188 + GPM_METRIC_GR3_CTXSW_ACTIVE_PCT GpmMetricId = 189 + GPM_METRIC_GR4_CTXSW_CYCLES_ELAPSED GpmMetricId = 190 + GPM_METRIC_GR4_CTXSW_CYCLES_ACTIVE GpmMetricId = 191 + GPM_METRIC_GR4_CTXSW_REQUESTS GpmMetricId = 192 + GPM_METRIC_GR4_CTXSW_CYCLES_PER_REQ GpmMetricId = 193 + GPM_METRIC_GR4_CTXSW_ACTIVE_PCT GpmMetricId = 194 + GPM_METRIC_GR5_CTXSW_CYCLES_ELAPSED GpmMetricId = 195 + GPM_METRIC_GR5_CTXSW_CYCLES_ACTIVE GpmMetricId = 196 + GPM_METRIC_GR5_CTXSW_REQUESTS GpmMetricId = 197 + GPM_METRIC_GR5_CTXSW_CYCLES_PER_REQ GpmMetricId = 198 + GPM_METRIC_GR5_CTXSW_ACTIVE_PCT GpmMetricId = 199 + GPM_METRIC_GR6_CTXSW_CYCLES_ELAPSED GpmMetricId = 200 + GPM_METRIC_GR6_CTXSW_CYCLES_ACTIVE GpmMetricId = 201 + GPM_METRIC_GR6_CTXSW_REQUESTS GpmMetricId = 202 + GPM_METRIC_GR6_CTXSW_CYCLES_PER_REQ GpmMetricId = 203 + GPM_METRIC_GR6_CTXSW_ACTIVE_PCT GpmMetricId = 204 + GPM_METRIC_GR7_CTXSW_CYCLES_ELAPSED GpmMetricId = 205 + GPM_METRIC_GR7_CTXSW_CYCLES_ACTIVE GpmMetricId = 206 + GPM_METRIC_GR7_CTXSW_REQUESTS GpmMetricId = 207 + GPM_METRIC_GR7_CTXSW_CYCLES_PER_REQ GpmMetricId = 208 + GPM_METRIC_GR7_CTXSW_ACTIVE_PCT GpmMetricId = 209 + GPM_METRIC_MAX GpmMetricId = 210 +) + +// PowerProfileType as declared in nvml/nvml.h +type PowerProfileType int32 + +// PowerProfileType enumeration from nvml/nvml.h +const ( + POWER_PROFILE_MAX_P PowerProfileType = iota + POWER_PROFILE_MAX_Q PowerProfileType = 1 + POWER_PROFILE_COMPUTE PowerProfileType = 2 + POWER_PROFILE_MEMORY_BOUND PowerProfileType = 3 + POWER_PROFILE_NETWORK PowerProfileType = 4 + POWER_PROFILE_BALANCED PowerProfileType = 5 + POWER_PROFILE_LLM_INFERENCE PowerProfileType = 6 + POWER_PROFILE_LLM_TRAINING PowerProfileType = 7 + POWER_PROFILE_RBM PowerProfileType = 8 + POWER_PROFILE_DCPCIE PowerProfileType = 9 + POWER_PROFILE_HMMA_SPARSE PowerProfileType = 10 + POWER_PROFILE_HMMA_DENSE PowerProfileType = 11 + POWER_PROFILE_SYNC_BALANCED PowerProfileType = 12 + POWER_PROFILE_HPC PowerProfileType = 13 + POWER_PROFILE_MIG PowerProfileType = 14 + POWER_PROFILE_MAX PowerProfileType = 15 +) diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const_static.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const_static.go new file mode 100644 index 00000000..9038b312 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/const_static.go @@ -0,0 +1,27 @@ +// Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import ( + "reflect" +) + +const ( + SYSTEM_PROCESS_NAME_BUFFER_SIZE = 256 +) + +func STRUCT_VERSION(data interface{}, version uint32) uint32 { + return uint32(uint32(reflect.Indirect(reflect.ValueOf(data)).Type().Size()) | (version << uint32(24))) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/device.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/device.go new file mode 100644 index 00000000..d341e157 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/device.go @@ -0,0 +1,3592 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import ( + "fmt" + "reflect" + "unsafe" +) + +// nvmlDeviceHandle attempts to convert a device d to an nvmlDevice. +// This is required for functions such as GetTopologyCommonAncestor which +// accept Device arguments that need to be passed to internal nvml* functions +// as nvmlDevice parameters. +func nvmlDeviceHandle(d Device) nvmlDevice { + var helper func(val reflect.Value) nvmlDevice + helper = func(val reflect.Value) nvmlDevice { + if val.Kind() == reflect.Interface { + val = val.Elem() + } + + if val.Kind() == reflect.Ptr { + val = val.Elem() + } + + if val.Type() == reflect.TypeOf(nvmlDevice{}) { + return val.Interface().(nvmlDevice) + } + + if val.Kind() != reflect.Struct { + panic(fmt.Errorf("unable to convert non-struct type %v to nvmlDevice", val.Kind())) + } + + for i := 0; i < val.Type().NumField(); i++ { + if !val.Type().Field(i).Anonymous { + continue + } + if !val.Field(i).Type().Implements(reflect.TypeOf((*Device)(nil)).Elem()) { + continue + } + return helper(val.Field(i)) + } + panic(fmt.Errorf("unable to convert %T to nvmlDevice", d)) + } + return helper(reflect.ValueOf(d)) +} + +// EccBitType +type EccBitType = MemoryErrorType + +// GpuInstanceInfo includes an interface type for Device instead of nvmlDevice +type GpuInstanceInfo struct { + Device Device + Id uint32 + ProfileId uint32 + Placement GpuInstancePlacement +} + +func (g nvmlGpuInstanceInfo) convert() GpuInstanceInfo { + out := GpuInstanceInfo{ + Device: g.Device, + Id: g.Id, + ProfileId: g.ProfileId, + Placement: g.Placement, + } + return out +} + +// ComputeInstanceInfo includes an interface type for Device instead of nvmlDevice +type ComputeInstanceInfo struct { + Device Device + GpuInstance GpuInstance + Id uint32 + ProfileId uint32 + Placement ComputeInstancePlacement +} + +func (c nvmlComputeInstanceInfo) convert() ComputeInstanceInfo { + out := ComputeInstanceInfo{ + Device: c.Device, + GpuInstance: c.GpuInstance, + Id: c.Id, + ProfileId: c.ProfileId, + Placement: c.Placement, + } + return out +} + +// nvml.DeviceGetCount() +func (l *library) DeviceGetCount() (int, Return) { + var deviceCount uint32 + ret := nvmlDeviceGetCount(&deviceCount) + return int(deviceCount), ret +} + +// nvml.DeviceGetHandleByIndex() +func (l *library) DeviceGetHandleByIndex(index int) (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetHandleByIndex(uint32(index), &device) + return device, ret +} + +// nvml.DeviceGetHandleBySerial() +// +// Deprecated: Use DeviceGetHandleByUUID instead. +func (l *library) DeviceGetHandleBySerial(serial string) (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetHandleBySerial(serial+string(rune(0)), &device) + return device, ret +} + +// nvml.DeviceGetHandleByUUID() +func (l *library) DeviceGetHandleByUUID(uuid string) (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetHandleByUUID(uuid+string(rune(0)), &device) + return device, ret +} + +// nvml.DeviceGetHandleByUUIDV() +func (l *library) DeviceGetHandleByUUIDV(uuid *UUID) (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetHandleByUUIDV(uuid, &device) + return device, ret +} + +// nvml.DeviceGetHandleByPciBusId() +func (l *library) DeviceGetHandleByPciBusId(pciBusId string) (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetHandleByPciBusId(pciBusId+string(rune(0)), &device) + return device, ret +} + +// nvml.DeviceGetName() +func (l *library) DeviceGetName(device Device) (string, Return) { + return device.GetName() +} + +func (device nvmlDevice) GetName() (string, Return) { + name := make([]byte, DEVICE_NAME_V2_BUFFER_SIZE) + ret := nvmlDeviceGetName(device, &name[0], DEVICE_NAME_V2_BUFFER_SIZE) + return string(name[:clen(name)]), ret +} + +// nvml.DeviceGetBrand() +func (l *library) DeviceGetBrand(device Device) (BrandType, Return) { + return device.GetBrand() +} + +func (device nvmlDevice) GetBrand() (BrandType, Return) { + var brandType BrandType + ret := nvmlDeviceGetBrand(device, &brandType) + return brandType, ret +} + +// nvml.DeviceGetIndex() +func (l *library) DeviceGetIndex(device Device) (int, Return) { + return device.GetIndex() +} + +func (device nvmlDevice) GetIndex() (int, Return) { + var index uint32 + ret := nvmlDeviceGetIndex(device, &index) + return int(index), ret +} + +// nvml.DeviceGetSerial() +func (l *library) DeviceGetSerial(device Device) (string, Return) { + return device.GetSerial() +} + +func (device nvmlDevice) GetSerial() (string, Return) { + serial := make([]byte, DEVICE_SERIAL_BUFFER_SIZE) + ret := nvmlDeviceGetSerial(device, &serial[0], DEVICE_SERIAL_BUFFER_SIZE) + return string(serial[:clen(serial)]), ret +} + +// nvml.DeviceGetCpuAffinity() +func (l *library) DeviceGetCpuAffinity(device Device, numCPUs int) ([]uint, Return) { + return device.GetCpuAffinity(numCPUs) +} + +func (device nvmlDevice) GetCpuAffinity(numCPUs int) ([]uint, Return) { + cpuSetSize := uint32((numCPUs-1)/int(unsafe.Sizeof(uint(0))) + 1) + cpuSet := make([]uint, cpuSetSize) + ret := nvmlDeviceGetCpuAffinity(device, cpuSetSize, &cpuSet[0]) + return cpuSet, ret +} + +// nvml.DeviceSetCpuAffinity() +func (l *library) DeviceSetCpuAffinity(device Device) Return { + return device.SetCpuAffinity() +} + +func (device nvmlDevice) SetCpuAffinity() Return { + return nvmlDeviceSetCpuAffinity(device) +} + +// nvml.DeviceClearCpuAffinity() +func (l *library) DeviceClearCpuAffinity(device Device) Return { + return device.ClearCpuAffinity() +} + +func (device nvmlDevice) ClearCpuAffinity() Return { + return nvmlDeviceClearCpuAffinity(device) +} + +// nvml.DeviceGetMemoryAffinity() +func (l *library) DeviceGetMemoryAffinity(device Device, numNodes int, scope AffinityScope) ([]uint, Return) { + return device.GetMemoryAffinity(numNodes, scope) +} + +func (device nvmlDevice) GetMemoryAffinity(numNodes int, scope AffinityScope) ([]uint, Return) { + nodeSetSize := uint32((numNodes-1)/int(unsafe.Sizeof(uint(0))) + 1) + nodeSet := make([]uint, nodeSetSize) + ret := nvmlDeviceGetMemoryAffinity(device, nodeSetSize, &nodeSet[0], scope) + return nodeSet, ret +} + +// nvml.DeviceGetCpuAffinityWithinScope() +func (l *library) DeviceGetCpuAffinityWithinScope(device Device, numCPUs int, scope AffinityScope) ([]uint, Return) { + return device.GetCpuAffinityWithinScope(numCPUs, scope) +} + +func (device nvmlDevice) GetCpuAffinityWithinScope(numCPUs int, scope AffinityScope) ([]uint, Return) { + cpuSetSize := uint32((numCPUs-1)/int(unsafe.Sizeof(uint(0))) + 1) + cpuSet := make([]uint, cpuSetSize) + ret := nvmlDeviceGetCpuAffinityWithinScope(device, cpuSetSize, &cpuSet[0], scope) + return cpuSet, ret +} + +// nvml.DeviceGetTopologyCommonAncestor() +func (l *library) DeviceGetTopologyCommonAncestor(device1 Device, device2 Device) (GpuTopologyLevel, Return) { + return device1.GetTopologyCommonAncestor(device2) +} + +func (device1 nvmlDevice) GetTopologyCommonAncestor(device2 Device) (GpuTopologyLevel, Return) { + var pathInfo GpuTopologyLevel + ret := nvmlDeviceGetTopologyCommonAncestorStub(device1, nvmlDeviceHandle(device2), &pathInfo) + return pathInfo, ret +} + +// nvmlDeviceGetTopologyCommonAncestorStub allows us to override this for testing. +var nvmlDeviceGetTopologyCommonAncestorStub = nvmlDeviceGetTopologyCommonAncestor + +// nvml.DeviceGetTopologyNearestGpus() +func (l *library) DeviceGetTopologyNearestGpus(device Device, level GpuTopologyLevel) ([]Device, Return) { + return device.GetTopologyNearestGpus(level) +} + +func (device nvmlDevice) GetTopologyNearestGpus(level GpuTopologyLevel) ([]Device, Return) { + var count uint32 + ret := nvmlDeviceGetTopologyNearestGpus(device, level, &count, nil) + if ret != SUCCESS { + return nil, ret + } + if count == 0 { + return []Device{}, ret + } + deviceArray := make([]nvmlDevice, count) + ret = nvmlDeviceGetTopologyNearestGpus(device, level, &count, &deviceArray[0]) + return convertSlice[nvmlDevice, Device](deviceArray), ret +} + +// nvml.DeviceGetP2PStatus() +func (l *library) DeviceGetP2PStatus(device1 Device, device2 Device, p2pIndex GpuP2PCapsIndex) (GpuP2PStatus, Return) { + return device1.GetP2PStatus(device2, p2pIndex) +} + +func (device1 nvmlDevice) GetP2PStatus(device2 Device, p2pIndex GpuP2PCapsIndex) (GpuP2PStatus, Return) { + var p2pStatus GpuP2PStatus + ret := nvmlDeviceGetP2PStatus(device1, nvmlDeviceHandle(device2), p2pIndex, &p2pStatus) + return p2pStatus, ret +} + +// nvml.DeviceGetUUID() +func (l *library) DeviceGetUUID(device Device) (string, Return) { + return device.GetUUID() +} + +func (device nvmlDevice) GetUUID() (string, Return) { + uuid := make([]byte, DEVICE_UUID_V2_BUFFER_SIZE) + ret := nvmlDeviceGetUUID(device, &uuid[0], DEVICE_UUID_V2_BUFFER_SIZE) + return string(uuid[:clen(uuid)]), ret +} + +// nvml.DeviceGetMinorNumber() +func (l *library) DeviceGetMinorNumber(device Device) (int, Return) { + return device.GetMinorNumber() +} + +func (device nvmlDevice) GetMinorNumber() (int, Return) { + var minorNumber uint32 + ret := nvmlDeviceGetMinorNumber(device, &minorNumber) + return int(minorNumber), ret +} + +// nvml.DeviceGetBoardPartNumber() +func (l *library) DeviceGetBoardPartNumber(device Device) (string, Return) { + return device.GetBoardPartNumber() +} + +func (device nvmlDevice) GetBoardPartNumber() (string, Return) { + partNumber := make([]byte, DEVICE_PART_NUMBER_BUFFER_SIZE) + ret := nvmlDeviceGetBoardPartNumber(device, &partNumber[0], DEVICE_PART_NUMBER_BUFFER_SIZE) + return string(partNumber[:clen(partNumber)]), ret +} + +// nvml.DeviceGetInforomVersion() +func (l *library) DeviceGetInforomVersion(device Device, object InforomObject) (string, Return) { + return device.GetInforomVersion(object) +} + +func (device nvmlDevice) GetInforomVersion(object InforomObject) (string, Return) { + version := make([]byte, DEVICE_INFOROM_VERSION_BUFFER_SIZE) + ret := nvmlDeviceGetInforomVersion(device, object, &version[0], DEVICE_INFOROM_VERSION_BUFFER_SIZE) + return string(version[:clen(version)]), ret +} + +// nvml.DeviceGetInforomImageVersion() +func (l *library) DeviceGetInforomImageVersion(device Device) (string, Return) { + return device.GetInforomImageVersion() +} + +func (device nvmlDevice) GetInforomImageVersion() (string, Return) { + version := make([]byte, DEVICE_INFOROM_VERSION_BUFFER_SIZE) + ret := nvmlDeviceGetInforomImageVersion(device, &version[0], DEVICE_INFOROM_VERSION_BUFFER_SIZE) + return string(version[:clen(version)]), ret +} + +// nvml.DeviceGetInforomConfigurationChecksum() +func (l *library) DeviceGetInforomConfigurationChecksum(device Device) (uint32, Return) { + return device.GetInforomConfigurationChecksum() +} + +func (device nvmlDevice) GetInforomConfigurationChecksum() (uint32, Return) { + var checksum uint32 + ret := nvmlDeviceGetInforomConfigurationChecksum(device, &checksum) + return checksum, ret +} + +// nvml.DeviceValidateInforom() +func (l *library) DeviceValidateInforom(device Device) Return { + return device.ValidateInforom() +} + +func (device nvmlDevice) ValidateInforom() Return { + return nvmlDeviceValidateInforom(device) +} + +// nvml.DeviceGetDisplayMode() +func (l *library) DeviceGetDisplayMode(device Device) (EnableState, Return) { + return device.GetDisplayMode() +} + +func (device nvmlDevice) GetDisplayMode() (EnableState, Return) { + var display EnableState + ret := nvmlDeviceGetDisplayMode(device, &display) + return display, ret +} + +// nvml.DeviceGetDisplayActive() +func (l *library) DeviceGetDisplayActive(device Device) (EnableState, Return) { + return device.GetDisplayActive() +} + +func (device nvmlDevice) GetDisplayActive() (EnableState, Return) { + var isActive EnableState + ret := nvmlDeviceGetDisplayActive(device, &isActive) + return isActive, ret +} + +// nvml.DeviceGetPersistenceMode() +func (l *library) DeviceGetPersistenceMode(device Device) (EnableState, Return) { + return device.GetPersistenceMode() +} + +func (device nvmlDevice) GetPersistenceMode() (EnableState, Return) { + var mode EnableState + ret := nvmlDeviceGetPersistenceMode(device, &mode) + return mode, ret +} + +// nvml.DeviceGetPciInfo() +func (l *library) DeviceGetPciInfo(device Device) (PciInfo, Return) { + return device.GetPciInfo() +} + +func (device nvmlDevice) GetPciInfo() (PciInfo, Return) { + var pci PciInfo + ret := nvmlDeviceGetPciInfo(device, &pci) + return pci, ret +} + +// nvml.DeviceGetMaxPcieLinkGeneration() +func (l *library) DeviceGetMaxPcieLinkGeneration(device Device) (int, Return) { + return device.GetMaxPcieLinkGeneration() +} + +func (device nvmlDevice) GetMaxPcieLinkGeneration() (int, Return) { + var maxLinkGen uint32 + ret := nvmlDeviceGetMaxPcieLinkGeneration(device, &maxLinkGen) + return int(maxLinkGen), ret +} + +// nvml.DeviceGetMaxPcieLinkWidth() +func (l *library) DeviceGetMaxPcieLinkWidth(device Device) (int, Return) { + return device.GetMaxPcieLinkWidth() +} + +func (device nvmlDevice) GetMaxPcieLinkWidth() (int, Return) { + var maxLinkWidth uint32 + ret := nvmlDeviceGetMaxPcieLinkWidth(device, &maxLinkWidth) + return int(maxLinkWidth), ret +} + +// nvml.DeviceGetCurrPcieLinkGeneration() +func (l *library) DeviceGetCurrPcieLinkGeneration(device Device) (int, Return) { + return device.GetCurrPcieLinkGeneration() +} + +func (device nvmlDevice) GetCurrPcieLinkGeneration() (int, Return) { + var currLinkGen uint32 + ret := nvmlDeviceGetCurrPcieLinkGeneration(device, &currLinkGen) + return int(currLinkGen), ret +} + +// nvml.DeviceGetCurrPcieLinkWidth() +func (l *library) DeviceGetCurrPcieLinkWidth(device Device) (int, Return) { + return device.GetCurrPcieLinkWidth() +} + +func (device nvmlDevice) GetCurrPcieLinkWidth() (int, Return) { + var currLinkWidth uint32 + ret := nvmlDeviceGetCurrPcieLinkWidth(device, &currLinkWidth) + return int(currLinkWidth), ret +} + +// nvml.DeviceGetPcieThroughput() +func (l *library) DeviceGetPcieThroughput(device Device, counter PcieUtilCounter) (uint32, Return) { + return device.GetPcieThroughput(counter) +} + +func (device nvmlDevice) GetPcieThroughput(counter PcieUtilCounter) (uint32, Return) { + var value uint32 + ret := nvmlDeviceGetPcieThroughput(device, counter, &value) + return value, ret +} + +// nvml.DeviceGetPcieReplayCounter() +func (l *library) DeviceGetPcieReplayCounter(device Device) (int, Return) { + return device.GetPcieReplayCounter() +} + +func (device nvmlDevice) GetPcieReplayCounter() (int, Return) { + var value uint32 + ret := nvmlDeviceGetPcieReplayCounter(device, &value) + return int(value), ret +} + +// nvml.nvmlDeviceGetClockInfo() +func (l *library) DeviceGetClockInfo(device Device, clockType ClockType) (uint32, Return) { + return device.GetClockInfo(clockType) +} + +func (device nvmlDevice) GetClockInfo(clockType ClockType) (uint32, Return) { + var clock uint32 + ret := nvmlDeviceGetClockInfo(device, clockType, &clock) + return clock, ret +} + +// nvml.DeviceGetMaxClockInfo() +func (l *library) DeviceGetMaxClockInfo(device Device, clockType ClockType) (uint32, Return) { + return device.GetMaxClockInfo(clockType) +} + +func (device nvmlDevice) GetMaxClockInfo(clockType ClockType) (uint32, Return) { + var clock uint32 + ret := nvmlDeviceGetMaxClockInfo(device, clockType, &clock) + return clock, ret +} + +// nvml.DeviceGetApplicationsClock() +// +// Deprecated: Applications clocks are deprecated and will be removed in CUDA 14.0. +func (l *library) DeviceGetApplicationsClock(device Device, clockType ClockType) (uint32, Return) { + return device.GetApplicationsClock(clockType) +} + +// Deprecated: Applications clocks are deprecated and will be removed in CUDA 14.0. +func (device nvmlDevice) GetApplicationsClock(clockType ClockType) (uint32, Return) { + var clockMHz uint32 + ret := nvmlDeviceGetApplicationsClock(device, clockType, &clockMHz) + return clockMHz, ret +} + +// nvml.DeviceGetDefaultApplicationsClock() +// +// Deprecated: Applications clocks are deprecated and will be removed in CUDA 14.0. +func (l *library) DeviceGetDefaultApplicationsClock(device Device, clockType ClockType) (uint32, Return) { + return device.GetDefaultApplicationsClock(clockType) +} + +// Deprecated: Applications clocks are deprecated and will be removed in CUDA 14.0. +func (device nvmlDevice) GetDefaultApplicationsClock(clockType ClockType) (uint32, Return) { + var clockMHz uint32 + ret := nvmlDeviceGetDefaultApplicationsClock(device, clockType, &clockMHz) + return clockMHz, ret +} + +// nvml.DeviceResetApplicationsClocks() +// +// Deprecated: Use DeviceResetMemoryLockedClocks for Memory Clocks and DeviceResetGpuLockedClocks for Graphics Clocks instead +func (l *library) DeviceResetApplicationsClocks(device Device) Return { + return device.ResetApplicationsClocks() +} + +// Deprecated: Use DeviceResetMemoryLockedClocks for Memory Clocks and DeviceResetGpuLockedClocks for Graphics Clocks instead +func (device nvmlDevice) ResetApplicationsClocks() Return { + return nvmlDeviceResetApplicationsClocks(device) +} + +// nvml.DeviceGetClock() +func (l *library) DeviceGetClock(device Device, clockType ClockType, clockId ClockId) (uint32, Return) { + return device.GetClock(clockType, clockId) +} + +func (device nvmlDevice) GetClock(clockType ClockType, clockId ClockId) (uint32, Return) { + var clockMHz uint32 + ret := nvmlDeviceGetClock(device, clockType, clockId, &clockMHz) + return clockMHz, ret +} + +// nvml.DeviceGetMaxCustomerBoostClock() +func (l *library) DeviceGetMaxCustomerBoostClock(device Device, clockType ClockType) (uint32, Return) { + return device.GetMaxCustomerBoostClock(clockType) +} + +func (device nvmlDevice) GetMaxCustomerBoostClock(clockType ClockType) (uint32, Return) { + var clockMHz uint32 + ret := nvmlDeviceGetMaxCustomerBoostClock(device, clockType, &clockMHz) + return clockMHz, ret +} + +// nvml.DeviceGetSupportedMemoryClocks() +func (l *library) DeviceGetSupportedMemoryClocks(device Device) (int, uint32, Return) { + return device.GetSupportedMemoryClocks() +} + +func (device nvmlDevice) GetSupportedMemoryClocks() (int, uint32, Return) { + var count, clocksMHz uint32 + ret := nvmlDeviceGetSupportedMemoryClocks(device, &count, &clocksMHz) + return int(count), clocksMHz, ret +} + +// nvml.DeviceGetSupportedGraphicsClocks() +func (l *library) DeviceGetSupportedGraphicsClocks(device Device, memoryClockMHz int) (int, uint32, Return) { + return device.GetSupportedGraphicsClocks(memoryClockMHz) +} + +func (device nvmlDevice) GetSupportedGraphicsClocks(memoryClockMHz int) (int, uint32, Return) { + var count, clocksMHz uint32 + ret := nvmlDeviceGetSupportedGraphicsClocks(device, uint32(memoryClockMHz), &count, &clocksMHz) + return int(count), clocksMHz, ret +} + +// nvml.DeviceGetAutoBoostedClocksEnabled() +func (l *library) DeviceGetAutoBoostedClocksEnabled(device Device) (EnableState, EnableState, Return) { + return device.GetAutoBoostedClocksEnabled() +} + +func (device nvmlDevice) GetAutoBoostedClocksEnabled() (EnableState, EnableState, Return) { + var isEnabled, defaultIsEnabled EnableState + ret := nvmlDeviceGetAutoBoostedClocksEnabled(device, &isEnabled, &defaultIsEnabled) + return isEnabled, defaultIsEnabled, ret +} + +// nvml.DeviceSetAutoBoostedClocksEnabled() +func (l *library) DeviceSetAutoBoostedClocksEnabled(device Device, enabled EnableState) Return { + return device.SetAutoBoostedClocksEnabled(enabled) +} + +func (device nvmlDevice) SetAutoBoostedClocksEnabled(enabled EnableState) Return { + return nvmlDeviceSetAutoBoostedClocksEnabled(device, enabled) +} + +// nvml.DeviceSetDefaultAutoBoostedClocksEnabled() +func (l *library) DeviceSetDefaultAutoBoostedClocksEnabled(device Device, enabled EnableState, flags uint32) Return { + return device.SetDefaultAutoBoostedClocksEnabled(enabled, flags) +} + +func (device nvmlDevice) SetDefaultAutoBoostedClocksEnabled(enabled EnableState, flags uint32) Return { + return nvmlDeviceSetDefaultAutoBoostedClocksEnabled(device, enabled, flags) +} + +// nvml.DeviceGetFanSpeed() +func (l *library) DeviceGetFanSpeed(device Device) (uint32, Return) { + return device.GetFanSpeed() +} + +func (device nvmlDevice) GetFanSpeed() (uint32, Return) { + var speed uint32 + ret := nvmlDeviceGetFanSpeed(device, &speed) + return speed, ret +} + +// nvml.DeviceGetFanSpeed_v2() +func (l *library) DeviceGetFanSpeed_v2(device Device, fan int) (uint32, Return) { + return device.GetFanSpeed_v2(fan) +} + +func (device nvmlDevice) GetFanSpeed_v2(fan int) (uint32, Return) { + var speed uint32 + ret := nvmlDeviceGetFanSpeed_v2(device, uint32(fan), &speed) + return speed, ret +} + +// nvml.DeviceGetNumFans() +func (l *library) DeviceGetNumFans(device Device) (int, Return) { + return device.GetNumFans() +} + +func (device nvmlDevice) GetNumFans() (int, Return) { + var numFans uint32 + ret := nvmlDeviceGetNumFans(device, &numFans) + return int(numFans), ret +} + +// nvml.DeviceGetTemperature() +// +// Deprecated: Use DeviceGetTemperatureV instead. +func (l *library) DeviceGetTemperature(device Device, sensorType TemperatureSensors) (uint32, Return) { + return device.GetTemperature(sensorType) +} + +// Deprecated: Use DeviceGetTemperatureV instead. +func (device nvmlDevice) GetTemperature(sensorType TemperatureSensors) (uint32, Return) { + var temp uint32 + ret := nvmlDeviceGetTemperature(device, sensorType, &temp) + return temp, ret +} + +// nvml.DeviceGetTemperatureThreshold() +func (l *library) DeviceGetTemperatureThreshold(device Device, thresholdType TemperatureThresholds) (uint32, Return) { + return device.GetTemperatureThreshold(thresholdType) +} + +func (device nvmlDevice) GetTemperatureThreshold(thresholdType TemperatureThresholds) (uint32, Return) { + var temp uint32 + ret := nvmlDeviceGetTemperatureThreshold(device, thresholdType, &temp) + return temp, ret +} + +// nvml.DeviceSetTemperatureThreshold() +func (l *library) DeviceSetTemperatureThreshold(device Device, thresholdType TemperatureThresholds, temp int) Return { + return device.SetTemperatureThreshold(thresholdType, temp) +} + +func (device nvmlDevice) SetTemperatureThreshold(thresholdType TemperatureThresholds, temp int) Return { + t := int32(temp) + ret := nvmlDeviceSetTemperatureThreshold(device, thresholdType, &t) + return ret +} + +// nvml.DeviceGetPerformanceState() +func (l *library) DeviceGetPerformanceState(device Device) (Pstates, Return) { + return device.GetPerformanceState() +} + +func (device nvmlDevice) GetPerformanceState() (Pstates, Return) { + var pState Pstates + ret := nvmlDeviceGetPerformanceState(device, &pState) + return pState, ret +} + +// nvml.DeviceGetCurrentClocksThrottleReasons() +// +// Deprecated: Use DeviceGetCurrentClocksEventReasons instead +func (l *library) DeviceGetCurrentClocksThrottleReasons(device Device) (uint64, Return) { + return device.GetCurrentClocksThrottleReasons() +} + +// Deprecated: Use DeviceGetCurrentClocksEventReasons instead +func (device nvmlDevice) GetCurrentClocksThrottleReasons() (uint64, Return) { + var clocksThrottleReasons uint64 + ret := nvmlDeviceGetCurrentClocksThrottleReasons(device, &clocksThrottleReasons) + return clocksThrottleReasons, ret +} + +// nvml.DeviceGetSupportedClocksThrottleReasons() +// +// Deprecated: Use DeviceGetSupportedClocksEventReasons instead +func (l *library) DeviceGetSupportedClocksThrottleReasons(device Device) (uint64, Return) { + return device.GetSupportedClocksThrottleReasons() +} + +// Deprecated: Use DeviceGetSupportedClocksEventReasons instead +func (device nvmlDevice) GetSupportedClocksThrottleReasons() (uint64, Return) { + var supportedClocksThrottleReasons uint64 + ret := nvmlDeviceGetSupportedClocksThrottleReasons(device, &supportedClocksThrottleReasons) + return supportedClocksThrottleReasons, ret +} + +// nvml.DeviceGetPowerState() +// +// Deprecated: Use DeviceGetPerformanceState instead +func (l *library) DeviceGetPowerState(device Device) (Pstates, Return) { + return device.GetPowerState() +} + +// Deprecated: Use DeviceGetPerformanceState instead +func (device nvmlDevice) GetPowerState() (Pstates, Return) { + var pState Pstates + ret := nvmlDeviceGetPowerState(device, &pState) + return pState, ret +} + +// nvml.DeviceGetPowerManagementMode() +// +// Deprecated: This will be removed in a future version +func (l *library) DeviceGetPowerManagementMode(device Device) (EnableState, Return) { + return device.GetPowerManagementMode() +} + +// Deprecated: This will be removed in a future version +func (device nvmlDevice) GetPowerManagementMode() (EnableState, Return) { + var mode EnableState + ret := nvmlDeviceGetPowerManagementMode(device, &mode) + return mode, ret +} + +// nvml.DeviceGetPowerManagementLimit() +func (l *library) DeviceGetPowerManagementLimit(device Device) (uint32, Return) { + return device.GetPowerManagementLimit() +} + +func (device nvmlDevice) GetPowerManagementLimit() (uint32, Return) { + var limit uint32 + ret := nvmlDeviceGetPowerManagementLimit(device, &limit) + return limit, ret +} + +// nvml.DeviceGetPowerManagementLimitConstraints() +func (l *library) DeviceGetPowerManagementLimitConstraints(device Device) (uint32, uint32, Return) { + return device.GetPowerManagementLimitConstraints() +} + +func (device nvmlDevice) GetPowerManagementLimitConstraints() (uint32, uint32, Return) { + var minLimit, maxLimit uint32 + ret := nvmlDeviceGetPowerManagementLimitConstraints(device, &minLimit, &maxLimit) + return minLimit, maxLimit, ret +} + +// nvml.DeviceGetPowerManagementDefaultLimit() +func (l *library) DeviceGetPowerManagementDefaultLimit(device Device) (uint32, Return) { + return device.GetPowerManagementDefaultLimit() +} + +func (device nvmlDevice) GetPowerManagementDefaultLimit() (uint32, Return) { + var defaultLimit uint32 + ret := nvmlDeviceGetPowerManagementDefaultLimit(device, &defaultLimit) + return defaultLimit, ret +} + +// nvml.DeviceGetPowerUsage() +func (l *library) DeviceGetPowerUsage(device Device) (uint32, Return) { + return device.GetPowerUsage() +} + +func (device nvmlDevice) GetPowerUsage() (uint32, Return) { + var power uint32 + ret := nvmlDeviceGetPowerUsage(device, &power) + return power, ret +} + +func (l *library) DeviceGetPowerMizerMode_v1(device Device) (DevicePowerMizerModes_v1, Return) { + return device.GetPowerMizerMode_v1() +} + +func (device nvmlDevice) GetPowerMizerMode_v1() (DevicePowerMizerModes_v1, Return) { + var devicePowerMizerModes DevicePowerMizerModes_v1 + ret := nvmlDeviceGetPowerMizerMode_v1(device, &devicePowerMizerModes) + return devicePowerMizerModes, ret +} + +// nvml.DeviceGetTotalEnergyConsumption() +func (l *library) DeviceGetTotalEnergyConsumption(device Device) (uint64, Return) { + return device.GetTotalEnergyConsumption() +} + +func (device nvmlDevice) GetTotalEnergyConsumption() (uint64, Return) { + var energy uint64 + ret := nvmlDeviceGetTotalEnergyConsumption(device, &energy) + return energy, ret +} + +// nvml.DeviceGetEnforcedPowerLimit() +func (l *library) DeviceGetEnforcedPowerLimit(device Device) (uint32, Return) { + return device.GetEnforcedPowerLimit() +} + +func (device nvmlDevice) GetEnforcedPowerLimit() (uint32, Return) { + var limit uint32 + ret := nvmlDeviceGetEnforcedPowerLimit(device, &limit) + return limit, ret +} + +// nvml.DeviceGetGpuOperationMode() +func (l *library) DeviceGetGpuOperationMode(device Device) (GpuOperationMode, GpuOperationMode, Return) { + return device.GetGpuOperationMode() +} + +func (device nvmlDevice) GetGpuOperationMode() (GpuOperationMode, GpuOperationMode, Return) { + var current, pending GpuOperationMode + ret := nvmlDeviceGetGpuOperationMode(device, ¤t, &pending) + return current, pending, ret +} + +// nvml.DeviceGetMemoryInfo() +func (l *library) DeviceGetMemoryInfo(device Device) (Memory, Return) { + return device.GetMemoryInfo() +} + +func (device nvmlDevice) GetMemoryInfo() (Memory, Return) { + var memory Memory + ret := nvmlDeviceGetMemoryInfo(device, &memory) + return memory, ret +} + +// nvml.DeviceGetMemoryInfo_v2() +func (l *library) DeviceGetMemoryInfo_v2(device Device) (Memory_v2, Return) { + return device.GetMemoryInfo_v2() +} + +func (device nvmlDevice) GetMemoryInfo_v2() (Memory_v2, Return) { + var memory Memory_v2 + memory.Version = STRUCT_VERSION(memory, 2) + ret := nvmlDeviceGetMemoryInfo_v2(device, &memory) + return memory, ret +} + +// nvml.DeviceGetComputeMode() +func (l *library) DeviceGetComputeMode(device Device) (ComputeMode, Return) { + return device.GetComputeMode() +} + +func (device nvmlDevice) GetComputeMode() (ComputeMode, Return) { + var mode ComputeMode + ret := nvmlDeviceGetComputeMode(device, &mode) + return mode, ret +} + +// nvml.DeviceGetCudaComputeCapability() +func (l *library) DeviceGetCudaComputeCapability(device Device) (int, int, Return) { + return device.GetCudaComputeCapability() +} + +func (device nvmlDevice) GetCudaComputeCapability() (int, int, Return) { + var major, minor int32 + ret := nvmlDeviceGetCudaComputeCapability(device, &major, &minor) + return int(major), int(minor), ret +} + +// nvml.DeviceGetEccMode() +func (l *library) DeviceGetEccMode(device Device) (EnableState, EnableState, Return) { + return device.GetEccMode() +} + +func (device nvmlDevice) GetEccMode() (EnableState, EnableState, Return) { + var current, pending EnableState + ret := nvmlDeviceGetEccMode(device, ¤t, &pending) + return current, pending, ret +} + +// nvml.DeviceGetBoardId() +func (l *library) DeviceGetBoardId(device Device) (uint32, Return) { + return device.GetBoardId() +} + +func (device nvmlDevice) GetBoardId() (uint32, Return) { + var boardId uint32 + ret := nvmlDeviceGetBoardId(device, &boardId) + return boardId, ret +} + +// nvml.DeviceGetMultiGpuBoard() +func (l *library) DeviceGetMultiGpuBoard(device Device) (int, Return) { + return device.GetMultiGpuBoard() +} + +func (device nvmlDevice) GetMultiGpuBoard() (int, Return) { + var multiGpuBool uint32 + ret := nvmlDeviceGetMultiGpuBoard(device, &multiGpuBool) + return int(multiGpuBool), ret +} + +// nvml.DeviceGetTotalEccErrors() +func (l *library) DeviceGetTotalEccErrors(device Device, errorType MemoryErrorType, counterType EccCounterType) (uint64, Return) { + return device.GetTotalEccErrors(errorType, counterType) +} + +func (device nvmlDevice) GetTotalEccErrors(errorType MemoryErrorType, counterType EccCounterType) (uint64, Return) { + var eccCounts uint64 + ret := nvmlDeviceGetTotalEccErrors(device, errorType, counterType, &eccCounts) + return eccCounts, ret +} + +// nvml.DeviceGetDetailedEccErrors() +// +// Deprecated: See DeviceGetMemoryErrorCounter +func (l *library) DeviceGetDetailedEccErrors(device Device, errorType MemoryErrorType, counterType EccCounterType) (EccErrorCounts, Return) { + return device.GetDetailedEccErrors(errorType, counterType) +} + +// Deprecated: See DeviceGetMemoryErrorCounter +func (device nvmlDevice) GetDetailedEccErrors(errorType MemoryErrorType, counterType EccCounterType) (EccErrorCounts, Return) { + var eccCounts EccErrorCounts + ret := nvmlDeviceGetDetailedEccErrors(device, errorType, counterType, &eccCounts) + return eccCounts, ret +} + +// nvml.DeviceGetMemoryErrorCounter() +func (l *library) DeviceGetMemoryErrorCounter(device Device, errorType MemoryErrorType, counterType EccCounterType, locationType MemoryLocation) (uint64, Return) { + return device.GetMemoryErrorCounter(errorType, counterType, locationType) +} + +func (device nvmlDevice) GetMemoryErrorCounter(errorType MemoryErrorType, counterType EccCounterType, locationType MemoryLocation) (uint64, Return) { + var count uint64 + ret := nvmlDeviceGetMemoryErrorCounter(device, errorType, counterType, locationType, &count) + return count, ret +} + +// nvml.DeviceGetUtilizationRates() +func (l *library) DeviceGetUtilizationRates(device Device) (Utilization, Return) { + return device.GetUtilizationRates() +} + +func (device nvmlDevice) GetUtilizationRates() (Utilization, Return) { + var utilization Utilization + ret := nvmlDeviceGetUtilizationRates(device, &utilization) + return utilization, ret +} + +// nvml.DeviceGetEncoderUtilization() +func (l *library) DeviceGetEncoderUtilization(device Device) (uint32, uint32, Return) { + return device.GetEncoderUtilization() +} + +func (device nvmlDevice) GetEncoderUtilization() (uint32, uint32, Return) { + var utilization, samplingPeriodUs uint32 + ret := nvmlDeviceGetEncoderUtilization(device, &utilization, &samplingPeriodUs) + return utilization, samplingPeriodUs, ret +} + +// nvml.DeviceGetEncoderCapacity() +func (l *library) DeviceGetEncoderCapacity(device Device, encoderQueryType EncoderType) (int, Return) { + return device.GetEncoderCapacity(encoderQueryType) +} + +func (device nvmlDevice) GetEncoderCapacity(encoderQueryType EncoderType) (int, Return) { + var encoderCapacity uint32 + ret := nvmlDeviceGetEncoderCapacity(device, encoderQueryType, &encoderCapacity) + return int(encoderCapacity), ret +} + +// nvml.DeviceGetEncoderStats() +func (l *library) DeviceGetEncoderStats(device Device) (int, uint32, uint32, Return) { + return device.GetEncoderStats() +} + +func (device nvmlDevice) GetEncoderStats() (int, uint32, uint32, Return) { + var sessionCount, averageFps, averageLatency uint32 + ret := nvmlDeviceGetEncoderStats(device, &sessionCount, &averageFps, &averageLatency) + return int(sessionCount), averageFps, averageLatency, ret +} + +// nvml.DeviceGetEncoderSessions() +func (l *library) DeviceGetEncoderSessions(device Device) ([]EncoderSessionInfo, Return) { + return device.GetEncoderSessions() +} + +func (device nvmlDevice) GetEncoderSessions() ([]EncoderSessionInfo, Return) { + var sessionCount uint32 = 1 // Will be reduced upon returning + for { + sessionInfos := make([]EncoderSessionInfo, sessionCount) + ret := nvmlDeviceGetEncoderSessions(device, &sessionCount, &sessionInfos[0]) + if ret == SUCCESS { + return sessionInfos[:sessionCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + sessionCount *= 2 + } +} + +// nvml.DeviceGetDecoderUtilization() +func (l *library) DeviceGetDecoderUtilization(device Device) (uint32, uint32, Return) { + return device.GetDecoderUtilization() +} + +func (device nvmlDevice) GetDecoderUtilization() (uint32, uint32, Return) { + var utilization, samplingPeriodUs uint32 + ret := nvmlDeviceGetDecoderUtilization(device, &utilization, &samplingPeriodUs) + return utilization, samplingPeriodUs, ret +} + +// nvml.DeviceGetFBCStats() +func (l *library) DeviceGetFBCStats(device Device) (FBCStats, Return) { + return device.GetFBCStats() +} + +func (device nvmlDevice) GetFBCStats() (FBCStats, Return) { + var fbcStats FBCStats + ret := nvmlDeviceGetFBCStats(device, &fbcStats) + return fbcStats, ret +} + +// nvml.DeviceGetFBCSessions() +func (l *library) DeviceGetFBCSessions(device Device) ([]FBCSessionInfo, Return) { + return device.GetFBCSessions() +} + +func (device nvmlDevice) GetFBCSessions() ([]FBCSessionInfo, Return) { + var sessionCount uint32 = 1 // Will be reduced upon returning + for { + sessionInfo := make([]FBCSessionInfo, sessionCount) + ret := nvmlDeviceGetFBCSessions(device, &sessionCount, &sessionInfo[0]) + if ret == SUCCESS { + return sessionInfo[:sessionCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + sessionCount *= 2 + } +} + +// nvml.DeviceGetDriverModel() +func (l *library) DeviceGetDriverModel(device Device) (DriverModel, DriverModel, Return) { + return device.GetDriverModel() +} + +func (device nvmlDevice) GetDriverModel() (DriverModel, DriverModel, Return) { + var current, pending DriverModel + ret := nvmlDeviceGetDriverModel(device, ¤t, &pending) + return current, pending, ret +} + +// nvml.DeviceGetVbiosVersion() +func (l *library) DeviceGetVbiosVersion(device Device) (string, Return) { + return device.GetVbiosVersion() +} + +func (device nvmlDevice) GetVbiosVersion() (string, Return) { + version := make([]byte, DEVICE_VBIOS_VERSION_BUFFER_SIZE) + ret := nvmlDeviceGetVbiosVersion(device, &version[0], DEVICE_VBIOS_VERSION_BUFFER_SIZE) + return string(version[:clen(version)]), ret +} + +// nvml.DeviceGetBridgeChipInfo() +func (l *library) DeviceGetBridgeChipInfo(device Device) (BridgeChipHierarchy, Return) { + return device.GetBridgeChipInfo() +} + +func (device nvmlDevice) GetBridgeChipInfo() (BridgeChipHierarchy, Return) { + var bridgeHierarchy BridgeChipHierarchy + ret := nvmlDeviceGetBridgeChipInfo(device, &bridgeHierarchy) + return bridgeHierarchy, ret +} + +// nvml.DeviceGetComputeRunningProcesses() +func deviceGetComputeRunningProcesses_v1(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v1, infoCount) + ret := nvmlDeviceGetComputeRunningProcesses_v1(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v1Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetComputeRunningProcesses_v2(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v2, infoCount) + ret := nvmlDeviceGetComputeRunningProcesses_v2(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v2Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetComputeRunningProcesses_v3(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo, infoCount) + ret := nvmlDeviceGetComputeRunningProcesses_v3(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return infos[:infoCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func (l *library) DeviceGetComputeRunningProcesses(device Device) ([]ProcessInfo, Return) { + return device.GetComputeRunningProcesses() +} + +func (device nvmlDevice) GetComputeRunningProcesses() ([]ProcessInfo, Return) { + return deviceGetComputeRunningProcesses(device) +} + +// nvml.DeviceGetGraphicsRunningProcesses() +func deviceGetGraphicsRunningProcesses_v1(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v1, infoCount) + ret := nvmlDeviceGetGraphicsRunningProcesses_v1(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v1Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetGraphicsRunningProcesses_v2(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v2, infoCount) + ret := nvmlDeviceGetGraphicsRunningProcesses_v2(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v2Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetGraphicsRunningProcesses_v3(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo, infoCount) + ret := nvmlDeviceGetGraphicsRunningProcesses_v3(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return infos[:infoCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func (l *library) DeviceGetGraphicsRunningProcesses(device Device) ([]ProcessInfo, Return) { + return device.GetGraphicsRunningProcesses() +} + +func (device nvmlDevice) GetGraphicsRunningProcesses() ([]ProcessInfo, Return) { + return deviceGetGraphicsRunningProcesses(device) +} + +// nvml.DeviceGetMPSComputeRunningProcesses() +func deviceGetMPSComputeRunningProcesses_v1(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v1, infoCount) + ret := nvmlDeviceGetMPSComputeRunningProcesses_v1(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v1Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetMPSComputeRunningProcesses_v2(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo_v2, infoCount) + ret := nvmlDeviceGetMPSComputeRunningProcesses_v2(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return ProcessInfo_v2Slice(infos[:infoCount]).ToProcessInfoSlice(), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func deviceGetMPSComputeRunningProcesses_v3(device nvmlDevice) ([]ProcessInfo, Return) { + var infoCount uint32 = 1 // Will be reduced upon returning + for { + infos := make([]ProcessInfo, infoCount) + ret := nvmlDeviceGetMPSComputeRunningProcesses_v3(device, &infoCount, &infos[0]) + if ret == SUCCESS { + return infos[:infoCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + infoCount *= 2 + } +} + +func (l *library) DeviceGetMPSComputeRunningProcesses(device Device) ([]ProcessInfo, Return) { + return device.GetMPSComputeRunningProcesses() +} + +func (device nvmlDevice) GetMPSComputeRunningProcesses() ([]ProcessInfo, Return) { + return deviceGetMPSComputeRunningProcesses(device) +} + +// nvml.DeviceOnSameBoard() +func (l *library) DeviceOnSameBoard(device1 Device, device2 Device) (int, Return) { + return device1.OnSameBoard(device2) +} + +func (device1 nvmlDevice) OnSameBoard(device2 Device) (int, Return) { + var onSameBoard int32 + ret := nvmlDeviceOnSameBoard(device1, nvmlDeviceHandle(device2), &onSameBoard) + return int(onSameBoard), ret +} + +// nvml.DeviceGetAPIRestriction() +func (l *library) DeviceGetAPIRestriction(device Device, apiType RestrictedAPI) (EnableState, Return) { + return device.GetAPIRestriction(apiType) +} + +func (device nvmlDevice) GetAPIRestriction(apiType RestrictedAPI) (EnableState, Return) { + var isRestricted EnableState + ret := nvmlDeviceGetAPIRestriction(device, apiType, &isRestricted) + return isRestricted, ret +} + +// nvml.DeviceGetSamples() +func (l *library) DeviceGetSamples(device Device, samplingType SamplingType, lastSeenTimestamp uint64) (ValueType, []Sample, Return) { + return device.GetSamples(samplingType, lastSeenTimestamp) +} + +func (device nvmlDevice) GetSamples(samplingType SamplingType, lastSeenTimestamp uint64) (ValueType, []Sample, Return) { + var sampleValType ValueType + var sampleCount uint32 + ret := nvmlDeviceGetSamples(device, samplingType, lastSeenTimestamp, &sampleValType, &sampleCount, nil) + if ret != SUCCESS { + return sampleValType, nil, ret + } + if sampleCount == 0 { + return sampleValType, []Sample{}, ret + } + samples := make([]Sample, sampleCount) + ret = nvmlDeviceGetSamples(device, samplingType, lastSeenTimestamp, &sampleValType, &sampleCount, &samples[0]) + return sampleValType, samples, ret +} + +// nvml.DeviceGetBAR1MemoryInfo() +func (l *library) DeviceGetBAR1MemoryInfo(device Device) (BAR1Memory, Return) { + return device.GetBAR1MemoryInfo() +} + +func (device nvmlDevice) GetBAR1MemoryInfo() (BAR1Memory, Return) { + var bar1Memory BAR1Memory + ret := nvmlDeviceGetBAR1MemoryInfo(device, &bar1Memory) + return bar1Memory, ret +} + +// nvml.DeviceGetViolationStatus() +// +// Deprecated: Use DeviceGetFieldValues instead. +func (l *library) DeviceGetViolationStatus(device Device, perfPolicyType PerfPolicyType) (ViolationTime, Return) { + return device.GetViolationStatus(perfPolicyType) +} + +// Deprecated: Use DeviceGetFieldValues instead. +func (device nvmlDevice) GetViolationStatus(perfPolicyType PerfPolicyType) (ViolationTime, Return) { + var violTime ViolationTime + ret := nvmlDeviceGetViolationStatus(device, perfPolicyType, &violTime) + return violTime, ret +} + +// nvml.DeviceGetIrqNum() +func (l *library) DeviceGetIrqNum(device Device) (int, Return) { + return device.GetIrqNum() +} + +func (device nvmlDevice) GetIrqNum() (int, Return) { + var irqNum uint32 + ret := nvmlDeviceGetIrqNum(device, &irqNum) + return int(irqNum), ret +} + +// nvml.DeviceGetNumGpuCores() +func (l *library) DeviceGetNumGpuCores(device Device) (int, Return) { + return device.GetNumGpuCores() +} + +func (device nvmlDevice) GetNumGpuCores() (int, Return) { + var numCores uint32 + ret := nvmlDeviceGetNumGpuCores(device, &numCores) + return int(numCores), ret +} + +// nvml.DeviceGetPowerSource() +func (l *library) DeviceGetPowerSource(device Device) (PowerSource, Return) { + return device.GetPowerSource() +} + +func (device nvmlDevice) GetPowerSource() (PowerSource, Return) { + var powerSource PowerSource + ret := nvmlDeviceGetPowerSource(device, &powerSource) + return powerSource, ret +} + +// nvml.DeviceGetMemoryBusWidth() +func (l *library) DeviceGetMemoryBusWidth(device Device) (uint32, Return) { + return device.GetMemoryBusWidth() +} + +func (device nvmlDevice) GetMemoryBusWidth() (uint32, Return) { + var busWidth uint32 + ret := nvmlDeviceGetMemoryBusWidth(device, &busWidth) + return busWidth, ret +} + +// nvml.DeviceGetPcieLinkMaxSpeed() +func (l *library) DeviceGetPcieLinkMaxSpeed(device Device) (uint32, Return) { + return device.GetPcieLinkMaxSpeed() +} + +func (device nvmlDevice) GetPcieLinkMaxSpeed() (uint32, Return) { + var maxSpeed uint32 + ret := nvmlDeviceGetPcieLinkMaxSpeed(device, &maxSpeed) + return maxSpeed, ret +} + +// nvml.DeviceGetAdaptiveClockInfoStatus() +func (l *library) DeviceGetAdaptiveClockInfoStatus(device Device) (uint32, Return) { + return device.GetAdaptiveClockInfoStatus() +} + +func (device nvmlDevice) GetAdaptiveClockInfoStatus() (uint32, Return) { + var adaptiveClockStatus uint32 + ret := nvmlDeviceGetAdaptiveClockInfoStatus(device, &adaptiveClockStatus) + return adaptiveClockStatus, ret +} + +// nvml.DeviceGetAccountingMode() +func (l *library) DeviceGetAccountingMode(device Device) (EnableState, Return) { + return device.GetAccountingMode() +} + +func (device nvmlDevice) GetAccountingMode() (EnableState, Return) { + var mode EnableState + ret := nvmlDeviceGetAccountingMode(device, &mode) + return mode, ret +} + +func (l *library) DeviceGetPdi(device Device) (Pdi, Return) { + return device.GetPdi() +} + +func (device nvmlDevice) GetPdi() (Pdi, Return) { + var pdi Pdi + pdi.Version = STRUCT_VERSION(pdi, 1) + ret := nvmlDeviceGetPdi(device, &pdi) + return pdi, ret +} + +// nvml.DeviceGetAccountingStats() +func (l *library) DeviceGetAccountingStats(device Device, pid uint32) (AccountingStats, Return) { + return device.GetAccountingStats(pid) +} + +func (device nvmlDevice) GetAccountingStats(pid uint32) (AccountingStats, Return) { + var stats AccountingStats + ret := nvmlDeviceGetAccountingStats(device, pid, &stats) + return stats, ret +} + +// nvml.DeviceGetAccountingPids() +func (l *library) DeviceGetAccountingPids(device Device) ([]int, Return) { + return device.GetAccountingPids() +} + +func (device nvmlDevice) GetAccountingPids() ([]int, Return) { + var count uint32 = 1 // Will be reduced upon returning + for { + pids := make([]uint32, count) + ret := nvmlDeviceGetAccountingPids(device, &count, &pids[0]) + if ret == SUCCESS { + return uint32SliceToIntSlice(pids[:count]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + count *= 2 + } +} + +// nvml.DeviceGetAccountingBufferSize() +func (l *library) DeviceGetAccountingBufferSize(device Device) (int, Return) { + return device.GetAccountingBufferSize() +} + +func (device nvmlDevice) GetAccountingBufferSize() (int, Return) { + var bufferSize uint32 + ret := nvmlDeviceGetAccountingBufferSize(device, &bufferSize) + return int(bufferSize), ret +} + +// nvml.DeviceGetRetiredPages() +func (l *library) DeviceGetRetiredPages(device Device, cause PageRetirementCause) ([]uint64, Return) { + return device.GetRetiredPages(cause) +} + +func (device nvmlDevice) GetRetiredPages(cause PageRetirementCause) ([]uint64, Return) { + var pageCount uint32 = 1 // Will be reduced upon returning + for { + addresses := make([]uint64, pageCount) + ret := nvmlDeviceGetRetiredPages(device, cause, &pageCount, &addresses[0]) + if ret == SUCCESS { + return addresses[:pageCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + pageCount *= 2 + } +} + +// nvml.DeviceGetRetiredPages_v2() +func (l *library) DeviceGetRetiredPages_v2(device Device, cause PageRetirementCause) ([]uint64, []uint64, Return) { + return device.GetRetiredPages_v2(cause) +} + +func (device nvmlDevice) GetRetiredPages_v2(cause PageRetirementCause) ([]uint64, []uint64, Return) { + var pageCount uint32 = 1 // Will be reduced upon returning + for { + addresses := make([]uint64, pageCount) + timestamps := make([]uint64, pageCount) + ret := nvmlDeviceGetRetiredPages_v2(device, cause, &pageCount, &addresses[0], ×tamps[0]) + if ret == SUCCESS { + return addresses[:pageCount], timestamps[:pageCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, nil, ret + } + pageCount *= 2 + } +} + +// nvml.DeviceGetRetiredPagesPendingStatus() +func (l *library) DeviceGetRetiredPagesPendingStatus(device Device) (EnableState, Return) { + return device.GetRetiredPagesPendingStatus() +} + +func (device nvmlDevice) GetRetiredPagesPendingStatus() (EnableState, Return) { + var isPending EnableState + ret := nvmlDeviceGetRetiredPagesPendingStatus(device, &isPending) + return isPending, ret +} + +// nvml.DeviceSetPersistenceMode() +func (l *library) DeviceSetPersistenceMode(device Device, mode EnableState) Return { + return device.SetPersistenceMode(mode) +} + +func (device nvmlDevice) SetPersistenceMode(mode EnableState) Return { + return nvmlDeviceSetPersistenceMode(device, mode) +} + +// nvml.DeviceSetComputeMode() +func (l *library) DeviceSetComputeMode(device Device, mode ComputeMode) Return { + return device.SetComputeMode(mode) +} + +func (device nvmlDevice) SetComputeMode(mode ComputeMode) Return { + return nvmlDeviceSetComputeMode(device, mode) +} + +// nvml.DeviceSetEccMode() +func (l *library) DeviceSetEccMode(device Device, ecc EnableState) Return { + return device.SetEccMode(ecc) +} + +func (device nvmlDevice) SetEccMode(ecc EnableState) Return { + return nvmlDeviceSetEccMode(device, ecc) +} + +// nvml.DeviceClearEccErrorCounts() +func (l *library) DeviceClearEccErrorCounts(device Device, counterType EccCounterType) Return { + return device.ClearEccErrorCounts(counterType) +} + +func (device nvmlDevice) ClearEccErrorCounts(counterType EccCounterType) Return { + return nvmlDeviceClearEccErrorCounts(device, counterType) +} + +// nvml.DeviceSetDriverModel() +func (l *library) DeviceSetDriverModel(device Device, driverModel DriverModel, flags uint32) Return { + return device.SetDriverModel(driverModel, flags) +} + +func (device nvmlDevice) SetDriverModel(driverModel DriverModel, flags uint32) Return { + return nvmlDeviceSetDriverModel(device, driverModel, flags) +} + +// nvml.DeviceSetGpuLockedClocks() +func (l *library) DeviceSetGpuLockedClocks(device Device, minGpuClockMHz uint32, maxGpuClockMHz uint32) Return { + return device.SetGpuLockedClocks(minGpuClockMHz, maxGpuClockMHz) +} + +func (device nvmlDevice) SetGpuLockedClocks(minGpuClockMHz uint32, maxGpuClockMHz uint32) Return { + return nvmlDeviceSetGpuLockedClocks(device, minGpuClockMHz, maxGpuClockMHz) +} + +// nvml.DeviceResetGpuLockedClocks() +func (l *library) DeviceResetGpuLockedClocks(device Device) Return { + return device.ResetGpuLockedClocks() +} + +func (device nvmlDevice) ResetGpuLockedClocks() Return { + return nvmlDeviceResetGpuLockedClocks(device) +} + +// nvmlDeviceSetMemoryLockedClocks() +func (l *library) DeviceSetMemoryLockedClocks(device Device, minMemClockMHz uint32, maxMemClockMHz uint32) Return { + return device.SetMemoryLockedClocks(minMemClockMHz, maxMemClockMHz) +} + +func (device nvmlDevice) SetMemoryLockedClocks(minMemClockMHz uint32, maxMemClockMHz uint32) Return { + return nvmlDeviceSetMemoryLockedClocks(device, minMemClockMHz, maxMemClockMHz) +} + +// nvmlDeviceResetMemoryLockedClocks() +func (l *library) DeviceResetMemoryLockedClocks(device Device) Return { + return device.ResetMemoryLockedClocks() +} + +func (device nvmlDevice) ResetMemoryLockedClocks() Return { + return nvmlDeviceResetMemoryLockedClocks(device) +} + +// nvml.DeviceGetClkMonStatus() +func (l *library) DeviceGetClkMonStatus(device Device) (ClkMonStatus, Return) { + return device.GetClkMonStatus() +} + +func (device nvmlDevice) GetClkMonStatus() (ClkMonStatus, Return) { + var status ClkMonStatus + ret := nvmlDeviceGetClkMonStatus(device, &status) + return status, ret +} + +// nvml.DeviceSetApplicationsClocks() +// +// Deprecated: Use DeviceSetMemoryLockedClocks for Memory Clocks and DeviceSetGpuLockedClocks for Graphics Clocks instead +func (l *library) DeviceSetApplicationsClocks(device Device, memClockMHz uint32, graphicsClockMHz uint32) Return { + return device.SetApplicationsClocks(memClockMHz, graphicsClockMHz) +} + +// Deprecated: Use DeviceSetMemoryLockedClocks for Memory Clocks and DeviceSetGpuLockedClocks for Graphics Clocks instead +func (device nvmlDevice) SetApplicationsClocks(memClockMHz uint32, graphicsClockMHz uint32) Return { + return nvmlDeviceSetApplicationsClocks(device, memClockMHz, graphicsClockMHz) +} + +// nvml.DeviceSetPowerManagementLimit() +func (l *library) DeviceSetPowerManagementLimit(device Device, limit uint32) Return { + return device.SetPowerManagementLimit(limit) +} + +func (device nvmlDevice) SetPowerManagementLimit(limit uint32) Return { + return nvmlDeviceSetPowerManagementLimit(device, limit) +} + +// nvml.DeviceSetPowerManagementLimit_v2() +func (l *library) DeviceSetPowerManagementLimit_v2(device Device, powerValue *PowerValue_v2) Return { + return device.SetPowerManagementLimit_v2(powerValue) +} + +func (device nvmlDevice) SetPowerManagementLimit_v2(powerValue *PowerValue_v2) Return { + return nvmlDeviceSetPowerManagementLimit_v2(device, powerValue) +} + +// nvml.DeviceSetGpuOperationMode() +func (l *library) DeviceSetGpuOperationMode(device Device, mode GpuOperationMode) Return { + return device.SetGpuOperationMode(mode) +} + +func (device nvmlDevice) SetGpuOperationMode(mode GpuOperationMode) Return { + return nvmlDeviceSetGpuOperationMode(device, mode) +} + +// nvml.DeviceSetAPIRestriction() +func (l *library) DeviceSetAPIRestriction(device Device, apiType RestrictedAPI, isRestricted EnableState) Return { + return device.SetAPIRestriction(apiType, isRestricted) +} + +func (device nvmlDevice) SetAPIRestriction(apiType RestrictedAPI, isRestricted EnableState) Return { + return nvmlDeviceSetAPIRestriction(device, apiType, isRestricted) +} + +// nvml.DeviceSetAccountingMode() +func (l *library) DeviceSetAccountingMode(device Device, mode EnableState) Return { + return device.SetAccountingMode(mode) +} + +func (device nvmlDevice) SetAccountingMode(mode EnableState) Return { + return nvmlDeviceSetAccountingMode(device, mode) +} + +// nvml.DeviceClearAccountingPids() +func (l *library) DeviceClearAccountingPids(device Device) Return { + return device.ClearAccountingPids() +} + +func (device nvmlDevice) ClearAccountingPids() Return { + return nvmlDeviceClearAccountingPids(device) +} + +// nvml.DeviceGetNvLinkState() +func (l *library) DeviceGetNvLinkState(device Device, link int) (EnableState, Return) { + return device.GetNvLinkState(link) +} + +func (device nvmlDevice) GetNvLinkState(link int) (EnableState, Return) { + var isActive EnableState + ret := nvmlDeviceGetNvLinkState(device, uint32(link), &isActive) + return isActive, ret +} + +// nvml.DeviceGetNvLinkVersion() +func (l *library) DeviceGetNvLinkVersion(device Device, link int) (uint32, Return) { + return device.GetNvLinkVersion(link) +} + +func (device nvmlDevice) GetNvLinkVersion(link int) (uint32, Return) { + var version uint32 + ret := nvmlDeviceGetNvLinkVersion(device, uint32(link), &version) + return version, ret +} + +// nvml.DeviceGetNvLinkCapability() +func (l *library) DeviceGetNvLinkCapability(device Device, link int, capability NvLinkCapability) (uint32, Return) { + return device.GetNvLinkCapability(link, capability) +} + +func (device nvmlDevice) GetNvLinkCapability(link int, capability NvLinkCapability) (uint32, Return) { + var capResult uint32 + ret := nvmlDeviceGetNvLinkCapability(device, uint32(link), capability, &capResult) + return capResult, ret +} + +// nvml.DeviceGetNvLinkRemotePciInfo() +func (l *library) DeviceGetNvLinkRemotePciInfo(device Device, link int) (PciInfo, Return) { + return device.GetNvLinkRemotePciInfo(link) +} + +func (device nvmlDevice) GetNvLinkRemotePciInfo(link int) (PciInfo, Return) { + var pci PciInfo + ret := nvmlDeviceGetNvLinkRemotePciInfo(device, uint32(link), &pci) + return pci, ret +} + +// nvml.DeviceGetNvLinkErrorCounter() +func (l *library) DeviceGetNvLinkErrorCounter(device Device, link int, counter NvLinkErrorCounter) (uint64, Return) { + return device.GetNvLinkErrorCounter(link, counter) +} + +func (device nvmlDevice) GetNvLinkErrorCounter(link int, counter NvLinkErrorCounter) (uint64, Return) { + var counterValue uint64 + ret := nvmlDeviceGetNvLinkErrorCounter(device, uint32(link), counter, &counterValue) + return counterValue, ret +} + +// nvml.DeviceResetNvLinkErrorCounters() +func (l *library) DeviceResetNvLinkErrorCounters(device Device, link int) Return { + return device.ResetNvLinkErrorCounters(link) +} + +func (device nvmlDevice) ResetNvLinkErrorCounters(link int) Return { + return nvmlDeviceResetNvLinkErrorCounters(device, uint32(link)) +} + +// nvml.DeviceSetNvLinkUtilizationControl() +// +// Deprecated: Setting utilization counter control is no longer supported. +func (l *library) DeviceSetNvLinkUtilizationControl(device Device, link int, counter int, control *NvLinkUtilizationControl, reset bool) Return { + return device.SetNvLinkUtilizationControl(link, counter, control, reset) +} + +// Deprecated: Setting utilization counter control is no longer supported. +func (device nvmlDevice) SetNvLinkUtilizationControl(link int, counter int, control *NvLinkUtilizationControl, reset bool) Return { + resetValue := uint32(0) + if reset { + resetValue = 1 + } + return nvmlDeviceSetNvLinkUtilizationControl(device, uint32(link), uint32(counter), control, resetValue) +} + +// nvml.DeviceGetNvLinkUtilizationControl() +// +// Deprecated: Getting utilization counter control is no longer supported. +func (l *library) DeviceGetNvLinkUtilizationControl(device Device, link int, counter int) (NvLinkUtilizationControl, Return) { + return device.GetNvLinkUtilizationControl(link, counter) +} + +// Deprecated: Getting utilization counter control is no longer supported. +func (device nvmlDevice) GetNvLinkUtilizationControl(link int, counter int) (NvLinkUtilizationControl, Return) { + var control NvLinkUtilizationControl + ret := nvmlDeviceGetNvLinkUtilizationControl(device, uint32(link), uint32(counter), &control) + return control, ret +} + +// nvml.DeviceGetNvLinkUtilizationCounter() +// +// Deprecated: Use DeviceGetFieldValues with NVML_FI_DEV_NVLINK_THROUGHPUT_* as field values instead. +func (l *library) DeviceGetNvLinkUtilizationCounter(device Device, link int, counter int) (uint64, uint64, Return) { + return device.GetNvLinkUtilizationCounter(link, counter) +} + +// Deprecated: Use DeviceGetFieldValues with NVML_FI_DEV_NVLINK_THROUGHPUT_* as field values instead. +func (device nvmlDevice) GetNvLinkUtilizationCounter(link int, counter int) (uint64, uint64, Return) { + var rxCounter, txCounter uint64 + ret := nvmlDeviceGetNvLinkUtilizationCounter(device, uint32(link), uint32(counter), &rxCounter, &txCounter) + return rxCounter, txCounter, ret +} + +// nvml.DeviceFreezeNvLinkUtilizationCounter() +// +// Deprecated: Freezing NVLINK utilization counters is no longer supported. +func (l *library) DeviceFreezeNvLinkUtilizationCounter(device Device, link int, counter int, freeze EnableState) Return { + return device.FreezeNvLinkUtilizationCounter(link, counter, freeze) +} + +// Deprecated: Freezing NVLINK utilization counters is no longer supported. +func (device nvmlDevice) FreezeNvLinkUtilizationCounter(link int, counter int, freeze EnableState) Return { + return nvmlDeviceFreezeNvLinkUtilizationCounter(device, uint32(link), uint32(counter), freeze) +} + +// nvml.DeviceResetNvLinkUtilizationCounter() +// +// Deprecated: Resetting NVLINK utilization counters is no longer supported. +func (l *library) DeviceResetNvLinkUtilizationCounter(device Device, link int, counter int) Return { + return device.ResetNvLinkUtilizationCounter(link, counter) +} + +// Deprecated: Resetting NVLINK utilization counters is no longer supported. +func (device nvmlDevice) ResetNvLinkUtilizationCounter(link int, counter int) Return { + return nvmlDeviceResetNvLinkUtilizationCounter(device, uint32(link), uint32(counter)) +} + +// nvml.DeviceGetNvLinkRemoteDeviceType() +func (l *library) DeviceGetNvLinkRemoteDeviceType(device Device, link int) (IntNvLinkDeviceType, Return) { + return device.GetNvLinkRemoteDeviceType(link) +} + +func (device nvmlDevice) GetNvLinkRemoteDeviceType(link int) (IntNvLinkDeviceType, Return) { + var nvLinkDeviceType IntNvLinkDeviceType + ret := nvmlDeviceGetNvLinkRemoteDeviceType(device, uint32(link), &nvLinkDeviceType) + return nvLinkDeviceType, ret +} + +// nvml.DeviceRegisterEvents() +func (l *library) DeviceRegisterEvents(device Device, eventTypes uint64, set EventSet) Return { + return device.RegisterEvents(eventTypes, set) +} + +func (device nvmlDevice) RegisterEvents(eventTypes uint64, set EventSet) Return { + return nvmlDeviceRegisterEvents(device, eventTypes, set.(nvmlEventSet)) +} + +// nvmlDeviceGetSupportedEventTypes() +func (l *library) DeviceGetSupportedEventTypes(device Device) (uint64, Return) { + return device.GetSupportedEventTypes() +} + +func (device nvmlDevice) GetSupportedEventTypes() (uint64, Return) { + var eventTypes uint64 + ret := nvmlDeviceGetSupportedEventTypes(device, &eventTypes) + return eventTypes, ret +} + +// nvml.DeviceModifyDrainState() +func (l *library) DeviceModifyDrainState(pciInfo *PciInfo, newState EnableState) Return { + return nvmlDeviceModifyDrainState(pciInfo, newState) +} + +// nvml.DeviceQueryDrainState() +func (l *library) DeviceQueryDrainState(pciInfo *PciInfo) (EnableState, Return) { + var currentState EnableState + ret := nvmlDeviceQueryDrainState(pciInfo, ¤tState) + return currentState, ret +} + +// nvml.DeviceRemoveGpu() +func (l *library) DeviceRemoveGpu(pciInfo *PciInfo) Return { + return nvmlDeviceRemoveGpu(pciInfo) +} + +// nvml.DeviceRemoveGpu_v2() +func (l *library) DeviceRemoveGpu_v2(pciInfo *PciInfo, gpuState DetachGpuState, linkState PcieLinkState) Return { + return nvmlDeviceRemoveGpu_v2(pciInfo, gpuState, linkState) +} + +// nvml.DeviceDiscoverGpus() +func (l *library) DeviceDiscoverGpus() (PciInfo, Return) { + var pciInfo PciInfo + ret := nvmlDeviceDiscoverGpus(&pciInfo) + return pciInfo, ret +} + +// nvml.DeviceGetFieldValues() +func (l *library) DeviceGetFieldValues(device Device, values []FieldValue) Return { + return device.GetFieldValues(values) +} + +func (device nvmlDevice) GetFieldValues(values []FieldValue) Return { + valuesCount := len(values) + return nvmlDeviceGetFieldValues(device, int32(valuesCount), &values[0]) +} + +// nvml.DeviceGetVirtualizationMode() +func (l *library) DeviceGetVirtualizationMode(device Device) (GpuVirtualizationMode, Return) { + return device.GetVirtualizationMode() +} + +func (device nvmlDevice) GetVirtualizationMode() (GpuVirtualizationMode, Return) { + var pVirtualMode GpuVirtualizationMode + ret := nvmlDeviceGetVirtualizationMode(device, &pVirtualMode) + return pVirtualMode, ret +} + +// nvml.DeviceGetHostVgpuMode() +func (l *library) DeviceGetHostVgpuMode(device Device) (HostVgpuMode, Return) { + return device.GetHostVgpuMode() +} + +func (device nvmlDevice) GetHostVgpuMode() (HostVgpuMode, Return) { + var pHostVgpuMode HostVgpuMode + ret := nvmlDeviceGetHostVgpuMode(device, &pHostVgpuMode) + return pHostVgpuMode, ret +} + +// nvml.DeviceSetVirtualizationMode() +func (l *library) DeviceSetVirtualizationMode(device Device, virtualMode GpuVirtualizationMode) Return { + return device.SetVirtualizationMode(virtualMode) +} + +func (device nvmlDevice) SetVirtualizationMode(virtualMode GpuVirtualizationMode) Return { + return nvmlDeviceSetVirtualizationMode(device, virtualMode) +} + +// nvml.DeviceGetGridLicensableFeatures() +func (l *library) DeviceGetGridLicensableFeatures(device Device) (GridLicensableFeatures, Return) { + return device.GetGridLicensableFeatures() +} + +func (device nvmlDevice) GetGridLicensableFeatures() (GridLicensableFeatures, Return) { + var pGridLicensableFeatures GridLicensableFeatures + ret := nvmlDeviceGetGridLicensableFeatures(device, &pGridLicensableFeatures) + return pGridLicensableFeatures, ret +} + +// nvml.DeviceGetProcessUtilization() +func (l *library) DeviceGetProcessUtilization(device Device, lastSeenTimestamp uint64) ([]ProcessUtilizationSample, Return) { + return device.GetProcessUtilization(lastSeenTimestamp) +} + +func (device nvmlDevice) GetProcessUtilization(lastSeenTimestamp uint64) ([]ProcessUtilizationSample, Return) { + var processSamplesCount uint32 + ret := nvmlDeviceGetProcessUtilization(device, nil, &processSamplesCount, lastSeenTimestamp) + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + if processSamplesCount == 0 { + return []ProcessUtilizationSample{}, ret + } + utilization := make([]ProcessUtilizationSample, processSamplesCount) + ret = nvmlDeviceGetProcessUtilization(device, &utilization[0], &processSamplesCount, lastSeenTimestamp) + return utilization[:processSamplesCount], ret +} + +// nvml.DeviceGetSupportedVgpus() +func (l *library) DeviceGetSupportedVgpus(device Device) ([]VgpuTypeId, Return) { + return device.GetSupportedVgpus() +} + +func (device nvmlDevice) GetSupportedVgpus() ([]VgpuTypeId, Return) { + var vgpuCount uint32 = 1 // Will be reduced upon returning + for { + vgpuTypeIds := make([]nvmlVgpuTypeId, vgpuCount) + ret := nvmlDeviceGetSupportedVgpus(device, &vgpuCount, &vgpuTypeIds[0]) + if ret == SUCCESS { + return convertSlice[nvmlVgpuTypeId, VgpuTypeId](vgpuTypeIds[:vgpuCount]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + vgpuCount *= 2 + } +} + +// nvml.DeviceGetCreatableVgpus() +func (l *library) DeviceGetCreatableVgpus(device Device) ([]VgpuTypeId, Return) { + return device.GetCreatableVgpus() +} + +func (device nvmlDevice) GetCreatableVgpus() ([]VgpuTypeId, Return) { + var vgpuCount uint32 = 1 // Will be reduced upon returning + for { + vgpuTypeIds := make([]nvmlVgpuTypeId, vgpuCount) + ret := nvmlDeviceGetCreatableVgpus(device, &vgpuCount, &vgpuTypeIds[0]) + if ret == SUCCESS { + return convertSlice[nvmlVgpuTypeId, VgpuTypeId](vgpuTypeIds[:vgpuCount]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + vgpuCount *= 2 + } +} + +// nvml.DeviceGetActiveVgpus() +func (l *library) DeviceGetActiveVgpus(device Device) ([]VgpuInstance, Return) { + return device.GetActiveVgpus() +} + +func (device nvmlDevice) GetActiveVgpus() ([]VgpuInstance, Return) { + var vgpuCount uint32 = 1 // Will be reduced upon returning + for { + vgpuInstances := make([]nvmlVgpuInstance, vgpuCount) + ret := nvmlDeviceGetActiveVgpus(device, &vgpuCount, &vgpuInstances[0]) + if ret == SUCCESS { + return convertSlice[nvmlVgpuInstance, VgpuInstance](vgpuInstances[:vgpuCount]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + vgpuCount *= 2 + } +} + +// nvml.DeviceGetVgpuMetadata() +func (l *library) DeviceGetVgpuMetadata(device Device) (VgpuPgpuMetadata, Return) { + return device.GetVgpuMetadata() +} + +func (device nvmlDevice) GetVgpuMetadata() (VgpuPgpuMetadata, Return) { + var vgpuPgpuMetadata VgpuPgpuMetadata + opaqueDataSize := unsafe.Sizeof(vgpuPgpuMetadata.nvmlVgpuPgpuMetadata.OpaqueData) + vgpuPgpuMetadataSize := unsafe.Sizeof(vgpuPgpuMetadata.nvmlVgpuPgpuMetadata) - opaqueDataSize + for { + bufferSize := uint32(vgpuPgpuMetadataSize + opaqueDataSize) + buffer := make([]byte, bufferSize) + nvmlVgpuPgpuMetadataPtr := (*nvmlVgpuPgpuMetadata)(unsafe.Pointer(&buffer[0])) + ret := nvmlDeviceGetVgpuMetadata(device, nvmlVgpuPgpuMetadataPtr, &bufferSize) + if ret == SUCCESS { + vgpuPgpuMetadata.nvmlVgpuPgpuMetadata = *nvmlVgpuPgpuMetadataPtr + vgpuPgpuMetadata.OpaqueData = buffer[vgpuPgpuMetadataSize:bufferSize] + return vgpuPgpuMetadata, ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return vgpuPgpuMetadata, ret + } + opaqueDataSize = 2 * opaqueDataSize + } +} + +// nvml.DeviceGetPgpuMetadataString() +func (l *library) DeviceGetPgpuMetadataString(device Device) (string, Return) { + return device.GetPgpuMetadataString() +} + +func (device nvmlDevice) GetPgpuMetadataString() (string, Return) { + var bufferSize uint32 = 1 // Will be reduced upon returning + for { + pgpuMetadata := make([]byte, bufferSize) + ret := nvmlDeviceGetPgpuMetadataString(device, &pgpuMetadata[0], &bufferSize) + if ret == SUCCESS { + return string(pgpuMetadata[:clen(pgpuMetadata)]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return "", ret + } + bufferSize *= 2 + } +} + +// nvml.DeviceGetVgpuUtilization() +func (l *library) DeviceGetVgpuUtilization(device Device, lastSeenTimestamp uint64) (ValueType, []VgpuInstanceUtilizationSample, Return) { + return device.GetVgpuUtilization(lastSeenTimestamp) +} + +func (device nvmlDevice) GetVgpuUtilization(lastSeenTimestamp uint64) (ValueType, []VgpuInstanceUtilizationSample, Return) { + var sampleValType ValueType + var vgpuInstanceSamplesCount uint32 = 1 // Will be reduced upon returning + for { + utilizationSamples := make([]VgpuInstanceUtilizationSample, vgpuInstanceSamplesCount) + ret := nvmlDeviceGetVgpuUtilization(device, lastSeenTimestamp, &sampleValType, &vgpuInstanceSamplesCount, &utilizationSamples[0]) + if ret == SUCCESS { + return sampleValType, utilizationSamples[:vgpuInstanceSamplesCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return sampleValType, nil, ret + } + vgpuInstanceSamplesCount *= 2 + } +} + +// nvml.DeviceGetAttributes() +func (l *library) DeviceGetAttributes(device Device) (DeviceAttributes, Return) { + return device.GetAttributes() +} + +func (device nvmlDevice) GetAttributes() (DeviceAttributes, Return) { + var attributes DeviceAttributes + ret := nvmlDeviceGetAttributes(device, &attributes) + return attributes, ret +} + +// nvml.DeviceGetRemappedRows() +func (l *library) DeviceGetRemappedRows(device Device) (int, int, bool, bool, Return) { + return device.GetRemappedRows() +} + +func (device nvmlDevice) GetRemappedRows() (int, int, bool, bool, Return) { + var corrRows, uncRows, isPending, failureOccured uint32 + ret := nvmlDeviceGetRemappedRows(device, &corrRows, &uncRows, &isPending, &failureOccured) + return int(corrRows), int(uncRows), (isPending != 0), (failureOccured != 0), ret +} + +// nvml.DeviceGetRowRemapperHistogram() +func (l *library) DeviceGetRowRemapperHistogram(device Device) (RowRemapperHistogramValues, Return) { + return device.GetRowRemapperHistogram() +} + +func (device nvmlDevice) GetRowRemapperHistogram() (RowRemapperHistogramValues, Return) { + var values RowRemapperHistogramValues + ret := nvmlDeviceGetRowRemapperHistogram(device, &values) + return values, ret +} + +// nvml.DeviceGetArchitecture() +func (l *library) DeviceGetArchitecture(device Device) (DeviceArchitecture, Return) { + return device.GetArchitecture() +} + +func (device nvmlDevice) GetArchitecture() (DeviceArchitecture, Return) { + var arch DeviceArchitecture + ret := nvmlDeviceGetArchitecture(device, &arch) + return arch, ret +} + +// nvml.DeviceGetVgpuProcessUtilization() +func (l *library) DeviceGetVgpuProcessUtilization(device Device, lastSeenTimestamp uint64) ([]VgpuProcessUtilizationSample, Return) { + return device.GetVgpuProcessUtilization(lastSeenTimestamp) +} + +func (device nvmlDevice) GetVgpuProcessUtilization(lastSeenTimestamp uint64) ([]VgpuProcessUtilizationSample, Return) { + var vgpuProcessSamplesCount uint32 = 1 // Will be reduced upon returning + for { + utilizationSamples := make([]VgpuProcessUtilizationSample, vgpuProcessSamplesCount) + ret := nvmlDeviceGetVgpuProcessUtilization(device, lastSeenTimestamp, &vgpuProcessSamplesCount, &utilizationSamples[0]) + if ret == SUCCESS { + return utilizationSamples[:vgpuProcessSamplesCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + vgpuProcessSamplesCount *= 2 + } +} + +// nvml.GetExcludedDeviceCount() +func (l *library) GetExcludedDeviceCount() (int, Return) { + var deviceCount uint32 + ret := nvmlGetExcludedDeviceCount(&deviceCount) + return int(deviceCount), ret +} + +// nvml.GetExcludedDeviceInfoByIndex() +func (l *library) GetExcludedDeviceInfoByIndex(index int) (ExcludedDeviceInfo, Return) { + var info ExcludedDeviceInfo + ret := nvmlGetExcludedDeviceInfoByIndex(uint32(index), &info) + return info, ret +} + +func (l *library) DeviceReadWritePRM_v1(device Device, buffer *PRMTLV_v1) Return { + return device.ReadWritePRM_v1(buffer) +} + +func (device nvmlDevice) ReadWritePRM_v1(buffer *PRMTLV_v1) Return { + return nvmlDeviceReadWritePRM_v1(device, buffer) +} + +// nvml.DeviceSetMigMode() +func (l *library) DeviceSetMigMode(device Device, mode int) (Return, Return) { + return device.SetMigMode(mode) +} + +func (device nvmlDevice) SetMigMode(mode int) (Return, Return) { + var activationStatus Return + ret := nvmlDeviceSetMigMode(device, uint32(mode), &activationStatus) + return activationStatus, ret +} + +// nvml.DeviceGetMigMode() +func (l *library) DeviceGetMigMode(device Device) (int, int, Return) { + return device.GetMigMode() +} + +func (device nvmlDevice) GetMigMode() (int, int, Return) { + var currentMode, pendingMode uint32 + ret := nvmlDeviceGetMigMode(device, ¤tMode, &pendingMode) + return int(currentMode), int(pendingMode), ret +} + +// nvml.DeviceGetGpuInstanceProfileInfo() +func (l *library) DeviceGetGpuInstanceProfileInfo(device Device, profile int) (GpuInstanceProfileInfo, Return) { + return device.GetGpuInstanceProfileInfo(profile) +} + +func (device nvmlDevice) GetGpuInstanceProfileInfo(profile int) (GpuInstanceProfileInfo, Return) { + var info GpuInstanceProfileInfo + ret := nvmlDeviceGetGpuInstanceProfileInfo(device, uint32(profile), &info) + return info, ret +} + +// nvml.DeviceGetGpuInstanceProfileInfoV() +type GpuInstanceProfileInfoHandler struct { + device nvmlDevice + profile int +} + +func (handler GpuInstanceProfileInfoHandler) V1() (GpuInstanceProfileInfo, Return) { + return DeviceGetGpuInstanceProfileInfo(handler.device, handler.profile) +} + +func (handler GpuInstanceProfileInfoHandler) V2() (GpuInstanceProfileInfo_v2, Return) { + var info GpuInstanceProfileInfo_v2 + info.Version = STRUCT_VERSION(info, 2) + ret := nvmlDeviceGetGpuInstanceProfileInfoV(handler.device, uint32(handler.profile), &info) + return info, ret +} + +func (handler GpuInstanceProfileInfoHandler) V3() (GpuInstanceProfileInfo_v3, Return) { + var info GpuInstanceProfileInfo_v3 + info.Version = STRUCT_VERSION(info, 3) + ret := nvmlDeviceGetGpuInstanceProfileInfoV(handler.device, uint32(handler.profile), (*GpuInstanceProfileInfo_v2)(unsafe.Pointer(&info))) + return info, ret +} + +func (l *library) DeviceGetGpuInstanceProfileInfoV(device Device, profile int) GpuInstanceProfileInfoHandler { + return device.GetGpuInstanceProfileInfoV(profile) +} + +func (device nvmlDevice) GetGpuInstanceProfileInfoV(profile int) GpuInstanceProfileInfoHandler { + return GpuInstanceProfileInfoHandler{device, profile} +} + +type GpuInstanceProfileInfoByIdHandler struct { + device nvmlDevice + profileId int +} + +func (handler GpuInstanceProfileInfoByIdHandler) V2() (GpuInstanceProfileInfo_v2, Return) { + var info GpuInstanceProfileInfo_v2 + info.Version = STRUCT_VERSION(info, 2) + ret := nvmlDeviceGetGpuInstanceProfileInfoByIdV(handler.device, uint32(handler.profileId), &info) + return info, ret +} + +func (handler GpuInstanceProfileInfoByIdHandler) V3() (GpuInstanceProfileInfo_v3, Return) { + var info GpuInstanceProfileInfo_v3 + info.Version = STRUCT_VERSION(info, 3) + ret := nvmlDeviceGetGpuInstanceProfileInfoV(handler.device, uint32(handler.profileId), (*GpuInstanceProfileInfo_v2)(unsafe.Pointer(&info))) + return info, ret +} + +func (l *library) DeviceGetGpuInstanceProfileInfoByIdV(device Device, profileId int) GpuInstanceProfileInfoByIdHandler { + return device.GetGpuInstanceProfileInfoByIdV(profileId) +} + +func (device nvmlDevice) GetGpuInstanceProfileInfoByIdV(profileId int) GpuInstanceProfileInfoByIdHandler { + return GpuInstanceProfileInfoByIdHandler{device, profileId} +} + +// nvml.DeviceGetGpuInstancePossiblePlacements() +func (l *library) DeviceGetGpuInstancePossiblePlacements(device Device, info *GpuInstanceProfileInfo) ([]GpuInstancePlacement, Return) { + return device.GetGpuInstancePossiblePlacements(info) +} + +func (device nvmlDevice) GetGpuInstancePossiblePlacements(info *GpuInstanceProfileInfo) ([]GpuInstancePlacement, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var count uint32 + ret := nvmlDeviceGetGpuInstancePossiblePlacements(device, info.Id, nil, &count) + if ret != SUCCESS { + return nil, ret + } + if count == 0 { + return []GpuInstancePlacement{}, ret + } + placements := make([]GpuInstancePlacement, count) + ret = nvmlDeviceGetGpuInstancePossiblePlacements(device, info.Id, &placements[0], &count) + return placements[:count], ret +} + +// nvml.DeviceGetGpuInstanceRemainingCapacity() +func (l *library) DeviceGetGpuInstanceRemainingCapacity(device Device, info *GpuInstanceProfileInfo) (int, Return) { + return device.GetGpuInstanceRemainingCapacity(info) +} + +func (device nvmlDevice) GetGpuInstanceRemainingCapacity(info *GpuInstanceProfileInfo) (int, Return) { + if info == nil { + return 0, ERROR_INVALID_ARGUMENT + } + var count uint32 + ret := nvmlDeviceGetGpuInstanceRemainingCapacity(device, info.Id, &count) + return int(count), ret +} + +// nvml.DeviceCreateGpuInstance() +func (l *library) DeviceCreateGpuInstance(device Device, info *GpuInstanceProfileInfo) (GpuInstance, Return) { + return device.CreateGpuInstance(info) +} + +func (device nvmlDevice) CreateGpuInstance(info *GpuInstanceProfileInfo) (GpuInstance, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var gpuInstance nvmlGpuInstance + ret := nvmlDeviceCreateGpuInstance(device, info.Id, &gpuInstance) + return gpuInstance, ret +} + +// nvml.DeviceCreateGpuInstanceWithPlacement() +func (l *library) DeviceCreateGpuInstanceWithPlacement(device Device, info *GpuInstanceProfileInfo, placement *GpuInstancePlacement) (GpuInstance, Return) { + return device.CreateGpuInstanceWithPlacement(info, placement) +} + +func (device nvmlDevice) CreateGpuInstanceWithPlacement(info *GpuInstanceProfileInfo, placement *GpuInstancePlacement) (GpuInstance, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var gpuInstance nvmlGpuInstance + ret := nvmlDeviceCreateGpuInstanceWithPlacement(device, info.Id, placement, &gpuInstance) + return gpuInstance, ret +} + +// nvml.GpuInstanceDestroy() +func (l *library) GpuInstanceDestroy(gpuInstance GpuInstance) Return { + return gpuInstance.Destroy() +} + +func (gpuInstance nvmlGpuInstance) Destroy() Return { + return nvmlGpuInstanceDestroy(gpuInstance) +} + +// nvml.DeviceGetGpuInstances() +func (l *library) DeviceGetGpuInstances(device Device, info *GpuInstanceProfileInfo) ([]GpuInstance, Return) { + return device.GetGpuInstances(info) +} + +func (device nvmlDevice) GetGpuInstances(info *GpuInstanceProfileInfo) ([]GpuInstance, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var count = info.InstanceCount + gpuInstances := make([]nvmlGpuInstance, count) + ret := nvmlDeviceGetGpuInstances(device, info.Id, &gpuInstances[0], &count) + return convertSlice[nvmlGpuInstance, GpuInstance](gpuInstances[:count]), ret +} + +// nvml.DeviceGetGpuInstanceById() +func (l *library) DeviceGetGpuInstanceById(device Device, id int) (GpuInstance, Return) { + return device.GetGpuInstanceById(id) +} + +func (device nvmlDevice) GetGpuInstanceById(id int) (GpuInstance, Return) { + var gpuInstance nvmlGpuInstance + ret := nvmlDeviceGetGpuInstanceById(device, uint32(id), &gpuInstance) + return gpuInstance, ret +} + +// nvml.GpuInstanceGetInfo() +func (l *library) GpuInstanceGetInfo(gpuInstance GpuInstance) (GpuInstanceInfo, Return) { + return gpuInstance.GetInfo() +} + +func (gpuInstance nvmlGpuInstance) GetInfo() (GpuInstanceInfo, Return) { + var info nvmlGpuInstanceInfo + ret := nvmlGpuInstanceGetInfo(gpuInstance, &info) + return info.convert(), ret +} + +// nvml.GpuInstanceGetComputeInstanceProfileInfo() +func (l *library) GpuInstanceGetComputeInstanceProfileInfo(gpuInstance GpuInstance, profile int, engProfile int) (ComputeInstanceProfileInfo, Return) { + return gpuInstance.GetComputeInstanceProfileInfo(profile, engProfile) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstanceProfileInfo(profile int, engProfile int) (ComputeInstanceProfileInfo, Return) { + var info ComputeInstanceProfileInfo + ret := nvmlGpuInstanceGetComputeInstanceProfileInfo(gpuInstance, uint32(profile), uint32(engProfile), &info) + return info, ret +} + +// nvml.GpuInstanceGetComputeInstanceProfileInfoV() +type ComputeInstanceProfileInfoHandler struct { + gpuInstance nvmlGpuInstance + profile int + engProfile int +} + +func (handler ComputeInstanceProfileInfoHandler) V1() (ComputeInstanceProfileInfo, Return) { + return GpuInstanceGetComputeInstanceProfileInfo(handler.gpuInstance, handler.profile, handler.engProfile) +} + +func (handler ComputeInstanceProfileInfoHandler) V2() (ComputeInstanceProfileInfo_v2, Return) { + var info ComputeInstanceProfileInfo_v2 + info.Version = STRUCT_VERSION(info, 2) + ret := nvmlGpuInstanceGetComputeInstanceProfileInfoV(handler.gpuInstance, uint32(handler.profile), uint32(handler.engProfile), &info) + return info, ret +} + +func (handler ComputeInstanceProfileInfoHandler) V3() (ComputeInstanceProfileInfo_v3, Return) { + var info ComputeInstanceProfileInfo_v3 + info.Version = STRUCT_VERSION(info, 3) + ret := nvmlGpuInstanceGetComputeInstanceProfileInfoV(handler.gpuInstance, uint32(handler.profile), uint32(handler.engProfile), (*ComputeInstanceProfileInfo_v2)(unsafe.Pointer(&info))) + return info, ret +} + +func (l *library) GpuInstanceGetComputeInstanceProfileInfoV(gpuInstance GpuInstance, profile int, engProfile int) ComputeInstanceProfileInfoHandler { + return gpuInstance.GetComputeInstanceProfileInfoV(profile, engProfile) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstanceProfileInfoV(profile int, engProfile int) ComputeInstanceProfileInfoHandler { + return ComputeInstanceProfileInfoHandler{gpuInstance, profile, engProfile} +} + +// nvml.GpuInstanceGetComputeInstanceRemainingCapacity() +func (l *library) GpuInstanceGetComputeInstanceRemainingCapacity(gpuInstance GpuInstance, info *ComputeInstanceProfileInfo) (int, Return) { + return gpuInstance.GetComputeInstanceRemainingCapacity(info) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstanceRemainingCapacity(info *ComputeInstanceProfileInfo) (int, Return) { + if info == nil { + return 0, ERROR_INVALID_ARGUMENT + } + var count uint32 + ret := nvmlGpuInstanceGetComputeInstanceRemainingCapacity(gpuInstance, info.Id, &count) + return int(count), ret +} + +// nvml.GpuInstanceCreateComputeInstance() +func (l *library) GpuInstanceCreateComputeInstance(gpuInstance GpuInstance, info *ComputeInstanceProfileInfo) (ComputeInstance, Return) { + return gpuInstance.CreateComputeInstance(info) +} + +func (gpuInstance nvmlGpuInstance) CreateComputeInstance(info *ComputeInstanceProfileInfo) (ComputeInstance, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var computeInstance nvmlComputeInstance + ret := nvmlGpuInstanceCreateComputeInstance(gpuInstance, info.Id, &computeInstance) + return computeInstance, ret +} + +// nvml.ComputeInstanceDestroy() +func (l *library) ComputeInstanceDestroy(computeInstance ComputeInstance) Return { + return computeInstance.Destroy() +} + +func (computeInstance nvmlComputeInstance) Destroy() Return { + return nvmlComputeInstanceDestroy(computeInstance) +} + +// nvml.GpuInstanceGetComputeInstances() +func (l *library) GpuInstanceGetComputeInstances(gpuInstance GpuInstance, info *ComputeInstanceProfileInfo) ([]ComputeInstance, Return) { + return gpuInstance.GetComputeInstances(info) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstances(info *ComputeInstanceProfileInfo) ([]ComputeInstance, Return) { + if info == nil { + return nil, ERROR_INVALID_ARGUMENT + } + var count = info.InstanceCount + computeInstances := make([]nvmlComputeInstance, count) + ret := nvmlGpuInstanceGetComputeInstances(gpuInstance, info.Id, &computeInstances[0], &count) + return convertSlice[nvmlComputeInstance, ComputeInstance](computeInstances[:count]), ret +} + +// nvml.GpuInstanceGetComputeInstanceById() +func (l *library) GpuInstanceGetComputeInstanceById(gpuInstance GpuInstance, id int) (ComputeInstance, Return) { + return gpuInstance.GetComputeInstanceById(id) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstanceById(id int) (ComputeInstance, Return) { + var computeInstance nvmlComputeInstance + ret := nvmlGpuInstanceGetComputeInstanceById(gpuInstance, uint32(id), &computeInstance) + return computeInstance, ret +} + +// nvml.ComputeInstanceGetInfo() +func (l *library) ComputeInstanceGetInfo(computeInstance ComputeInstance) (ComputeInstanceInfo, Return) { + return computeInstance.GetInfo() +} + +func (computeInstance nvmlComputeInstance) GetInfo() (ComputeInstanceInfo, Return) { + var info nvmlComputeInstanceInfo + ret := nvmlComputeInstanceGetInfo(computeInstance, &info) + return info.convert(), ret +} + +// nvml.DeviceIsMigDeviceHandle() +func (l *library) DeviceIsMigDeviceHandle(device Device) (bool, Return) { + return device.IsMigDeviceHandle() +} + +func (device nvmlDevice) IsMigDeviceHandle() (bool, Return) { + var isMigDevice uint32 + ret := nvmlDeviceIsMigDeviceHandle(device, &isMigDevice) + return (isMigDevice != 0), ret +} + +// nvml DeviceGetGpuInstanceId() +func (l *library) DeviceGetGpuInstanceId(device Device) (int, Return) { + return device.GetGpuInstanceId() +} + +func (device nvmlDevice) GetGpuInstanceId() (int, Return) { + var id uint32 + ret := nvmlDeviceGetGpuInstanceId(device, &id) + return int(id), ret +} + +// nvml.DeviceGetComputeInstanceId() +func (l *library) DeviceGetComputeInstanceId(device Device) (int, Return) { + return device.GetComputeInstanceId() +} + +func (device nvmlDevice) GetComputeInstanceId() (int, Return) { + var id uint32 + ret := nvmlDeviceGetComputeInstanceId(device, &id) + return int(id), ret +} + +// nvml.DeviceGetMaxMigDeviceCount() +func (l *library) DeviceGetMaxMigDeviceCount(device Device) (int, Return) { + return device.GetMaxMigDeviceCount() +} + +func (device nvmlDevice) GetMaxMigDeviceCount() (int, Return) { + var count uint32 + ret := nvmlDeviceGetMaxMigDeviceCount(device, &count) + return int(count), ret +} + +// nvml.DeviceGetMigDeviceHandleByIndex() +func (l *library) DeviceGetMigDeviceHandleByIndex(device Device, index int) (Device, Return) { + return device.GetMigDeviceHandleByIndex(index) +} + +func (device nvmlDevice) GetMigDeviceHandleByIndex(index int) (Device, Return) { + var migDevice nvmlDevice + ret := nvmlDeviceGetMigDeviceHandleByIndex(device, uint32(index), &migDevice) + return migDevice, ret +} + +// nvml.DeviceGetDeviceHandleFromMigDeviceHandle() +func (l *library) DeviceGetDeviceHandleFromMigDeviceHandle(migdevice Device) (Device, Return) { + return migdevice.GetDeviceHandleFromMigDeviceHandle() +} + +func (migDevice nvmlDevice) GetDeviceHandleFromMigDeviceHandle() (Device, Return) { + var device nvmlDevice + ret := nvmlDeviceGetDeviceHandleFromMigDeviceHandle(migDevice, &device) + return device, ret +} + +// nvml.DeviceGetBusType() +func (l *library) DeviceGetBusType(device Device) (BusType, Return) { + return device.GetBusType() +} + +func (device nvmlDevice) GetBusType() (BusType, Return) { + var busType BusType + ret := nvmlDeviceGetBusType(device, &busType) + return busType, ret +} + +// nvml.DeviceSetDefaultFanSpeed_v2() +func (l *library) DeviceSetDefaultFanSpeed_v2(device Device, fan int) Return { + return device.SetDefaultFanSpeed_v2(fan) +} + +func (device nvmlDevice) SetDefaultFanSpeed_v2(fan int) Return { + return nvmlDeviceSetDefaultFanSpeed_v2(device, uint32(fan)) +} + +// nvml.DeviceGetMinMaxFanSpeed() +func (l *library) DeviceGetMinMaxFanSpeed(device Device) (int, int, Return) { + return device.GetMinMaxFanSpeed() +} + +func (device nvmlDevice) GetMinMaxFanSpeed() (int, int, Return) { + var minSpeed, maxSpeed uint32 + ret := nvmlDeviceGetMinMaxFanSpeed(device, &minSpeed, &maxSpeed) + return int(minSpeed), int(maxSpeed), ret +} + +// nvml.DeviceGetThermalSettings() +func (l *library) DeviceGetThermalSettings(device Device, sensorIndex uint32) (GpuThermalSettings, Return) { + return device.GetThermalSettings(sensorIndex) +} + +func (device nvmlDevice) GetThermalSettings(sensorIndex uint32) (GpuThermalSettings, Return) { + var pThermalSettings GpuThermalSettings + ret := nvmlDeviceGetThermalSettings(device, sensorIndex, &pThermalSettings) + return pThermalSettings, ret +} + +// nvml.DeviceGetDefaultEccMode() +func (l *library) DeviceGetDefaultEccMode(device Device) (EnableState, Return) { + return device.GetDefaultEccMode() +} + +func (device nvmlDevice) GetDefaultEccMode() (EnableState, Return) { + var defaultMode EnableState + ret := nvmlDeviceGetDefaultEccMode(device, &defaultMode) + return defaultMode, ret +} + +// nvml.DeviceGetPcieSpeed() +func (l *library) DeviceGetPcieSpeed(device Device) (int, Return) { + return device.GetPcieSpeed() +} + +func (device nvmlDevice) GetPcieSpeed() (int, Return) { + var pcieSpeed uint32 + ret := nvmlDeviceGetPcieSpeed(device, &pcieSpeed) + return int(pcieSpeed), ret +} + +// nvml.DeviceGetGspFirmwareVersion() +func (l *library) DeviceGetGspFirmwareVersion(device Device) (string, Return) { + return device.GetGspFirmwareVersion() +} + +func (device nvmlDevice) GetGspFirmwareVersion() (string, Return) { + version := make([]byte, GSP_FIRMWARE_VERSION_BUF_SIZE) + ret := nvmlDeviceGetGspFirmwareVersion(device, &version[0]) + return string(version[:clen(version)]), ret +} + +// nvml.DeviceGetGspFirmwareMode() +func (l *library) DeviceGetGspFirmwareMode(device Device) (bool, bool, Return) { + return device.GetGspFirmwareMode() +} + +func (device nvmlDevice) GetGspFirmwareMode() (bool, bool, Return) { + var isEnabled, defaultMode uint32 + ret := nvmlDeviceGetGspFirmwareMode(device, &isEnabled, &defaultMode) + return (isEnabled != 0), (defaultMode != 0), ret +} + +// nvml.DeviceGetDynamicPstatesInfo() +func (l *library) DeviceGetDynamicPstatesInfo(device Device) (GpuDynamicPstatesInfo, Return) { + return device.GetDynamicPstatesInfo() +} + +func (device nvmlDevice) GetDynamicPstatesInfo() (GpuDynamicPstatesInfo, Return) { + var pDynamicPstatesInfo GpuDynamicPstatesInfo + ret := nvmlDeviceGetDynamicPstatesInfo(device, &pDynamicPstatesInfo) + return pDynamicPstatesInfo, ret +} + +// nvml.DeviceSetFanSpeed_v2() +func (l *library) DeviceSetFanSpeed_v2(device Device, fan int, speed int) Return { + return device.SetFanSpeed_v2(fan, speed) +} + +func (device nvmlDevice) SetFanSpeed_v2(fan int, speed int) Return { + return nvmlDeviceSetFanSpeed_v2(device, uint32(fan), uint32(speed)) +} + +// nvml.DeviceGetGpcClkVfOffset() +func (l *library) DeviceGetGpcClkVfOffset(device Device) (int, Return) { + return device.GetGpcClkVfOffset() +} + +func (device nvmlDevice) GetGpcClkVfOffset() (int, Return) { + var offset int32 + ret := nvmlDeviceGetGpcClkVfOffset(device, &offset) + return int(offset), ret +} + +// nvml.DeviceSetGpcClkVfOffset() +// +// Deprecated: Use DeviceSetClockOffsets instead. +func (l *library) DeviceSetGpcClkVfOffset(device Device, offset int) Return { + return device.SetGpcClkVfOffset(offset) +} + +// Deprecated: Use DeviceSetClockOffsets instead. +func (device nvmlDevice) SetGpcClkVfOffset(offset int) Return { + return nvmlDeviceSetGpcClkVfOffset(device, int32(offset)) +} + +// nvml.DeviceGetMinMaxClockOfPState() +func (l *library) DeviceGetMinMaxClockOfPState(device Device, clockType ClockType, pstate Pstates) (uint32, uint32, Return) { + return device.GetMinMaxClockOfPState(clockType, pstate) +} + +func (device nvmlDevice) GetMinMaxClockOfPState(clockType ClockType, pstate Pstates) (uint32, uint32, Return) { + var minClockMHz, maxClockMHz uint32 + ret := nvmlDeviceGetMinMaxClockOfPState(device, clockType, pstate, &minClockMHz, &maxClockMHz) + return minClockMHz, maxClockMHz, ret +} + +// nvml.DeviceGetSupportedPerformanceStates() +func (l *library) DeviceGetSupportedPerformanceStates(device Device) ([]Pstates, Return) { + return device.GetSupportedPerformanceStates() +} + +func (device nvmlDevice) GetSupportedPerformanceStates() ([]Pstates, Return) { + pstates := make([]Pstates, MAX_GPU_PERF_PSTATES) + ret := nvmlDeviceGetSupportedPerformanceStates(device, &pstates[0], MAX_GPU_PERF_PSTATES) + for i := 0; i < MAX_GPU_PERF_PSTATES; i++ { + if pstates[i] == PSTATE_UNKNOWN { + return pstates[0:i], ret + } + } + return pstates, ret +} + +// nvml.DeviceGetTargetFanSpeed() +func (l *library) DeviceGetTargetFanSpeed(device Device, fan int) (int, Return) { + return device.GetTargetFanSpeed(fan) +} + +func (device nvmlDevice) GetTargetFanSpeed(fan int) (int, Return) { + var targetSpeed uint32 + ret := nvmlDeviceGetTargetFanSpeed(device, uint32(fan), &targetSpeed) + return int(targetSpeed), ret +} + +// nvml.DeviceGetMemClkVfOffset() +func (l *library) DeviceGetMemClkVfOffset(device Device) (int, Return) { + return device.GetMemClkVfOffset() +} + +func (device nvmlDevice) GetMemClkVfOffset() (int, Return) { + var offset int32 + ret := nvmlDeviceGetMemClkVfOffset(device, &offset) + return int(offset), ret +} + +// nvml.DeviceSetMemClkVfOffset() +// +// Deprecated: Use DeviceSetMemClkVfOffset instead +func (l *library) DeviceSetMemClkVfOffset(device Device, offset int) Return { + return device.SetMemClkVfOffset(offset) +} + +// Deprecated: Use DeviceSetMemClkVfOffset instead +func (device nvmlDevice) SetMemClkVfOffset(offset int) Return { + return nvmlDeviceSetMemClkVfOffset(device, int32(offset)) +} + +// nvml.DeviceGetGpcClkMinMaxVfOffset() +func (l *library) DeviceGetGpcClkMinMaxVfOffset(device Device) (int, int, Return) { + return device.GetGpcClkMinMaxVfOffset() +} + +func (device nvmlDevice) GetGpcClkMinMaxVfOffset() (int, int, Return) { + var minOffset, maxOffset int32 + ret := nvmlDeviceGetGpcClkMinMaxVfOffset(device, &minOffset, &maxOffset) + return int(minOffset), int(maxOffset), ret +} + +// nvml.DeviceGetMemClkMinMaxVfOffset() +func (l *library) DeviceGetMemClkMinMaxVfOffset(device Device) (int, int, Return) { + return device.GetMemClkMinMaxVfOffset() +} + +func (device nvmlDevice) GetMemClkMinMaxVfOffset() (int, int, Return) { + var minOffset, maxOffset int32 + ret := nvmlDeviceGetMemClkMinMaxVfOffset(device, &minOffset, &maxOffset) + return int(minOffset), int(maxOffset), ret +} + +// nvml.DeviceGetGpuMaxPcieLinkGeneration() +func (l *library) DeviceGetGpuMaxPcieLinkGeneration(device Device) (int, Return) { + return device.GetGpuMaxPcieLinkGeneration() +} + +func (device nvmlDevice) GetGpuMaxPcieLinkGeneration() (int, Return) { + var maxLinkGenDevice uint32 + ret := nvmlDeviceGetGpuMaxPcieLinkGeneration(device, &maxLinkGenDevice) + return int(maxLinkGenDevice), ret +} + +// nvml.DeviceGetFanControlPolicy_v2() +func (l *library) DeviceGetFanControlPolicy_v2(device Device, fan int) (FanControlPolicy, Return) { + return device.GetFanControlPolicy_v2(fan) +} + +func (device nvmlDevice) GetFanControlPolicy_v2(fan int) (FanControlPolicy, Return) { + var policy FanControlPolicy + ret := nvmlDeviceGetFanControlPolicy_v2(device, uint32(fan), &policy) + return policy, ret +} + +// nvml.DeviceSetFanControlPolicy() +func (l *library) DeviceSetFanControlPolicy(device Device, fan int, policy FanControlPolicy) Return { + return device.SetFanControlPolicy(fan, policy) +} + +func (device nvmlDevice) SetFanControlPolicy(fan int, policy FanControlPolicy) Return { + return nvmlDeviceSetFanControlPolicy(device, uint32(fan), policy) +} + +// nvml.DeviceClearFieldValues() +func (l *library) DeviceClearFieldValues(device Device, values []FieldValue) Return { + return device.ClearFieldValues(values) +} + +func (device nvmlDevice) ClearFieldValues(values []FieldValue) Return { + valuesCount := len(values) + return nvmlDeviceClearFieldValues(device, int32(valuesCount), &values[0]) +} + +// nvml.DeviceGetVgpuCapabilities() +func (l *library) DeviceGetVgpuCapabilities(device Device, capability DeviceVgpuCapability) (bool, Return) { + return device.GetVgpuCapabilities(capability) +} + +func (device nvmlDevice) GetVgpuCapabilities(capability DeviceVgpuCapability) (bool, Return) { + var capResult uint32 + ret := nvmlDeviceGetVgpuCapabilities(device, capability, &capResult) + return (capResult != 0), ret +} + +// nvml.DeviceGetVgpuSchedulerLog() +func (l *library) DeviceGetVgpuSchedulerLog(device Device) (VgpuSchedulerLog, Return) { + return device.GetVgpuSchedulerLog() +} + +func (device nvmlDevice) GetVgpuSchedulerLog() (VgpuSchedulerLog, Return) { + var pSchedulerLog VgpuSchedulerLog + ret := nvmlDeviceGetVgpuSchedulerLog(device, &pSchedulerLog) + return pSchedulerLog, ret +} + +// nvml.DeviceGetVgpuSchedulerState() +func (l *library) DeviceGetVgpuSchedulerState(device Device) (VgpuSchedulerGetState, Return) { + return device.GetVgpuSchedulerState() +} + +func (device nvmlDevice) GetVgpuSchedulerState() (VgpuSchedulerGetState, Return) { + var pSchedulerState VgpuSchedulerGetState + ret := nvmlDeviceGetVgpuSchedulerState(device, &pSchedulerState) + return pSchedulerState, ret +} + +// nvml.DeviceSetVgpuSchedulerState() +func (l *library) DeviceSetVgpuSchedulerState(device Device, pSchedulerState *VgpuSchedulerSetState) Return { + return device.SetVgpuSchedulerState(pSchedulerState) +} + +func (device nvmlDevice) SetVgpuSchedulerState(pSchedulerState *VgpuSchedulerSetState) Return { + return nvmlDeviceSetVgpuSchedulerState(device, pSchedulerState) +} + +// nvml.DeviceGetVgpuSchedulerCapabilities() +func (l *library) DeviceGetVgpuSchedulerCapabilities(device Device) (VgpuSchedulerCapabilities, Return) { + return device.GetVgpuSchedulerCapabilities() +} + +func (device nvmlDevice) GetVgpuSchedulerCapabilities() (VgpuSchedulerCapabilities, Return) { + var pCapabilities VgpuSchedulerCapabilities + ret := nvmlDeviceGetVgpuSchedulerCapabilities(device, &pCapabilities) + return pCapabilities, ret +} + +// nvml.GpuInstanceGetComputeInstancePossiblePlacements() +func (l *library) GpuInstanceGetComputeInstancePossiblePlacements(gpuInstance GpuInstance, info *ComputeInstanceProfileInfo) ([]ComputeInstancePlacement, Return) { + return gpuInstance.GetComputeInstancePossiblePlacements(info) +} + +func (gpuInstance nvmlGpuInstance) GetComputeInstancePossiblePlacements(info *ComputeInstanceProfileInfo) ([]ComputeInstancePlacement, Return) { + var count uint32 + ret := nvmlGpuInstanceGetComputeInstancePossiblePlacements(gpuInstance, info.Id, nil, &count) + if ret != SUCCESS { + return nil, ret + } + if count == 0 { + return []ComputeInstancePlacement{}, ret + } + placementArray := make([]ComputeInstancePlacement, count) + ret = nvmlGpuInstanceGetComputeInstancePossiblePlacements(gpuInstance, info.Id, &placementArray[0], &count) + return placementArray, ret +} + +// nvml.GpuInstanceCreateComputeInstanceWithPlacement() +func (l *library) GpuInstanceCreateComputeInstanceWithPlacement(gpuInstance GpuInstance, info *ComputeInstanceProfileInfo, placement *ComputeInstancePlacement) (ComputeInstance, Return) { + return gpuInstance.CreateComputeInstanceWithPlacement(info, placement) +} + +func (gpuInstance nvmlGpuInstance) CreateComputeInstanceWithPlacement(info *ComputeInstanceProfileInfo, placement *ComputeInstancePlacement) (ComputeInstance, Return) { + var computeInstance nvmlComputeInstance + ret := nvmlGpuInstanceCreateComputeInstanceWithPlacement(gpuInstance, info.Id, placement, &computeInstance) + return computeInstance, ret +} + +// nvml.DeviceGetGpuFabricInfo() +// +// Deprecated: Use DeviceGetGpuFabricInfoV instead +func (l *library) DeviceGetGpuFabricInfo(device Device) (GpuFabricInfo, Return) { + return device.GetGpuFabricInfo() +} + +// Deprecated: Use DeviceGetGpuFabricInfoV instead +func (device nvmlDevice) GetGpuFabricInfo() (GpuFabricInfo, Return) { + var gpuFabricInfo GpuFabricInfo + ret := nvmlDeviceGetGpuFabricInfo(device, &gpuFabricInfo) + return gpuFabricInfo, ret +} + +// nvml.DeviceSetNvLinkDeviceLowPowerThreshold() +func (l *library) DeviceSetNvLinkDeviceLowPowerThreshold(device Device, info *NvLinkPowerThres) Return { + return device.SetNvLinkDeviceLowPowerThreshold(info) +} + +func (device nvmlDevice) SetNvLinkDeviceLowPowerThreshold(info *NvLinkPowerThres) Return { + return nvmlDeviceSetNvLinkDeviceLowPowerThreshold(device, info) +} + +// nvml.DeviceGetModuleId() +func (l *library) DeviceGetModuleId(device Device) (int, Return) { + return device.GetModuleId() +} + +func (device nvmlDevice) GetModuleId() (int, Return) { + var moduleID uint32 + ret := nvmlDeviceGetModuleId(device, &moduleID) + return int(moduleID), ret +} + +// nvml.DeviceGetCurrentClocksEventReasons() +func (l *library) DeviceGetCurrentClocksEventReasons(device Device) (uint64, Return) { + return device.GetCurrentClocksEventReasons() +} + +func (device nvmlDevice) GetCurrentClocksEventReasons() (uint64, Return) { + var clocksEventReasons uint64 + ret := nvmlDeviceGetCurrentClocksEventReasons(device, &clocksEventReasons) + return clocksEventReasons, ret +} + +// nvml.DeviceGetSupportedClocksEventReasons() +func (l *library) DeviceGetSupportedClocksEventReasons(device Device) (uint64, Return) { + return device.GetSupportedClocksEventReasons() +} + +func (device nvmlDevice) GetSupportedClocksEventReasons() (uint64, Return) { + var supportedClocksEventReasons uint64 + ret := nvmlDeviceGetSupportedClocksEventReasons(device, &supportedClocksEventReasons) + return supportedClocksEventReasons, ret +} + +// nvml.DeviceGetJpgUtilization() +func (l *library) DeviceGetJpgUtilization(device Device) (uint32, uint32, Return) { + return device.GetJpgUtilization() +} + +func (device nvmlDevice) GetJpgUtilization() (uint32, uint32, Return) { + var utilization, samplingPeriodUs uint32 + ret := nvmlDeviceGetJpgUtilization(device, &utilization, &samplingPeriodUs) + return utilization, samplingPeriodUs, ret +} + +// nvml.DeviceGetOfaUtilization() +func (l *library) DeviceGetOfaUtilization(device Device) (uint32, uint32, Return) { + return device.GetOfaUtilization() +} + +func (device nvmlDevice) GetOfaUtilization() (uint32, uint32, Return) { + var utilization, samplingPeriodUs uint32 + ret := nvmlDeviceGetOfaUtilization(device, &utilization, &samplingPeriodUs) + return utilization, samplingPeriodUs, ret +} + +// nvml.DeviceGetRunningProcessDetailList() +func (l *library) DeviceGetRunningProcessDetailList(device Device) (ProcessDetailList, Return) { + return device.GetRunningProcessDetailList() +} + +func (device nvmlDevice) GetRunningProcessDetailList() (ProcessDetailList, Return) { + var plist ProcessDetailList + plist.Version = STRUCT_VERSION(plist, 1) + ret := nvmlDeviceGetRunningProcessDetailList(device, &plist) + return plist, ret +} + +// nvml.DeviceGetConfComputeMemSizeInfo() +func (l *library) DeviceGetConfComputeMemSizeInfo(device Device) (ConfComputeMemSizeInfo, Return) { + return device.GetConfComputeMemSizeInfo() +} + +func (device nvmlDevice) GetConfComputeMemSizeInfo() (ConfComputeMemSizeInfo, Return) { + var memInfo ConfComputeMemSizeInfo + ret := nvmlDeviceGetConfComputeMemSizeInfo(device, &memInfo) + return memInfo, ret +} + +// nvml.DeviceGetConfComputeProtectedMemoryUsage() +func (l *library) DeviceGetConfComputeProtectedMemoryUsage(device Device) (Memory, Return) { + return device.GetConfComputeProtectedMemoryUsage() +} + +func (device nvmlDevice) GetConfComputeProtectedMemoryUsage() (Memory, Return) { + var memory Memory + ret := nvmlDeviceGetConfComputeProtectedMemoryUsage(device, &memory) + return memory, ret +} + +// nvml.DeviceGetConfComputeGpuCertificate() +func (l *library) DeviceGetConfComputeGpuCertificate(device Device) (ConfComputeGpuCertificate, Return) { + return device.GetConfComputeGpuCertificate() +} + +func (device nvmlDevice) GetConfComputeGpuCertificate() (ConfComputeGpuCertificate, Return) { + var gpuCert ConfComputeGpuCertificate + ret := nvmlDeviceGetConfComputeGpuCertificate(device, &gpuCert) + return gpuCert, ret +} + +// nvml.DeviceGetConfComputeGpuAttestationReport() +func (l *library) DeviceGetConfComputeGpuAttestationReport(device Device, gpuAtstReport *ConfComputeGpuAttestationReport) Return { + return device.GetConfComputeGpuAttestationReport(gpuAtstReport) +} + +func (device nvmlDevice) GetConfComputeGpuAttestationReport(gpuAtstReport *ConfComputeGpuAttestationReport) Return { + return nvmlDeviceGetConfComputeGpuAttestationReport(device, gpuAtstReport) +} + +// nvml.DeviceSetConfComputeUnprotectedMemSize() +func (l *library) DeviceSetConfComputeUnprotectedMemSize(device Device, sizeKiB uint64) Return { + return device.SetConfComputeUnprotectedMemSize(sizeKiB) +} + +func (device nvmlDevice) SetConfComputeUnprotectedMemSize(sizeKiB uint64) Return { + return nvmlDeviceSetConfComputeUnprotectedMemSize(device, sizeKiB) +} + +// nvml.DeviceGetC2cModeInfoV() +type C2cModeInfoHandler struct { + device nvmlDevice +} + +func (handler C2cModeInfoHandler) V1() (C2cModeInfo_v1, Return) { + var c2cModeInfo C2cModeInfo_v1 + ret := nvmlDeviceGetC2cModeInfoV(handler.device, &c2cModeInfo) + return c2cModeInfo, ret +} + +func (l *library) DeviceGetC2cModeInfoV(device Device) C2cModeInfoHandler { + return device.GetC2cModeInfoV() +} + +func (device nvmlDevice) GetC2cModeInfoV() C2cModeInfoHandler { + return C2cModeInfoHandler{device} +} + +// nvml.DeviceGetLastBBXFlushTime() +func (l *library) DeviceGetLastBBXFlushTime(device Device) (uint64, uint, Return) { + return device.GetLastBBXFlushTime() +} + +func (device nvmlDevice) GetLastBBXFlushTime() (uint64, uint, Return) { + var timestamp uint64 + var durationUs uint + ret := nvmlDeviceGetLastBBXFlushTime(device, ×tamp, &durationUs) + return timestamp, durationUs, ret +} + +// nvml.DeviceGetNumaNodeId() +func (l *library) DeviceGetNumaNodeId(device Device) (int, Return) { + return device.GetNumaNodeId() +} + +func (device nvmlDevice) GetNumaNodeId() (int, Return) { + var node uint32 + ret := nvmlDeviceGetNumaNodeId(device, &node) + return int(node), ret +} + +func (l *library) DeviceGetAddressingMode(device Device) (DeviceAddressingMode, Return) { + return device.GetAddressingMode() +} + +func (device nvmlDevice) GetAddressingMode() (DeviceAddressingMode, Return) { + var deviceAddressingMode DeviceAddressingMode + deviceAddressingMode.Version = STRUCT_VERSION(deviceAddressingMode, 1) + ret := nvmlDeviceGetAddressingMode(device, &deviceAddressingMode) + return deviceAddressingMode, ret +} + +func (l *library) DeviceGetRepairStatus(device Device) (RepairStatus, Return) { + return device.GetRepairStatus() +} + +func (device nvmlDevice) GetRepairStatus() (RepairStatus, Return) { + var repairStatus RepairStatus + repairStatus.Version = STRUCT_VERSION(repairStatus, 1) + ret := nvmlDeviceGetRepairStatus(device, &repairStatus) + return repairStatus, ret +} + +// nvml.DeviceGetPciInfoExt() +func (l *library) DeviceGetPciInfoExt(device Device) (PciInfoExt, Return) { + return device.GetPciInfoExt() +} + +func (device nvmlDevice) GetPciInfoExt() (PciInfoExt, Return) { + var pciInfo PciInfoExt + pciInfo.Version = STRUCT_VERSION(pciInfo, 1) + ret := nvmlDeviceGetPciInfoExt(device, &pciInfo) + return pciInfo, ret +} + +// nvml.DeviceGetGpuFabricInfoV() +type GpuFabricInfoHandler struct { + device nvmlDevice +} + +func (handler GpuFabricInfoHandler) V1() (GpuFabricInfo, Return) { + return handler.device.GetGpuFabricInfo() +} + +func (handler GpuFabricInfoHandler) V2() (GpuFabricInfo_v2, Return) { + var info GpuFabricInfo_v2 + info.Version = STRUCT_VERSION(info, 2) + ret := nvmlDeviceGetGpuFabricInfoV(handler.device, (*GpuFabricInfoV)(unsafe.Pointer(&info))) + return info, ret +} + +func (handler GpuFabricInfoHandler) V3() (GpuFabricInfo_v3, Return) { + var info GpuFabricInfo_v3 + info.Version = STRUCT_VERSION(info, 3) + ret := nvmlDeviceGetGpuFabricInfoV(handler.device, (*GpuFabricInfoV)(unsafe.Pointer(&info))) + return info, ret +} + +func (l *library) DeviceGetGpuFabricInfoV(device Device) GpuFabricInfoHandler { + return device.GetGpuFabricInfoV() +} + +func (device nvmlDevice) GetGpuFabricInfoV() GpuFabricInfoHandler { + return GpuFabricInfoHandler{device} +} + +// nvml.DeviceGetProcessesUtilizationInfo() +func (l *library) DeviceGetProcessesUtilizationInfo(device Device) (ProcessesUtilizationInfo, Return) { + return device.GetProcessesUtilizationInfo() +} + +func (device nvmlDevice) GetProcessesUtilizationInfo() (ProcessesUtilizationInfo, Return) { + var processesUtilInfo ProcessesUtilizationInfo + ret := nvmlDeviceGetProcessesUtilizationInfo(device, &processesUtilInfo) + return processesUtilInfo, ret +} + +// nvml.DeviceGetVgpuHeterogeneousMode() +func (l *library) DeviceGetVgpuHeterogeneousMode(device Device) (VgpuHeterogeneousMode, Return) { + return device.GetVgpuHeterogeneousMode() +} + +func (device nvmlDevice) GetVgpuHeterogeneousMode() (VgpuHeterogeneousMode, Return) { + var heterogeneousMode VgpuHeterogeneousMode + heterogeneousMode.Version = STRUCT_VERSION(heterogeneousMode, 1) + ret := nvmlDeviceGetVgpuHeterogeneousMode(device, &heterogeneousMode) + return heterogeneousMode, ret +} + +// nvml.DeviceSetVgpuHeterogeneousMode() +func (l *library) DeviceSetVgpuHeterogeneousMode(device Device, heterogeneousMode VgpuHeterogeneousMode) Return { + return device.SetVgpuHeterogeneousMode(heterogeneousMode) +} + +func (device nvmlDevice) SetVgpuHeterogeneousMode(heterogeneousMode VgpuHeterogeneousMode) Return { + ret := nvmlDeviceSetVgpuHeterogeneousMode(device, &heterogeneousMode) + return ret +} + +// nvml.DeviceGetVgpuTypeSupportedPlacements() +func (l *library) DeviceGetVgpuTypeSupportedPlacements(device Device, vgpuTypeId VgpuTypeId) (VgpuPlacementList, Return) { + return device.GetVgpuTypeSupportedPlacements(vgpuTypeId) +} + +func (device nvmlDevice) GetVgpuTypeSupportedPlacements(vgpuTypeId VgpuTypeId) (VgpuPlacementList, Return) { + return vgpuTypeId.GetSupportedPlacements(device) +} + +func (vgpuTypeId nvmlVgpuTypeId) GetSupportedPlacements(device Device) (VgpuPlacementList, Return) { + var placementList VgpuPlacementList + placementList.Version = STRUCT_VERSION(placementList, 1) + ret := nvmlDeviceGetVgpuTypeSupportedPlacements(nvmlDeviceHandle(device), vgpuTypeId, &placementList) + return placementList, ret +} + +// nvml.DeviceGetVgpuTypeCreatablePlacements() +func (l *library) DeviceGetVgpuTypeCreatablePlacements(device Device, vgpuTypeId VgpuTypeId) (VgpuPlacementList, Return) { + return device.GetVgpuTypeCreatablePlacements(vgpuTypeId) +} + +func (device nvmlDevice) GetVgpuTypeCreatablePlacements(vgpuTypeId VgpuTypeId) (VgpuPlacementList, Return) { + return vgpuTypeId.GetCreatablePlacements(device) +} + +func (vgpuTypeId nvmlVgpuTypeId) GetCreatablePlacements(device Device) (VgpuPlacementList, Return) { + var placementList VgpuPlacementList + placementList.Version = STRUCT_VERSION(placementList, 1) + ret := nvmlDeviceGetVgpuTypeCreatablePlacements(nvmlDeviceHandle(device), vgpuTypeId, &placementList) + return placementList, ret +} + +// nvml.DeviceSetVgpuCapabilities() +func (l *library) DeviceSetVgpuCapabilities(device Device, capability DeviceVgpuCapability, state EnableState) Return { + return device.SetVgpuCapabilities(capability, state) +} + +func (device nvmlDevice) SetVgpuCapabilities(capability DeviceVgpuCapability, state EnableState) Return { + ret := nvmlDeviceSetVgpuCapabilities(device, capability, state) + return ret +} + +// nvml.DeviceGetVgpuInstancesUtilizationInfo() +func (l *library) DeviceGetVgpuInstancesUtilizationInfo(device Device) (VgpuInstancesUtilizationInfo, Return) { + return device.GetVgpuInstancesUtilizationInfo() +} + +func (device nvmlDevice) GetVgpuInstancesUtilizationInfo() (VgpuInstancesUtilizationInfo, Return) { + var vgpuUtilInfo VgpuInstancesUtilizationInfo + ret := nvmlDeviceGetVgpuInstancesUtilizationInfo(device, &vgpuUtilInfo) + return vgpuUtilInfo, ret +} + +// nvml.DeviceGetVgpuProcessesUtilizationInfo() +func (l *library) DeviceGetVgpuProcessesUtilizationInfo(device Device) (VgpuProcessesUtilizationInfo, Return) { + return device.GetVgpuProcessesUtilizationInfo() +} + +func (device nvmlDevice) GetVgpuProcessesUtilizationInfo() (VgpuProcessesUtilizationInfo, Return) { + var vgpuProcUtilInfo VgpuProcessesUtilizationInfo + vgpuProcUtilInfo.Version = STRUCT_VERSION(vgpuProcUtilInfo, 1) + ret := nvmlDeviceGetVgpuProcessesUtilizationInfo(device, &vgpuProcUtilInfo) + return vgpuProcUtilInfo, ret +} + +// nvml.DeviceGetSramEccErrorStatus() +func (l *library) DeviceGetSramEccErrorStatus(device Device) (EccSramErrorStatus, Return) { + return device.GetSramEccErrorStatus() +} + +func (device nvmlDevice) GetSramEccErrorStatus() (EccSramErrorStatus, Return) { + var status EccSramErrorStatus + status.Version = STRUCT_VERSION(status, 1) + ret := nvmlDeviceGetSramEccErrorStatus(device, &status) + return status, ret +} + +// nvml.DeviceGetClockOffsets() +func (l *library) DeviceGetClockOffsets(device Device) (ClockOffset, Return) { + return device.GetClockOffsets() +} + +func (device nvmlDevice) GetClockOffsets() (ClockOffset, Return) { + var info ClockOffset + info.Version = STRUCT_VERSION(info, 1) + ret := nvmlDeviceGetClockOffsets(device, &info) + return info, ret +} + +// nvml.DeviceSetClockOffsets() +func (l *library) DeviceSetClockOffsets(device Device, info ClockOffset) Return { + return device.SetClockOffsets(info) +} + +func (device nvmlDevice) SetClockOffsets(info ClockOffset) Return { + return nvmlDeviceSetClockOffsets(device, &info) +} + +// nvml.DeviceGetDriverModel_v2() +func (l *library) DeviceGetDriverModel_v2(device Device) (DriverModel, DriverModel, Return) { + return device.GetDriverModel_v2() +} + +func (device nvmlDevice) GetDriverModel_v2() (DriverModel, DriverModel, Return) { + var current, pending DriverModel + ret := nvmlDeviceGetDriverModel_v2(device, ¤t, &pending) + return current, pending, ret +} + +// nvml.DeviceGetCapabilities() +func (l *library) DeviceGetCapabilities(device Device) (DeviceCapabilities, Return) { + return device.GetCapabilities() +} + +func (device nvmlDevice) GetCapabilities() (DeviceCapabilities, Return) { + var caps DeviceCapabilities + caps.Version = STRUCT_VERSION(caps, 1) + ret := nvmlDeviceGetCapabilities(device, &caps) + return caps, ret +} + +// nvml.DeviceGetFanSpeedRPM() +func (l *library) DeviceGetFanSpeedRPM(device Device) (FanSpeedInfo, Return) { + return device.GetFanSpeedRPM() +} + +func (device nvmlDevice) GetFanSpeedRPM() (FanSpeedInfo, Return) { + var fanSpeed FanSpeedInfo + fanSpeed.Version = STRUCT_VERSION(fanSpeed, 1) + ret := nvmlDeviceGetFanSpeedRPM(device, &fanSpeed) + return fanSpeed, ret +} + +// nvml.DeviceGetCoolerInfo() +func (l *library) DeviceGetCoolerInfo(device Device) (CoolerInfo, Return) { + return device.GetCoolerInfo() +} + +func (device nvmlDevice) GetCoolerInfo() (CoolerInfo, Return) { + var coolerInfo CoolerInfo + coolerInfo.Version = STRUCT_VERSION(coolerInfo, 1) + ret := nvmlDeviceGetCoolerInfo(device, &coolerInfo) + return coolerInfo, ret +} + +// nvml.DeviceGetTemperatureV() +type TemperatureHandler struct { + device nvmlDevice +} + +func (handler TemperatureHandler) V1() (Temperature, Return) { + var temperature Temperature + temperature.Version = STRUCT_VERSION(temperature, 1) + ret := nvmlDeviceGetTemperatureV(handler.device, &temperature) + return temperature, ret +} + +func (l *library) DeviceGetTemperatureV(device Device) TemperatureHandler { + return device.GetTemperatureV() +} + +func (device nvmlDevice) GetTemperatureV() TemperatureHandler { + return TemperatureHandler{device} +} + +// nvml.DeviceGetMarginTemperature() +func (l *library) DeviceGetMarginTemperature(device Device) (MarginTemperature, Return) { + return device.GetMarginTemperature() +} + +func (device nvmlDevice) GetMarginTemperature() (MarginTemperature, Return) { + var marginTemp MarginTemperature + marginTemp.Version = STRUCT_VERSION(marginTemp, 1) + ret := nvmlDeviceGetMarginTemperature(device, &marginTemp) + return marginTemp, ret +} + +// nvml.DeviceGetPerformanceModes() +func (l *library) DeviceGetPerformanceModes(device Device) (DevicePerfModes, Return) { + return device.GetPerformanceModes() +} + +func (device nvmlDevice) GetPerformanceModes() (DevicePerfModes, Return) { + var perfModes DevicePerfModes + perfModes.Version = STRUCT_VERSION(perfModes, 1) + ret := nvmlDeviceGetPerformanceModes(device, &perfModes) + return perfModes, ret +} + +// nvml.DeviceGetCurrentClockFreqs() +func (l *library) DeviceGetCurrentClockFreqs(device Device) (DeviceCurrentClockFreqs, Return) { + return device.GetCurrentClockFreqs() +} + +func (device nvmlDevice) GetCurrentClockFreqs() (DeviceCurrentClockFreqs, Return) { + var currentClockFreqs DeviceCurrentClockFreqs + currentClockFreqs.Version = STRUCT_VERSION(currentClockFreqs, 1) + ret := nvmlDeviceGetCurrentClockFreqs(device, ¤tClockFreqs) + return currentClockFreqs, ret +} + +// nvml.DeviceGetDramEncryptionMode() +func (l *library) DeviceGetDramEncryptionMode(device Device) (DramEncryptionInfo, DramEncryptionInfo, Return) { + return device.GetDramEncryptionMode() +} + +func (device nvmlDevice) GetDramEncryptionMode() (DramEncryptionInfo, DramEncryptionInfo, Return) { + var current, pending DramEncryptionInfo + current.Version = STRUCT_VERSION(current, 1) + pending.Version = STRUCT_VERSION(pending, 1) + ret := nvmlDeviceGetDramEncryptionMode(device, ¤t, &pending) + return current, pending, ret +} + +// nvml.DeviceSetDramEncryptionMode() +func (l *library) DeviceSetDramEncryptionMode(device Device, dramEncryption *DramEncryptionInfo) Return { + return device.SetDramEncryptionMode(dramEncryption) +} + +func (device nvmlDevice) SetDramEncryptionMode(dramEncryption *DramEncryptionInfo) Return { + return nvmlDeviceSetDramEncryptionMode(device, dramEncryption) +} + +// nvml.DeviceGetPlatformInfo() +func (l *library) DeviceGetPlatformInfo(device Device) (PlatformInfo, Return) { + return device.GetPlatformInfo() +} + +func (device nvmlDevice) GetPlatformInfo() (PlatformInfo, Return) { + var platformInfo PlatformInfo + platformInfo.Version = STRUCT_VERSION(platformInfo, 1) + ret := nvmlDeviceGetPlatformInfo(device, &platformInfo) + return platformInfo, ret +} + +// nvml.DeviceGetNvlinkSupportedBwModes() +func (l *library) DeviceGetNvlinkSupportedBwModes(device Device) (NvlinkSupportedBwModes, Return) { + return device.GetNvlinkSupportedBwModes() +} + +func (device nvmlDevice) GetNvlinkSupportedBwModes() (NvlinkSupportedBwModes, Return) { + var supportedBwMode NvlinkSupportedBwModes + supportedBwMode.Version = STRUCT_VERSION(supportedBwMode, 1) + ret := nvmlDeviceGetNvlinkSupportedBwModes(device, &supportedBwMode) + return supportedBwMode, ret +} + +// nvml.DeviceGetNvlinkBwMode() +func (l *library) DeviceGetNvlinkBwMode(device Device) (NvlinkGetBwMode, Return) { + return device.GetNvlinkBwMode() +} + +func (device nvmlDevice) GetNvlinkBwMode() (NvlinkGetBwMode, Return) { + var getBwMode NvlinkGetBwMode + getBwMode.Version = STRUCT_VERSION(getBwMode, 1) + ret := nvmlDeviceGetNvlinkBwMode(device, &getBwMode) + return getBwMode, ret +} + +// nvml.DeviceSetNvlinkBwMode() +func (l *library) DeviceSetNvlinkBwMode(device Device, setBwMode *NvlinkSetBwMode) Return { + return device.SetNvlinkBwMode(setBwMode) +} + +func (device nvmlDevice) SetNvlinkBwMode(setBwMode *NvlinkSetBwMode) Return { + return nvmlDeviceSetNvlinkBwMode(device, setBwMode) +} + +func (l *library) DeviceGetNvLinkInfo(device Device) NvLinkInfoHandler { + return device.GetNvLinkInfo() +} + +func (device nvmlDevice) GetNvLinkInfo() NvLinkInfoHandler { + return NvLinkInfoHandler{device} +} + +type NvLinkInfoHandler struct { + device nvmlDevice +} + +func (handler NvLinkInfoHandler) V1() (NvLinkInfo_v1, Return) { + var info NvLinkInfo_v1 + info.Version = STRUCT_VERSION(info, 1) + ret := nvmlDeviceGetNvLinkInfo(handler.device, (*NvLinkInfo)(unsafe.Pointer(&info))) + + return info, ret +} + +func (handler NvLinkInfoHandler) V2() (NvLinkInfo_v2, Return) { + var info NvLinkInfo_v2 + info.Version = STRUCT_VERSION(info, 2) + ret := nvmlDeviceGetNvLinkInfo(handler.device, (*NvLinkInfo)(unsafe.Pointer(&info))) + + return info, ret +} + +// nvml.DeviceWorkloadPowerProfileGetProfilesInfo() +func (l *library) DeviceWorkloadPowerProfileGetProfilesInfo(device Device) (WorkloadPowerProfileProfilesInfo, Return) { + return device.WorkloadPowerProfileGetProfilesInfo() +} + +func (device nvmlDevice) WorkloadPowerProfileGetProfilesInfo() (WorkloadPowerProfileProfilesInfo, Return) { + var profilesInfo WorkloadPowerProfileProfilesInfo + profilesInfo.Version = STRUCT_VERSION(profilesInfo, 1) + ret := nvmlDeviceWorkloadPowerProfileGetProfilesInfo(device, &profilesInfo) + return profilesInfo, ret +} + +// nvml.DeviceWorkloadPowerProfileGetCurrentProfiles() +func (l *library) DeviceWorkloadPowerProfileGetCurrentProfiles(device Device) (WorkloadPowerProfileCurrentProfiles, Return) { + return device.WorkloadPowerProfileGetCurrentProfiles() +} + +func (device nvmlDevice) WorkloadPowerProfileGetCurrentProfiles() (WorkloadPowerProfileCurrentProfiles, Return) { + var currentProfiles WorkloadPowerProfileCurrentProfiles + currentProfiles.Version = STRUCT_VERSION(currentProfiles, 1) + ret := nvmlDeviceWorkloadPowerProfileGetCurrentProfiles(device, ¤tProfiles) + return currentProfiles, ret +} + +// nvml.DeviceWorkloadPowerProfileSetRequestedProfiles() +func (l *library) DeviceWorkloadPowerProfileSetRequestedProfiles(device Device, requestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + return device.WorkloadPowerProfileSetRequestedProfiles(requestedProfiles) +} + +func (device nvmlDevice) WorkloadPowerProfileSetRequestedProfiles(requestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + return nvmlDeviceWorkloadPowerProfileSetRequestedProfiles(device, requestedProfiles) +} + +// nvml.DeviceWorkloadPowerProfileClearRequestedProfiles() +func (l *library) DeviceWorkloadPowerProfileClearRequestedProfiles(device Device, requestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + return device.WorkloadPowerProfileClearRequestedProfiles(requestedProfiles) +} + +func (device nvmlDevice) WorkloadPowerProfileClearRequestedProfiles(requestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + return nvmlDeviceWorkloadPowerProfileClearRequestedProfiles(device, requestedProfiles) +} + +// nvml.DevicePowerSmoothingActivatePresetProfile() +func (l *library) DevicePowerSmoothingActivatePresetProfile(device Device, profile *PowerSmoothingProfile) Return { + return device.PowerSmoothingActivatePresetProfile(profile) +} + +func (device nvmlDevice) PowerSmoothingActivatePresetProfile(profile *PowerSmoothingProfile) Return { + return nvmlDevicePowerSmoothingActivatePresetProfile(device, profile) +} + +// nvml.DevicePowerSmoothingUpdatePresetProfileParam() +func (l *library) DevicePowerSmoothingUpdatePresetProfileParam(device Device, profile *PowerSmoothingProfile) Return { + return device.PowerSmoothingUpdatePresetProfileParam(profile) +} + +func (device nvmlDevice) PowerSmoothingUpdatePresetProfileParam(profile *PowerSmoothingProfile) Return { + return nvmlDevicePowerSmoothingUpdatePresetProfileParam(device, profile) +} + +// nvml.DevicePowerSmoothingSetState() +func (l *library) DevicePowerSmoothingSetState(device Device, state *PowerSmoothingState) Return { + return device.PowerSmoothingSetState(state) +} + +func (device nvmlDevice) PowerSmoothingSetState(state *PowerSmoothingState) Return { + return nvmlDevicePowerSmoothingSetState(device, state) +} + +func (l *library) DeviceGetSramUniqueUncorrectedEccErrorCounts(device Device, errorCounts *EccSramUniqueUncorrectedErrorCounts) Return { + return device.GetSramUniqueUncorrectedEccErrorCounts(errorCounts) +} + +func (device nvmlDevice) GetSramUniqueUncorrectedEccErrorCounts(errorCounts *EccSramUniqueUncorrectedErrorCounts) Return { + return nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(device, errorCounts) +} + +// nvml.GpuInstanceGetCreatableVgpus() +func (l *library) GpuInstanceGetCreatableVgpus(gpuInstance GpuInstance) (VgpuTypeIdInfo, Return) { + return gpuInstance.GetCreatableVgpus() +} + +func (gpuInstance nvmlGpuInstance) GetCreatableVgpus() (VgpuTypeIdInfo, Return) { + var vgpuTypeIdInfo VgpuTypeIdInfo + vgpuTypeIdInfo.Version = STRUCT_VERSION(vgpuTypeIdInfo, 1) + ret := nvmlGpuInstanceGetCreatableVgpus(gpuInstance, &vgpuTypeIdInfo) + return vgpuTypeIdInfo, ret +} + +// nvml.GpuInstanceGetActiveVgpus() +func (l *library) GpuInstanceGetActiveVgpus(gpuInstance GpuInstance) (ActiveVgpuInstanceInfo, Return) { + return gpuInstance.GetActiveVgpus() +} + +func (gpuInstance nvmlGpuInstance) GetActiveVgpus() (ActiveVgpuInstanceInfo, Return) { + var activeVgpuInstanceInfo ActiveVgpuInstanceInfo + activeVgpuInstanceInfo.Version = STRUCT_VERSION(activeVgpuInstanceInfo, 1) + ret := nvmlGpuInstanceGetActiveVgpus(gpuInstance, &activeVgpuInstanceInfo) + return activeVgpuInstanceInfo, ret +} + +// nvml.GpuInstanceSetVgpuSchedulerState() +func (l *library) GpuInstanceSetVgpuSchedulerState(gpuInstance GpuInstance, scheduler *VgpuSchedulerState) Return { + return gpuInstance.SetVgpuSchedulerState(scheduler) +} + +func (gpuInstance nvmlGpuInstance) SetVgpuSchedulerState(scheduler *VgpuSchedulerState) Return { + return nvmlGpuInstanceSetVgpuSchedulerState(gpuInstance, scheduler) +} + +// nvml.GpuInstanceGetVgpuSchedulerState() +func (l *library) GpuInstanceGetVgpuSchedulerState(gpuInstance GpuInstance) (VgpuSchedulerStateInfo, Return) { + return gpuInstance.GetVgpuSchedulerState() +} + +func (gpuInstance nvmlGpuInstance) GetVgpuSchedulerState() (VgpuSchedulerStateInfo, Return) { + var schedulerStateInfo VgpuSchedulerStateInfo + schedulerStateInfo.Version = STRUCT_VERSION(schedulerStateInfo, 1) + ret := nvmlGpuInstanceGetVgpuSchedulerState(gpuInstance, &schedulerStateInfo) + return schedulerStateInfo, ret +} + +// nvml.GpuInstanceGetVgpuSchedulerLog() +func (l *library) GpuInstanceGetVgpuSchedulerLog(gpuInstance GpuInstance) (VgpuSchedulerLogInfo, Return) { + return gpuInstance.GetVgpuSchedulerLog() +} + +func (gpuInstance nvmlGpuInstance) GetVgpuSchedulerLog() (VgpuSchedulerLogInfo, Return) { + var schedulerLogInfo VgpuSchedulerLogInfo + schedulerLogInfo.Version = STRUCT_VERSION(schedulerLogInfo, 1) + ret := nvmlGpuInstanceGetVgpuSchedulerLog(gpuInstance, &schedulerLogInfo) + return schedulerLogInfo, ret +} + +// nvml.GpuInstanceGetVgpuTypeCreatablePlacements() +func (l *library) GpuInstanceGetVgpuTypeCreatablePlacements(gpuInstance GpuInstance) (VgpuCreatablePlacementInfo, Return) { + return gpuInstance.GetVgpuTypeCreatablePlacements() +} + +func (gpuInstance nvmlGpuInstance) GetVgpuTypeCreatablePlacements() (VgpuCreatablePlacementInfo, Return) { + var creatablePlacementInfo VgpuCreatablePlacementInfo + creatablePlacementInfo.Version = STRUCT_VERSION(creatablePlacementInfo, 1) + ret := nvmlGpuInstanceGetVgpuTypeCreatablePlacements(gpuInstance, &creatablePlacementInfo) + return creatablePlacementInfo, ret +} + +// nvml.GpuInstanceGetVgpuHeterogeneousMode() +func (l *library) GpuInstanceGetVgpuHeterogeneousMode(gpuInstance GpuInstance) (VgpuHeterogeneousMode, Return) { + return gpuInstance.GetVgpuHeterogeneousMode() +} + +func (gpuInstance nvmlGpuInstance) GetVgpuHeterogeneousMode() (VgpuHeterogeneousMode, Return) { + var heterogeneousMode VgpuHeterogeneousMode + heterogeneousMode.Version = STRUCT_VERSION(heterogeneousMode, 1) + ret := nvmlGpuInstanceGetVgpuHeterogeneousMode(gpuInstance, &heterogeneousMode) + return heterogeneousMode, ret +} + +// nvml.GpuInstanceSetVgpuHeterogeneousMode() +func (l *library) GpuInstanceSetVgpuHeterogeneousMode(gpuInstance GpuInstance, heterogeneousMode *VgpuHeterogeneousMode) Return { + return gpuInstance.SetVgpuHeterogeneousMode(heterogeneousMode) +} + +func (gpuInstance nvmlGpuInstance) SetVgpuHeterogeneousMode(heterogeneousMode *VgpuHeterogeneousMode) Return { + return nvmlGpuInstanceSetVgpuHeterogeneousMode(gpuInstance, heterogeneousMode) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/doc.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/doc.go new file mode 100644 index 00000000..c2ce2e37 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/doc.go @@ -0,0 +1,21 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +/* +Package NVML bindings +*/ +package nvml diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/dynamicLibrary_mock.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/dynamicLibrary_mock.go new file mode 100644 index 00000000..b785431c --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/dynamicLibrary_mock.go @@ -0,0 +1,157 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package nvml + +import ( + "sync" +) + +// Ensure, that dynamicLibraryMock does implement dynamicLibrary. +// If this is not the case, regenerate this file with moq. +var _ dynamicLibrary = &dynamicLibraryMock{} + +// dynamicLibraryMock is a mock implementation of dynamicLibrary. +// +// func TestSomethingThatUsesdynamicLibrary(t *testing.T) { +// +// // make and configure a mocked dynamicLibrary +// mockeddynamicLibrary := &dynamicLibraryMock{ +// CloseFunc: func() error { +// panic("mock out the Close method") +// }, +// LookupFunc: func(s string) error { +// panic("mock out the Lookup method") +// }, +// OpenFunc: func() error { +// panic("mock out the Open method") +// }, +// } +// +// // use mockeddynamicLibrary in code that requires dynamicLibrary +// // and then make assertions. +// +// } +type dynamicLibraryMock struct { + // CloseFunc mocks the Close method. + CloseFunc func() error + + // LookupFunc mocks the Lookup method. + LookupFunc func(s string) error + + // OpenFunc mocks the Open method. + OpenFunc func() error + + // calls tracks calls to the methods. + calls struct { + // Close holds details about calls to the Close method. + Close []struct { + } + // Lookup holds details about calls to the Lookup method. + Lookup []struct { + // S is the s argument value. + S string + } + // Open holds details about calls to the Open method. + Open []struct { + } + } + lockClose sync.RWMutex + lockLookup sync.RWMutex + lockOpen sync.RWMutex +} + +// Close calls CloseFunc. +func (mock *dynamicLibraryMock) Close() error { + callInfo := struct { + }{} + mock.lockClose.Lock() + mock.calls.Close = append(mock.calls.Close, callInfo) + mock.lockClose.Unlock() + if mock.CloseFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.CloseFunc() +} + +// CloseCalls gets all the calls that were made to Close. +// Check the length with: +// +// len(mockeddynamicLibrary.CloseCalls()) +func (mock *dynamicLibraryMock) CloseCalls() []struct { +} { + var calls []struct { + } + mock.lockClose.RLock() + calls = mock.calls.Close + mock.lockClose.RUnlock() + return calls +} + +// Lookup calls LookupFunc. +func (mock *dynamicLibraryMock) Lookup(s string) error { + callInfo := struct { + S string + }{ + S: s, + } + mock.lockLookup.Lock() + mock.calls.Lookup = append(mock.calls.Lookup, callInfo) + mock.lockLookup.Unlock() + if mock.LookupFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.LookupFunc(s) +} + +// LookupCalls gets all the calls that were made to Lookup. +// Check the length with: +// +// len(mockeddynamicLibrary.LookupCalls()) +func (mock *dynamicLibraryMock) LookupCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockLookup.RLock() + calls = mock.calls.Lookup + mock.lockLookup.RUnlock() + return calls +} + +// Open calls OpenFunc. +func (mock *dynamicLibraryMock) Open() error { + callInfo := struct { + }{} + mock.lockOpen.Lock() + mock.calls.Open = append(mock.calls.Open, callInfo) + mock.lockOpen.Unlock() + if mock.OpenFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.OpenFunc() +} + +// OpenCalls gets all the calls that were made to Open. +// Check the length with: +// +// len(mockeddynamicLibrary.OpenCalls()) +func (mock *dynamicLibraryMock) OpenCalls() []struct { +} { + var calls []struct { + } + mock.lockOpen.RLock() + calls = mock.calls.Open + mock.lockOpen.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/event_set.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/event_set.go new file mode 100644 index 00000000..b772d57f --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/event_set.go @@ -0,0 +1,82 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +// EventData includes an interface type for Device instead of nvmlDevice +type EventData struct { + Device Device + EventType uint64 + EventData uint64 + GpuInstanceId uint32 + ComputeInstanceId uint32 +} + +func (e nvmlEventData) convert() EventData { + out := EventData{ + Device: e.Device, + EventType: e.EventType, + EventData: e.EventData, + GpuInstanceId: e.GpuInstanceId, + ComputeInstanceId: e.ComputeInstanceId, + } + return out +} + +// nvml.EventSetCreate() +func (l *library) EventSetCreate() (EventSet, Return) { + var Set nvmlEventSet + ret := nvmlEventSetCreate(&Set) + return Set, ret +} + +// nvml.EventSetWait() +func (l *library) EventSetWait(set EventSet, timeoutms uint32) (EventData, Return) { + return set.Wait(timeoutms) +} + +func (set nvmlEventSet) Wait(timeoutms uint32) (EventData, Return) { + var data nvmlEventData + ret := nvmlEventSetWait(set, &data, timeoutms) + return data.convert(), ret +} + +// nvml.EventSetFree() +func (l *library) EventSetFree(set EventSet) Return { + return set.Free() +} + +func (set nvmlEventSet) Free() Return { + return nvmlEventSetFree(set) +} + +// nvml.SystemEventSetCreate() +func (l *library) SystemEventSetCreate(request *SystemEventSetCreateRequest) Return { + return nvmlSystemEventSetCreate(request) +} + +// nvml.SystemEventSetFree() +func (l *library) SystemEventSetFree(request *SystemEventSetFreeRequest) Return { + return nvmlSystemEventSetFree(request) +} + +// nvml.SystemRegisterEvents() +func (l *library) SystemRegisterEvents(request *SystemRegisterEventRequest) Return { + return nvmlSystemRegisterEvents(request) +} + +// nvml.SystemEventSetWait() +func (l *library) SystemEventSetWait(request *SystemEventSetWaitRequest) Return { + return nvmlSystemEventSetWait(request) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/gpm.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/gpm.go new file mode 100644 index 00000000..563bc593 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/gpm.go @@ -0,0 +1,170 @@ +// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +// GpmMetricsGetType includes interface types for GpmSample instead of nvmlGpmSample +type GpmMetricsGetType struct { + Version uint32 + NumMetrics uint32 + Sample1 GpmSample + Sample2 GpmSample + Metrics [210]GpmMetric +} + +func (g *GpmMetricsGetType) convert() *nvmlGpmMetricsGetType { + out := &nvmlGpmMetricsGetType{ + Version: g.Version, + NumMetrics: g.NumMetrics, + Sample1: g.Sample1.(nvmlGpmSample), + Sample2: g.Sample2.(nvmlGpmSample), + } + copy(out.Metrics[:], g.Metrics[:]) + + return out +} + +func (g *nvmlGpmMetricsGetType) convert() *GpmMetricsGetType { + out := &GpmMetricsGetType{ + Version: g.Version, + NumMetrics: g.NumMetrics, + Sample1: g.Sample1, + Sample2: g.Sample2, + } + copy(out.Metrics[:], g.Metrics[:]) + + return out +} + +// nvml.GpmMetricsGet() +type GpmMetricsGetVType struct { + metricsGet *GpmMetricsGetType +} + +func (l *library) GpmMetricsGetV(metricsGet *GpmMetricsGetType) GpmMetricsGetVType { + return GpmMetricsGetVType{metricsGet} +} + +// nvmlGpmMetricsGetStub is a stub function that can be overridden for testing. +var nvmlGpmMetricsGetStub = nvmlGpmMetricsGet + +func (metricsGetV GpmMetricsGetVType) V1() Return { + metricsGetV.metricsGet.Version = 1 + return gpmMetricsGet(metricsGetV.metricsGet) +} + +func (l *library) GpmMetricsGet(metricsGet *GpmMetricsGetType) Return { + metricsGet.Version = GPM_METRICS_GET_VERSION + return gpmMetricsGet(metricsGet) +} + +func gpmMetricsGet(metricsGet *GpmMetricsGetType) Return { + nvmlMetricsGet := metricsGet.convert() + ret := nvmlGpmMetricsGetStub(nvmlMetricsGet) + *metricsGet = *nvmlMetricsGet.convert() + return ret +} + +// nvml.GpmSampleFree() +func (l *library) GpmSampleFree(gpmSample GpmSample) Return { + return gpmSample.Free() +} + +func (gpmSample nvmlGpmSample) Free() Return { + return nvmlGpmSampleFree(gpmSample) +} + +// nvml.GpmSampleAlloc() +func (l *library) GpmSampleAlloc() (GpmSample, Return) { + var gpmSample nvmlGpmSample + ret := nvmlGpmSampleAlloc(&gpmSample) + return gpmSample, ret +} + +// nvml.GpmSampleGet() +func (l *library) GpmSampleGet(device Device, gpmSample GpmSample) Return { + return gpmSample.Get(device) +} + +func (device nvmlDevice) GpmSampleGet(gpmSample GpmSample) Return { + return gpmSample.Get(device) +} + +func (gpmSample nvmlGpmSample) Get(device Device) Return { + return nvmlGpmSampleGet(nvmlDeviceHandle(device), gpmSample) +} + +// nvml.GpmQueryDeviceSupport() +type GpmSupportV struct { + device nvmlDevice +} + +func (l *library) GpmQueryDeviceSupportV(device Device) GpmSupportV { + return device.GpmQueryDeviceSupportV() +} + +func (device nvmlDevice) GpmQueryDeviceSupportV() GpmSupportV { + return GpmSupportV{device} +} + +func (gpmSupportV GpmSupportV) V1() (GpmSupport, Return) { + var gpmSupport GpmSupport + gpmSupport.Version = STRUCT_VERSION(gpmSupport, 1) + ret := nvmlGpmQueryDeviceSupport(gpmSupportV.device, &gpmSupport) + return gpmSupport, ret +} + +func (l *library) GpmQueryDeviceSupport(device Device) (GpmSupport, Return) { + return device.GpmQueryDeviceSupport() +} + +func (device nvmlDevice) GpmQueryDeviceSupport() (GpmSupport, Return) { + var gpmSupport GpmSupport + gpmSupport.Version = STRUCT_VERSION(gpmSupport, GPM_SUPPORT_VERSION) + ret := nvmlGpmQueryDeviceSupport(device, &gpmSupport) + return gpmSupport, ret +} + +// nvml.GpmMigSampleGet() +func (l *library) GpmMigSampleGet(device Device, gpuInstanceId int, gpmSample GpmSample) Return { + return gpmSample.MigGet(device, gpuInstanceId) +} + +func (device nvmlDevice) GpmMigSampleGet(gpuInstanceId int, gpmSample GpmSample) Return { + return gpmSample.MigGet(device, gpuInstanceId) +} + +func (gpmSample nvmlGpmSample) MigGet(device Device, gpuInstanceId int) Return { + return nvmlGpmMigSampleGet(nvmlDeviceHandle(device), uint32(gpuInstanceId), gpmSample) +} + +// nvml.GpmQueryIfStreamingEnabled() +func (l *library) GpmQueryIfStreamingEnabled(device Device) (uint32, Return) { + return device.GpmQueryIfStreamingEnabled() +} + +func (device nvmlDevice) GpmQueryIfStreamingEnabled() (uint32, Return) { + var state uint32 + ret := nvmlGpmQueryIfStreamingEnabled(device, &state) + return state, ret +} + +// nvml.GpmSetStreamingEnabled() +func (l *library) GpmSetStreamingEnabled(device Device, state uint32) Return { + return device.GpmSetStreamingEnabled(state) +} + +func (device nvmlDevice) GpmSetStreamingEnabled(state uint32) Return { + return nvmlGpmSetStreamingEnabled(device, state) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/init.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/init.go new file mode 100644 index 00000000..06e64441 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/init.go @@ -0,0 +1,48 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import "C" + +// nvml.Init() +func (l *library) Init() Return { + if err := l.load(); err != nil { + return ERROR_LIBRARY_NOT_FOUND + } + return nvmlInit() +} + +// nvml.InitWithFlags() +func (l *library) InitWithFlags(flags uint32) Return { + if err := l.load(); err != nil { + return ERROR_LIBRARY_NOT_FOUND + } + return nvmlInitWithFlags(flags) +} + +// nvml.Shutdown() +func (l *library) Shutdown() Return { + ret := nvmlShutdown() + if ret != SUCCESS { + return ret + } + + err := l.close() + if err != nil { + return ERROR_UNKNOWN + } + + return ret +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/lib.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/lib.go new file mode 100644 index 00000000..5a7e6882 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/lib.go @@ -0,0 +1,296 @@ +/** +# Copyright 2023 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvml + +import ( + "errors" + "fmt" + "sync" + + "github.com/NVIDIA/go-nvml/pkg/dl" +) + +import "C" + +const ( + defaultNvmlLibraryName = "libnvidia-ml.so.1" + defaultNvmlLibraryLoadFlags = dl.RTLD_LAZY | dl.RTLD_GLOBAL +) + +var errLibraryNotLoaded = errors.New("library not loaded") +var errLibraryAlreadyLoaded = errors.New("library already loaded") + +// dynamicLibrary is an interface for abstacting the underlying library. +// This also allows for mocking and testing. + +//go:generate moq -stub -out dynamicLibrary_mock.go . dynamicLibrary +type dynamicLibrary interface { + Lookup(string) error + Open() error + Close() error +} + +// library represents an nvml library. +// This includes a reference to the underlying DynamicLibrary +type library struct { + sync.Mutex + path string + refcount refcount + dl dynamicLibrary +} + +var _ Interface = (*library)(nil) + +// libnvml is a global instance of the nvml library. +var libnvml = newLibrary() + +func New(opts ...LibraryOption) Interface { + return newLibrary(opts...) +} + +func newLibrary(opts ...LibraryOption) *library { + l := &library{} + l.init(opts...) + return l +} + +func (l *library) init(opts ...LibraryOption) { + o := libraryOptions{} + for _, opt := range opts { + opt(&o) + } + + if o.path == "" { + o.path = defaultNvmlLibraryName + } + if o.flags == 0 { + o.flags = defaultNvmlLibraryLoadFlags + } + + l.path = o.path + l.dl = dl.New(o.path, o.flags) +} + +func (l *library) Extensions() ExtendedInterface { + return l +} + +// LookupSymbol checks whether the specified library symbol exists in the library. +// Note that this requires that the library be loaded. +func (l *library) LookupSymbol(name string) error { + if l == nil || l.refcount == 0 { + return fmt.Errorf("error looking up %s: %w", name, errLibraryNotLoaded) + } + return l.dl.Lookup(name) +} + +// load initializes the library and updates the versioned symbols. +// Multiple calls to an already loaded library will return without error. +func (l *library) load() (rerr error) { + l.Lock() + defer l.Unlock() + + defer func() { l.refcount.IncOnNoError(rerr) }() + if l.refcount > 0 { + return nil + } + + if err := l.dl.Open(); err != nil { + return fmt.Errorf("error opening %s: %w", l.path, err) + } + + // Update the errorStringFunc to point to nvml.ErrorString + errorStringFunc = nvmlErrorString + + // Update all versioned symbols + l.updateVersionedSymbols() + + return nil +} + +// close the underlying library and ensure that the global pointer to the +// library is set to nil to ensure that subsequent calls to open will reinitialize it. +// Multiple calls to an already closed nvml library will return without error. +func (l *library) close() (rerr error) { + l.Lock() + defer l.Unlock() + + defer func() { l.refcount.DecOnNoError(rerr) }() + if l.refcount != 1 { + return nil + } + + if err := l.dl.Close(); err != nil { + return fmt.Errorf("error closing %s: %w", l.path, err) + } + + // Update the errorStringFunc to point to defaultErrorStringFunc + errorStringFunc = defaultErrorStringFunc + + return nil +} + +// Default all versioned APIs to v1 (to infer the types) +var nvmlInit = nvmlInit_v1 +var nvmlDeviceGetPciInfo = nvmlDeviceGetPciInfo_v1 +var nvmlDeviceGetCount = nvmlDeviceGetCount_v1 +var nvmlDeviceGetHandleByIndex = nvmlDeviceGetHandleByIndex_v1 +var nvmlDeviceGetHandleByPciBusId = nvmlDeviceGetHandleByPciBusId_v1 +var nvmlDeviceGetNvLinkRemotePciInfo = nvmlDeviceGetNvLinkRemotePciInfo_v1 +var nvmlDeviceRemoveGpu = nvmlDeviceRemoveGpu_v1 +var nvmlDeviceGetGridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures_v1 +var nvmlEventSetWait = nvmlEventSetWait_v1 +var nvmlDeviceGetAttributes = nvmlDeviceGetAttributes_v1 +var nvmlComputeInstanceGetInfo = nvmlComputeInstanceGetInfo_v1 +var deviceGetComputeRunningProcesses = deviceGetComputeRunningProcesses_v1 +var deviceGetGraphicsRunningProcesses = deviceGetGraphicsRunningProcesses_v1 +var deviceGetMPSComputeRunningProcesses = deviceGetMPSComputeRunningProcesses_v1 +var GetBlacklistDeviceCount = GetExcludedDeviceCount +var GetBlacklistDeviceInfoByIndex = GetExcludedDeviceInfoByIndex +var nvmlDeviceGetGpuInstancePossiblePlacements = nvmlDeviceGetGpuInstancePossiblePlacements_v1 +var nvmlVgpuInstanceGetLicenseInfo = nvmlVgpuInstanceGetLicenseInfo_v1 +var nvmlDeviceGetDriverModel = nvmlDeviceGetDriverModel_v1 + +// BlacklistDeviceInfo was replaced by ExcludedDeviceInfo +type BlacklistDeviceInfo = ExcludedDeviceInfo + +type ProcessInfo_v1Slice []ProcessInfo_v1 +type ProcessInfo_v2Slice []ProcessInfo_v2 + +func (pis ProcessInfo_v1Slice) ToProcessInfoSlice() []ProcessInfo { + var newInfos []ProcessInfo + for _, pi := range pis { + info := ProcessInfo{ + Pid: pi.Pid, + UsedGpuMemory: pi.UsedGpuMemory, + GpuInstanceId: 0xFFFFFFFF, // GPU instance ID is invalid in v1 + ComputeInstanceId: 0xFFFFFFFF, // Compute instance ID is invalid in v1 + } + newInfos = append(newInfos, info) + } + return newInfos +} + +func (pis ProcessInfo_v2Slice) ToProcessInfoSlice() []ProcessInfo { + var newInfos []ProcessInfo + for _, pi := range pis { + info := ProcessInfo(pi) + newInfos = append(newInfos, info) + } + return newInfos +} + +// updateVersionedSymbols checks for versioned symbols in the loaded dynamic library. +// If newer versioned symbols exist, these replace the default `v1` symbols initialized above. +// When new versioned symbols are added, these would have to be initialized above and have +// corresponding checks and subsequent assignments added below. +func (l *library) updateVersionedSymbols() { + err := l.dl.Lookup("nvmlInit_v2") + if err == nil { + nvmlInit = nvmlInit_v2 + } + err = l.dl.Lookup("nvmlDeviceGetPciInfo_v2") + if err == nil { + nvmlDeviceGetPciInfo = nvmlDeviceGetPciInfo_v2 + } + err = l.dl.Lookup("nvmlDeviceGetPciInfo_v3") + if err == nil { + nvmlDeviceGetPciInfo = nvmlDeviceGetPciInfo_v3 + } + err = l.dl.Lookup("nvmlDeviceGetCount_v2") + if err == nil { + nvmlDeviceGetCount = nvmlDeviceGetCount_v2 + } + err = l.dl.Lookup("nvmlDeviceGetHandleByIndex_v2") + if err == nil { + nvmlDeviceGetHandleByIndex = nvmlDeviceGetHandleByIndex_v2 + } + err = l.dl.Lookup("nvmlDeviceGetHandleByPciBusId_v2") + if err == nil { + nvmlDeviceGetHandleByPciBusId = nvmlDeviceGetHandleByPciBusId_v2 + } + err = l.dl.Lookup("nvmlDeviceGetNvLinkRemotePciInfo_v2") + if err == nil { + nvmlDeviceGetNvLinkRemotePciInfo = nvmlDeviceGetNvLinkRemotePciInfo_v2 + } + // Unable to overwrite nvmlDeviceRemoveGpu() because the v2 function takes + // a different set of parameters than the v1 function. + //err = l.dl.Lookup("nvmlDeviceRemoveGpu_v2") + //if err == nil { + // nvmlDeviceRemoveGpu = nvmlDeviceRemoveGpu_v2 + //} + err = l.dl.Lookup("nvmlDeviceGetGridLicensableFeatures_v2") + if err == nil { + nvmlDeviceGetGridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures_v2 + } + err = l.dl.Lookup("nvmlDeviceGetGridLicensableFeatures_v3") + if err == nil { + nvmlDeviceGetGridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures_v3 + } + err = l.dl.Lookup("nvmlDeviceGetGridLicensableFeatures_v4") + if err == nil { + nvmlDeviceGetGridLicensableFeatures = nvmlDeviceGetGridLicensableFeatures_v4 + } + err = l.dl.Lookup("nvmlEventSetWait_v2") + if err == nil { + nvmlEventSetWait = nvmlEventSetWait_v2 + } + err = l.dl.Lookup("nvmlDeviceGetAttributes_v2") + if err == nil { + nvmlDeviceGetAttributes = nvmlDeviceGetAttributes_v2 + } + err = l.dl.Lookup("nvmlComputeInstanceGetInfo_v2") + if err == nil { + nvmlComputeInstanceGetInfo = nvmlComputeInstanceGetInfo_v2 + } + err = l.dl.Lookup("nvmlDeviceGetComputeRunningProcesses_v2") + if err == nil { + deviceGetComputeRunningProcesses = deviceGetComputeRunningProcesses_v2 + } + err = l.dl.Lookup("nvmlDeviceGetComputeRunningProcesses_v3") + if err == nil { + deviceGetComputeRunningProcesses = deviceGetComputeRunningProcesses_v3 + } + err = l.dl.Lookup("nvmlDeviceGetGraphicsRunningProcesses_v2") + if err == nil { + deviceGetGraphicsRunningProcesses = deviceGetGraphicsRunningProcesses_v2 + } + err = l.dl.Lookup("nvmlDeviceGetGraphicsRunningProcesses_v3") + if err == nil { + deviceGetGraphicsRunningProcesses = deviceGetGraphicsRunningProcesses_v3 + } + err = l.dl.Lookup("nvmlDeviceGetMPSComputeRunningProcesses_v2") + if err == nil { + deviceGetMPSComputeRunningProcesses = deviceGetMPSComputeRunningProcesses_v2 + } + err = l.dl.Lookup("nvmlDeviceGetMPSComputeRunningProcesses_v3") + if err == nil { + deviceGetMPSComputeRunningProcesses = deviceGetMPSComputeRunningProcesses_v3 + } + err = l.dl.Lookup("nvmlDeviceGetGpuInstancePossiblePlacements_v2") + if err == nil { + nvmlDeviceGetGpuInstancePossiblePlacements = nvmlDeviceGetGpuInstancePossiblePlacements_v2 + } + err = l.dl.Lookup("nvmlVgpuInstanceGetLicenseInfo_v2") + if err == nil { + nvmlVgpuInstanceGetLicenseInfo = nvmlVgpuInstanceGetLicenseInfo_v2 + } + err = l.dl.Lookup("nvmlDeviceGetDriverModel_v2") + if err == nil { + nvmlDeviceGetDriverModel = nvmlDeviceGetDriverModel_v2 + } +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/computeinstance.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/computeinstance.go new file mode 100644 index 00000000..784fa114 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/computeinstance.go @@ -0,0 +1,105 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that ComputeInstance does implement nvml.ComputeInstance. +// If this is not the case, regenerate this file with moq. +var _ nvml.ComputeInstance = &ComputeInstance{} + +// ComputeInstance is a mock implementation of nvml.ComputeInstance. +// +// func TestSomethingThatUsesComputeInstance(t *testing.T) { +// +// // make and configure a mocked nvml.ComputeInstance +// mockedComputeInstance := &ComputeInstance{ +// DestroyFunc: func() nvml.Return { +// panic("mock out the Destroy method") +// }, +// GetInfoFunc: func() (nvml.ComputeInstanceInfo, nvml.Return) { +// panic("mock out the GetInfo method") +// }, +// } +// +// // use mockedComputeInstance in code that requires nvml.ComputeInstance +// // and then make assertions. +// +// } +type ComputeInstance struct { + // DestroyFunc mocks the Destroy method. + DestroyFunc func() nvml.Return + + // GetInfoFunc mocks the GetInfo method. + GetInfoFunc func() (nvml.ComputeInstanceInfo, nvml.Return) + + // calls tracks calls to the methods. + calls struct { + // Destroy holds details about calls to the Destroy method. + Destroy []struct { + } + // GetInfo holds details about calls to the GetInfo method. + GetInfo []struct { + } + } + lockDestroy sync.RWMutex + lockGetInfo sync.RWMutex +} + +// Destroy calls DestroyFunc. +func (mock *ComputeInstance) Destroy() nvml.Return { + if mock.DestroyFunc == nil { + panic("ComputeInstance.DestroyFunc: method is nil but ComputeInstance.Destroy was just called") + } + callInfo := struct { + }{} + mock.lockDestroy.Lock() + mock.calls.Destroy = append(mock.calls.Destroy, callInfo) + mock.lockDestroy.Unlock() + return mock.DestroyFunc() +} + +// DestroyCalls gets all the calls that were made to Destroy. +// Check the length with: +// +// len(mockedComputeInstance.DestroyCalls()) +func (mock *ComputeInstance) DestroyCalls() []struct { +} { + var calls []struct { + } + mock.lockDestroy.RLock() + calls = mock.calls.Destroy + mock.lockDestroy.RUnlock() + return calls +} + +// GetInfo calls GetInfoFunc. +func (mock *ComputeInstance) GetInfo() (nvml.ComputeInstanceInfo, nvml.Return) { + if mock.GetInfoFunc == nil { + panic("ComputeInstance.GetInfoFunc: method is nil but ComputeInstance.GetInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetInfo.Lock() + mock.calls.GetInfo = append(mock.calls.GetInfo, callInfo) + mock.lockGetInfo.Unlock() + return mock.GetInfoFunc() +} + +// GetInfoCalls gets all the calls that were made to GetInfo. +// Check the length with: +// +// len(mockedComputeInstance.GetInfoCalls()) +func (mock *ComputeInstance) GetInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetInfo.RLock() + calls = mock.calls.GetInfo + mock.lockGetInfo.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/device.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/device.go new file mode 100644 index 00000000..26397284 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/device.go @@ -0,0 +1,10524 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that Device does implement nvml.Device. +// If this is not the case, regenerate this file with moq. +var _ nvml.Device = &Device{} + +// Device is a mock implementation of nvml.Device. +// +// func TestSomethingThatUsesDevice(t *testing.T) { +// +// // make and configure a mocked nvml.Device +// mockedDevice := &Device{ +// ClearAccountingPidsFunc: func() nvml.Return { +// panic("mock out the ClearAccountingPids method") +// }, +// ClearCpuAffinityFunc: func() nvml.Return { +// panic("mock out the ClearCpuAffinity method") +// }, +// ClearEccErrorCountsFunc: func(eccCounterType nvml.EccCounterType) nvml.Return { +// panic("mock out the ClearEccErrorCounts method") +// }, +// ClearFieldValuesFunc: func(fieldValues []nvml.FieldValue) nvml.Return { +// panic("mock out the ClearFieldValues method") +// }, +// CreateGpuInstanceFunc: func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the CreateGpuInstance method") +// }, +// CreateGpuInstanceWithPlacementFunc: func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the CreateGpuInstanceWithPlacement method") +// }, +// FreezeNvLinkUtilizationCounterFunc: func(n1 int, n2 int, enableState nvml.EnableState) nvml.Return { +// panic("mock out the FreezeNvLinkUtilizationCounter method") +// }, +// GetAPIRestrictionFunc: func(restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) { +// panic("mock out the GetAPIRestriction method") +// }, +// GetAccountingBufferSizeFunc: func() (int, nvml.Return) { +// panic("mock out the GetAccountingBufferSize method") +// }, +// GetAccountingModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetAccountingMode method") +// }, +// GetAccountingPidsFunc: func() ([]int, nvml.Return) { +// panic("mock out the GetAccountingPids method") +// }, +// GetAccountingStatsFunc: func(v uint32) (nvml.AccountingStats, nvml.Return) { +// panic("mock out the GetAccountingStats method") +// }, +// GetActiveVgpusFunc: func() ([]nvml.VgpuInstance, nvml.Return) { +// panic("mock out the GetActiveVgpus method") +// }, +// GetAdaptiveClockInfoStatusFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetAdaptiveClockInfoStatus method") +// }, +// GetAddressingModeFunc: func() (nvml.DeviceAddressingMode, nvml.Return) { +// panic("mock out the GetAddressingMode method") +// }, +// GetApplicationsClockFunc: func(clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the GetApplicationsClock method") +// }, +// GetArchitectureFunc: func() (nvml.DeviceArchitecture, nvml.Return) { +// panic("mock out the GetArchitecture method") +// }, +// GetAttributesFunc: func() (nvml.DeviceAttributes, nvml.Return) { +// panic("mock out the GetAttributes method") +// }, +// GetAutoBoostedClocksEnabledFunc: func() (nvml.EnableState, nvml.EnableState, nvml.Return) { +// panic("mock out the GetAutoBoostedClocksEnabled method") +// }, +// GetBAR1MemoryInfoFunc: func() (nvml.BAR1Memory, nvml.Return) { +// panic("mock out the GetBAR1MemoryInfo method") +// }, +// GetBoardIdFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetBoardId method") +// }, +// GetBoardPartNumberFunc: func() (string, nvml.Return) { +// panic("mock out the GetBoardPartNumber method") +// }, +// GetBrandFunc: func() (nvml.BrandType, nvml.Return) { +// panic("mock out the GetBrand method") +// }, +// GetBridgeChipInfoFunc: func() (nvml.BridgeChipHierarchy, nvml.Return) { +// panic("mock out the GetBridgeChipInfo method") +// }, +// GetBusTypeFunc: func() (nvml.BusType, nvml.Return) { +// panic("mock out the GetBusType method") +// }, +// GetC2cModeInfoVFunc: func() nvml.C2cModeInfoHandler { +// panic("mock out the GetC2cModeInfoV method") +// }, +// GetCapabilitiesFunc: func() (nvml.DeviceCapabilities, nvml.Return) { +// panic("mock out the GetCapabilities method") +// }, +// GetClkMonStatusFunc: func() (nvml.ClkMonStatus, nvml.Return) { +// panic("mock out the GetClkMonStatus method") +// }, +// GetClockFunc: func(clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) { +// panic("mock out the GetClock method") +// }, +// GetClockInfoFunc: func(clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the GetClockInfo method") +// }, +// GetClockOffsetsFunc: func() (nvml.ClockOffset, nvml.Return) { +// panic("mock out the GetClockOffsets method") +// }, +// GetComputeInstanceIdFunc: func() (int, nvml.Return) { +// panic("mock out the GetComputeInstanceId method") +// }, +// GetComputeModeFunc: func() (nvml.ComputeMode, nvml.Return) { +// panic("mock out the GetComputeMode method") +// }, +// GetComputeRunningProcessesFunc: func() ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the GetComputeRunningProcesses method") +// }, +// GetConfComputeGpuAttestationReportFunc: func(confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return { +// panic("mock out the GetConfComputeGpuAttestationReport method") +// }, +// GetConfComputeGpuCertificateFunc: func() (nvml.ConfComputeGpuCertificate, nvml.Return) { +// panic("mock out the GetConfComputeGpuCertificate method") +// }, +// GetConfComputeMemSizeInfoFunc: func() (nvml.ConfComputeMemSizeInfo, nvml.Return) { +// panic("mock out the GetConfComputeMemSizeInfo method") +// }, +// GetConfComputeProtectedMemoryUsageFunc: func() (nvml.Memory, nvml.Return) { +// panic("mock out the GetConfComputeProtectedMemoryUsage method") +// }, +// GetCoolerInfoFunc: func() (nvml.CoolerInfo, nvml.Return) { +// panic("mock out the GetCoolerInfo method") +// }, +// GetCpuAffinityFunc: func(n int) ([]uint, nvml.Return) { +// panic("mock out the GetCpuAffinity method") +// }, +// GetCpuAffinityWithinScopeFunc: func(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { +// panic("mock out the GetCpuAffinityWithinScope method") +// }, +// GetCreatableVgpusFunc: func() ([]nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the GetCreatableVgpus method") +// }, +// GetCudaComputeCapabilityFunc: func() (int, int, nvml.Return) { +// panic("mock out the GetCudaComputeCapability method") +// }, +// GetCurrPcieLinkGenerationFunc: func() (int, nvml.Return) { +// panic("mock out the GetCurrPcieLinkGeneration method") +// }, +// GetCurrPcieLinkWidthFunc: func() (int, nvml.Return) { +// panic("mock out the GetCurrPcieLinkWidth method") +// }, +// GetCurrentClockFreqsFunc: func() (nvml.DeviceCurrentClockFreqs, nvml.Return) { +// panic("mock out the GetCurrentClockFreqs method") +// }, +// GetCurrentClocksEventReasonsFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetCurrentClocksEventReasons method") +// }, +// GetCurrentClocksThrottleReasonsFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetCurrentClocksThrottleReasons method") +// }, +// GetDecoderUtilizationFunc: func() (uint32, uint32, nvml.Return) { +// panic("mock out the GetDecoderUtilization method") +// }, +// GetDefaultApplicationsClockFunc: func(clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the GetDefaultApplicationsClock method") +// }, +// GetDefaultEccModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetDefaultEccMode method") +// }, +// GetDetailedEccErrorsFunc: func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) { +// panic("mock out the GetDetailedEccErrors method") +// }, +// GetDeviceHandleFromMigDeviceHandleFunc: func() (nvml.Device, nvml.Return) { +// panic("mock out the GetDeviceHandleFromMigDeviceHandle method") +// }, +// GetDisplayActiveFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetDisplayActive method") +// }, +// GetDisplayModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetDisplayMode method") +// }, +// GetDramEncryptionModeFunc: func() (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) { +// panic("mock out the GetDramEncryptionMode method") +// }, +// GetDriverModelFunc: func() (nvml.DriverModel, nvml.DriverModel, nvml.Return) { +// panic("mock out the GetDriverModel method") +// }, +// GetDriverModel_v2Func: func() (nvml.DriverModel, nvml.DriverModel, nvml.Return) { +// panic("mock out the GetDriverModel_v2 method") +// }, +// GetDynamicPstatesInfoFunc: func() (nvml.GpuDynamicPstatesInfo, nvml.Return) { +// panic("mock out the GetDynamicPstatesInfo method") +// }, +// GetEccModeFunc: func() (nvml.EnableState, nvml.EnableState, nvml.Return) { +// panic("mock out the GetEccMode method") +// }, +// GetEncoderCapacityFunc: func(encoderType nvml.EncoderType) (int, nvml.Return) { +// panic("mock out the GetEncoderCapacity method") +// }, +// GetEncoderSessionsFunc: func() ([]nvml.EncoderSessionInfo, nvml.Return) { +// panic("mock out the GetEncoderSessions method") +// }, +// GetEncoderStatsFunc: func() (int, uint32, uint32, nvml.Return) { +// panic("mock out the GetEncoderStats method") +// }, +// GetEncoderUtilizationFunc: func() (uint32, uint32, nvml.Return) { +// panic("mock out the GetEncoderUtilization method") +// }, +// GetEnforcedPowerLimitFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetEnforcedPowerLimit method") +// }, +// GetFBCSessionsFunc: func() ([]nvml.FBCSessionInfo, nvml.Return) { +// panic("mock out the GetFBCSessions method") +// }, +// GetFBCStatsFunc: func() (nvml.FBCStats, nvml.Return) { +// panic("mock out the GetFBCStats method") +// }, +// GetFanControlPolicy_v2Func: func(n int) (nvml.FanControlPolicy, nvml.Return) { +// panic("mock out the GetFanControlPolicy_v2 method") +// }, +// GetFanSpeedFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetFanSpeed method") +// }, +// GetFanSpeedRPMFunc: func() (nvml.FanSpeedInfo, nvml.Return) { +// panic("mock out the GetFanSpeedRPM method") +// }, +// GetFanSpeed_v2Func: func(n int) (uint32, nvml.Return) { +// panic("mock out the GetFanSpeed_v2 method") +// }, +// GetFieldValuesFunc: func(fieldValues []nvml.FieldValue) nvml.Return { +// panic("mock out the GetFieldValues method") +// }, +// GetGpcClkMinMaxVfOffsetFunc: func() (int, int, nvml.Return) { +// panic("mock out the GetGpcClkMinMaxVfOffset method") +// }, +// GetGpcClkVfOffsetFunc: func() (int, nvml.Return) { +// panic("mock out the GetGpcClkVfOffset method") +// }, +// GetGpuFabricInfoFunc: func() (nvml.GpuFabricInfo, nvml.Return) { +// panic("mock out the GetGpuFabricInfo method") +// }, +// GetGpuFabricInfoVFunc: func() nvml.GpuFabricInfoHandler { +// panic("mock out the GetGpuFabricInfoV method") +// }, +// GetGpuInstanceByIdFunc: func(n int) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the GetGpuInstanceById method") +// }, +// GetGpuInstanceIdFunc: func() (int, nvml.Return) { +// panic("mock out the GetGpuInstanceId method") +// }, +// GetGpuInstancePossiblePlacementsFunc: func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) { +// panic("mock out the GetGpuInstancePossiblePlacements method") +// }, +// GetGpuInstanceProfileInfoFunc: func(n int) (nvml.GpuInstanceProfileInfo, nvml.Return) { +// panic("mock out the GetGpuInstanceProfileInfo method") +// }, +// GetGpuInstanceProfileInfoByIdVFunc: func(n int) nvml.GpuInstanceProfileInfoByIdHandler { +// panic("mock out the GetGpuInstanceProfileInfoByIdV method") +// }, +// GetGpuInstanceProfileInfoVFunc: func(n int) nvml.GpuInstanceProfileInfoHandler { +// panic("mock out the GetGpuInstanceProfileInfoV method") +// }, +// GetGpuInstanceRemainingCapacityFunc: func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) { +// panic("mock out the GetGpuInstanceRemainingCapacity method") +// }, +// GetGpuInstancesFunc: func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { +// panic("mock out the GetGpuInstances method") +// }, +// GetGpuMaxPcieLinkGenerationFunc: func() (int, nvml.Return) { +// panic("mock out the GetGpuMaxPcieLinkGeneration method") +// }, +// GetGpuOperationModeFunc: func() (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) { +// panic("mock out the GetGpuOperationMode method") +// }, +// GetGraphicsRunningProcessesFunc: func() ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the GetGraphicsRunningProcesses method") +// }, +// GetGridLicensableFeaturesFunc: func() (nvml.GridLicensableFeatures, nvml.Return) { +// panic("mock out the GetGridLicensableFeatures method") +// }, +// GetGspFirmwareModeFunc: func() (bool, bool, nvml.Return) { +// panic("mock out the GetGspFirmwareMode method") +// }, +// GetGspFirmwareVersionFunc: func() (string, nvml.Return) { +// panic("mock out the GetGspFirmwareVersion method") +// }, +// GetHostVgpuModeFunc: func() (nvml.HostVgpuMode, nvml.Return) { +// panic("mock out the GetHostVgpuMode method") +// }, +// GetIndexFunc: func() (int, nvml.Return) { +// panic("mock out the GetIndex method") +// }, +// GetInforomConfigurationChecksumFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetInforomConfigurationChecksum method") +// }, +// GetInforomImageVersionFunc: func() (string, nvml.Return) { +// panic("mock out the GetInforomImageVersion method") +// }, +// GetInforomVersionFunc: func(inforomObject nvml.InforomObject) (string, nvml.Return) { +// panic("mock out the GetInforomVersion method") +// }, +// GetIrqNumFunc: func() (int, nvml.Return) { +// panic("mock out the GetIrqNum method") +// }, +// GetJpgUtilizationFunc: func() (uint32, uint32, nvml.Return) { +// panic("mock out the GetJpgUtilization method") +// }, +// GetLastBBXFlushTimeFunc: func() (uint64, uint, nvml.Return) { +// panic("mock out the GetLastBBXFlushTime method") +// }, +// GetMPSComputeRunningProcessesFunc: func() ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the GetMPSComputeRunningProcesses method") +// }, +// GetMarginTemperatureFunc: func() (nvml.MarginTemperature, nvml.Return) { +// panic("mock out the GetMarginTemperature method") +// }, +// GetMaxClockInfoFunc: func(clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the GetMaxClockInfo method") +// }, +// GetMaxCustomerBoostClockFunc: func(clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the GetMaxCustomerBoostClock method") +// }, +// GetMaxMigDeviceCountFunc: func() (int, nvml.Return) { +// panic("mock out the GetMaxMigDeviceCount method") +// }, +// GetMaxPcieLinkGenerationFunc: func() (int, nvml.Return) { +// panic("mock out the GetMaxPcieLinkGeneration method") +// }, +// GetMaxPcieLinkWidthFunc: func() (int, nvml.Return) { +// panic("mock out the GetMaxPcieLinkWidth method") +// }, +// GetMemClkMinMaxVfOffsetFunc: func() (int, int, nvml.Return) { +// panic("mock out the GetMemClkMinMaxVfOffset method") +// }, +// GetMemClkVfOffsetFunc: func() (int, nvml.Return) { +// panic("mock out the GetMemClkVfOffset method") +// }, +// GetMemoryAffinityFunc: func(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { +// panic("mock out the GetMemoryAffinity method") +// }, +// GetMemoryBusWidthFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetMemoryBusWidth method") +// }, +// GetMemoryErrorCounterFunc: func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) { +// panic("mock out the GetMemoryErrorCounter method") +// }, +// GetMemoryInfoFunc: func() (nvml.Memory, nvml.Return) { +// panic("mock out the GetMemoryInfo method") +// }, +// GetMemoryInfo_v2Func: func() (nvml.Memory_v2, nvml.Return) { +// panic("mock out the GetMemoryInfo_v2 method") +// }, +// GetMigDeviceHandleByIndexFunc: func(n int) (nvml.Device, nvml.Return) { +// panic("mock out the GetMigDeviceHandleByIndex method") +// }, +// GetMigModeFunc: func() (int, int, nvml.Return) { +// panic("mock out the GetMigMode method") +// }, +// GetMinMaxClockOfPStateFunc: func(clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) { +// panic("mock out the GetMinMaxClockOfPState method") +// }, +// GetMinMaxFanSpeedFunc: func() (int, int, nvml.Return) { +// panic("mock out the GetMinMaxFanSpeed method") +// }, +// GetMinorNumberFunc: func() (int, nvml.Return) { +// panic("mock out the GetMinorNumber method") +// }, +// GetModuleIdFunc: func() (int, nvml.Return) { +// panic("mock out the GetModuleId method") +// }, +// GetMultiGpuBoardFunc: func() (int, nvml.Return) { +// panic("mock out the GetMultiGpuBoard method") +// }, +// GetNameFunc: func() (string, nvml.Return) { +// panic("mock out the GetName method") +// }, +// GetNumFansFunc: func() (int, nvml.Return) { +// panic("mock out the GetNumFans method") +// }, +// GetNumGpuCoresFunc: func() (int, nvml.Return) { +// panic("mock out the GetNumGpuCores method") +// }, +// GetNumaNodeIdFunc: func() (int, nvml.Return) { +// panic("mock out the GetNumaNodeId method") +// }, +// GetNvLinkCapabilityFunc: func(n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) { +// panic("mock out the GetNvLinkCapability method") +// }, +// GetNvLinkErrorCounterFunc: func(n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) { +// panic("mock out the GetNvLinkErrorCounter method") +// }, +// GetNvLinkInfoFunc: func() nvml.NvLinkInfoHandler { +// panic("mock out the GetNvLinkInfo method") +// }, +// GetNvLinkRemoteDeviceTypeFunc: func(n int) (nvml.IntNvLinkDeviceType, nvml.Return) { +// panic("mock out the GetNvLinkRemoteDeviceType method") +// }, +// GetNvLinkRemotePciInfoFunc: func(n int) (nvml.PciInfo, nvml.Return) { +// panic("mock out the GetNvLinkRemotePciInfo method") +// }, +// GetNvLinkStateFunc: func(n int) (nvml.EnableState, nvml.Return) { +// panic("mock out the GetNvLinkState method") +// }, +// GetNvLinkUtilizationControlFunc: func(n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) { +// panic("mock out the GetNvLinkUtilizationControl method") +// }, +// GetNvLinkUtilizationCounterFunc: func(n1 int, n2 int) (uint64, uint64, nvml.Return) { +// panic("mock out the GetNvLinkUtilizationCounter method") +// }, +// GetNvLinkVersionFunc: func(n int) (uint32, nvml.Return) { +// panic("mock out the GetNvLinkVersion method") +// }, +// GetNvlinkBwModeFunc: func() (nvml.NvlinkGetBwMode, nvml.Return) { +// panic("mock out the GetNvlinkBwMode method") +// }, +// GetNvlinkSupportedBwModesFunc: func() (nvml.NvlinkSupportedBwModes, nvml.Return) { +// panic("mock out the GetNvlinkSupportedBwModes method") +// }, +// GetOfaUtilizationFunc: func() (uint32, uint32, nvml.Return) { +// panic("mock out the GetOfaUtilization method") +// }, +// GetP2PStatusFunc: func(device nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) { +// panic("mock out the GetP2PStatus method") +// }, +// GetPciInfoFunc: func() (nvml.PciInfo, nvml.Return) { +// panic("mock out the GetPciInfo method") +// }, +// GetPciInfoExtFunc: func() (nvml.PciInfoExt, nvml.Return) { +// panic("mock out the GetPciInfoExt method") +// }, +// GetPcieLinkMaxSpeedFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetPcieLinkMaxSpeed method") +// }, +// GetPcieReplayCounterFunc: func() (int, nvml.Return) { +// panic("mock out the GetPcieReplayCounter method") +// }, +// GetPcieSpeedFunc: func() (int, nvml.Return) { +// panic("mock out the GetPcieSpeed method") +// }, +// GetPcieThroughputFunc: func(pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) { +// panic("mock out the GetPcieThroughput method") +// }, +// GetPdiFunc: func() (nvml.Pdi, nvml.Return) { +// panic("mock out the GetPdi method") +// }, +// GetPerformanceModesFunc: func() (nvml.DevicePerfModes, nvml.Return) { +// panic("mock out the GetPerformanceModes method") +// }, +// GetPerformanceStateFunc: func() (nvml.Pstates, nvml.Return) { +// panic("mock out the GetPerformanceState method") +// }, +// GetPersistenceModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetPersistenceMode method") +// }, +// GetPgpuMetadataStringFunc: func() (string, nvml.Return) { +// panic("mock out the GetPgpuMetadataString method") +// }, +// GetPlatformInfoFunc: func() (nvml.PlatformInfo, nvml.Return) { +// panic("mock out the GetPlatformInfo method") +// }, +// GetPowerManagementDefaultLimitFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetPowerManagementDefaultLimit method") +// }, +// GetPowerManagementLimitFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetPowerManagementLimit method") +// }, +// GetPowerManagementLimitConstraintsFunc: func() (uint32, uint32, nvml.Return) { +// panic("mock out the GetPowerManagementLimitConstraints method") +// }, +// GetPowerManagementModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetPowerManagementMode method") +// }, +// GetPowerMizerMode_v1Func: func() (nvml.DevicePowerMizerModes_v1, nvml.Return) { +// panic("mock out the GetPowerMizerMode_v1 method") +// }, +// GetPowerSourceFunc: func() (nvml.PowerSource, nvml.Return) { +// panic("mock out the GetPowerSource method") +// }, +// GetPowerStateFunc: func() (nvml.Pstates, nvml.Return) { +// panic("mock out the GetPowerState method") +// }, +// GetPowerUsageFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetPowerUsage method") +// }, +// GetProcessUtilizationFunc: func(v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) { +// panic("mock out the GetProcessUtilization method") +// }, +// GetProcessesUtilizationInfoFunc: func() (nvml.ProcessesUtilizationInfo, nvml.Return) { +// panic("mock out the GetProcessesUtilizationInfo method") +// }, +// GetRemappedRowsFunc: func() (int, int, bool, bool, nvml.Return) { +// panic("mock out the GetRemappedRows method") +// }, +// GetRepairStatusFunc: func() (nvml.RepairStatus, nvml.Return) { +// panic("mock out the GetRepairStatus method") +// }, +// GetRetiredPagesFunc: func(pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) { +// panic("mock out the GetRetiredPages method") +// }, +// GetRetiredPagesPendingStatusFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetRetiredPagesPendingStatus method") +// }, +// GetRetiredPages_v2Func: func(pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) { +// panic("mock out the GetRetiredPages_v2 method") +// }, +// GetRowRemapperHistogramFunc: func() (nvml.RowRemapperHistogramValues, nvml.Return) { +// panic("mock out the GetRowRemapperHistogram method") +// }, +// GetRunningProcessDetailListFunc: func() (nvml.ProcessDetailList, nvml.Return) { +// panic("mock out the GetRunningProcessDetailList method") +// }, +// GetSamplesFunc: func(samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) { +// panic("mock out the GetSamples method") +// }, +// GetSerialFunc: func() (string, nvml.Return) { +// panic("mock out the GetSerial method") +// }, +// GetSramEccErrorStatusFunc: func() (nvml.EccSramErrorStatus, nvml.Return) { +// panic("mock out the GetSramEccErrorStatus method") +// }, +// GetSramUniqueUncorrectedEccErrorCountsFunc: func(eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return { +// panic("mock out the GetSramUniqueUncorrectedEccErrorCounts method") +// }, +// GetSupportedClocksEventReasonsFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetSupportedClocksEventReasons method") +// }, +// GetSupportedClocksThrottleReasonsFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetSupportedClocksThrottleReasons method") +// }, +// GetSupportedEventTypesFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetSupportedEventTypes method") +// }, +// GetSupportedGraphicsClocksFunc: func(n int) (int, uint32, nvml.Return) { +// panic("mock out the GetSupportedGraphicsClocks method") +// }, +// GetSupportedMemoryClocksFunc: func() (int, uint32, nvml.Return) { +// panic("mock out the GetSupportedMemoryClocks method") +// }, +// GetSupportedPerformanceStatesFunc: func() ([]nvml.Pstates, nvml.Return) { +// panic("mock out the GetSupportedPerformanceStates method") +// }, +// GetSupportedVgpusFunc: func() ([]nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the GetSupportedVgpus method") +// }, +// GetTargetFanSpeedFunc: func(n int) (int, nvml.Return) { +// panic("mock out the GetTargetFanSpeed method") +// }, +// GetTemperatureFunc: func(temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) { +// panic("mock out the GetTemperature method") +// }, +// GetTemperatureThresholdFunc: func(temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) { +// panic("mock out the GetTemperatureThreshold method") +// }, +// GetTemperatureVFunc: func() nvml.TemperatureHandler { +// panic("mock out the GetTemperatureV method") +// }, +// GetThermalSettingsFunc: func(v uint32) (nvml.GpuThermalSettings, nvml.Return) { +// panic("mock out the GetThermalSettings method") +// }, +// GetTopologyCommonAncestorFunc: func(device nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) { +// panic("mock out the GetTopologyCommonAncestor method") +// }, +// GetTopologyNearestGpusFunc: func(gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) { +// panic("mock out the GetTopologyNearestGpus method") +// }, +// GetTotalEccErrorsFunc: func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) { +// panic("mock out the GetTotalEccErrors method") +// }, +// GetTotalEnergyConsumptionFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetTotalEnergyConsumption method") +// }, +// GetUUIDFunc: func() (string, nvml.Return) { +// panic("mock out the GetUUID method") +// }, +// GetUtilizationRatesFunc: func() (nvml.Utilization, nvml.Return) { +// panic("mock out the GetUtilizationRates method") +// }, +// GetVbiosVersionFunc: func() (string, nvml.Return) { +// panic("mock out the GetVbiosVersion method") +// }, +// GetVgpuCapabilitiesFunc: func(deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) { +// panic("mock out the GetVgpuCapabilities method") +// }, +// GetVgpuHeterogeneousModeFunc: func() (nvml.VgpuHeterogeneousMode, nvml.Return) { +// panic("mock out the GetVgpuHeterogeneousMode method") +// }, +// GetVgpuInstancesUtilizationInfoFunc: func() (nvml.VgpuInstancesUtilizationInfo, nvml.Return) { +// panic("mock out the GetVgpuInstancesUtilizationInfo method") +// }, +// GetVgpuMetadataFunc: func() (nvml.VgpuPgpuMetadata, nvml.Return) { +// panic("mock out the GetVgpuMetadata method") +// }, +// GetVgpuProcessUtilizationFunc: func(v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) { +// panic("mock out the GetVgpuProcessUtilization method") +// }, +// GetVgpuProcessesUtilizationInfoFunc: func() (nvml.VgpuProcessesUtilizationInfo, nvml.Return) { +// panic("mock out the GetVgpuProcessesUtilizationInfo method") +// }, +// GetVgpuSchedulerCapabilitiesFunc: func() (nvml.VgpuSchedulerCapabilities, nvml.Return) { +// panic("mock out the GetVgpuSchedulerCapabilities method") +// }, +// GetVgpuSchedulerLogFunc: func() (nvml.VgpuSchedulerLog, nvml.Return) { +// panic("mock out the GetVgpuSchedulerLog method") +// }, +// GetVgpuSchedulerStateFunc: func() (nvml.VgpuSchedulerGetState, nvml.Return) { +// panic("mock out the GetVgpuSchedulerState method") +// }, +// GetVgpuTypeCreatablePlacementsFunc: func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the GetVgpuTypeCreatablePlacements method") +// }, +// GetVgpuTypeSupportedPlacementsFunc: func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the GetVgpuTypeSupportedPlacements method") +// }, +// GetVgpuUtilizationFunc: func(v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) { +// panic("mock out the GetVgpuUtilization method") +// }, +// GetViolationStatusFunc: func(perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) { +// panic("mock out the GetViolationStatus method") +// }, +// GetVirtualizationModeFunc: func() (nvml.GpuVirtualizationMode, nvml.Return) { +// panic("mock out the GetVirtualizationMode method") +// }, +// GpmMigSampleGetFunc: func(n int, gpmSample nvml.GpmSample) nvml.Return { +// panic("mock out the GpmMigSampleGet method") +// }, +// GpmQueryDeviceSupportFunc: func() (nvml.GpmSupport, nvml.Return) { +// panic("mock out the GpmQueryDeviceSupport method") +// }, +// GpmQueryDeviceSupportVFunc: func() nvml.GpmSupportV { +// panic("mock out the GpmQueryDeviceSupportV method") +// }, +// GpmQueryIfStreamingEnabledFunc: func() (uint32, nvml.Return) { +// panic("mock out the GpmQueryIfStreamingEnabled method") +// }, +// GpmSampleGetFunc: func(gpmSample nvml.GpmSample) nvml.Return { +// panic("mock out the GpmSampleGet method") +// }, +// GpmSetStreamingEnabledFunc: func(v uint32) nvml.Return { +// panic("mock out the GpmSetStreamingEnabled method") +// }, +// IsMigDeviceHandleFunc: func() (bool, nvml.Return) { +// panic("mock out the IsMigDeviceHandle method") +// }, +// OnSameBoardFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the OnSameBoard method") +// }, +// PowerSmoothingActivatePresetProfileFunc: func(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { +// panic("mock out the PowerSmoothingActivatePresetProfile method") +// }, +// PowerSmoothingSetStateFunc: func(powerSmoothingState *nvml.PowerSmoothingState) nvml.Return { +// panic("mock out the PowerSmoothingSetState method") +// }, +// PowerSmoothingUpdatePresetProfileParamFunc: func(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { +// panic("mock out the PowerSmoothingUpdatePresetProfileParam method") +// }, +// ReadWritePRM_v1Func: func(pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return { +// panic("mock out the ReadWritePRM_v1 method") +// }, +// RegisterEventsFunc: func(v uint64, eventSet nvml.EventSet) nvml.Return { +// panic("mock out the RegisterEvents method") +// }, +// ResetApplicationsClocksFunc: func() nvml.Return { +// panic("mock out the ResetApplicationsClocks method") +// }, +// ResetGpuLockedClocksFunc: func() nvml.Return { +// panic("mock out the ResetGpuLockedClocks method") +// }, +// ResetMemoryLockedClocksFunc: func() nvml.Return { +// panic("mock out the ResetMemoryLockedClocks method") +// }, +// ResetNvLinkErrorCountersFunc: func(n int) nvml.Return { +// panic("mock out the ResetNvLinkErrorCounters method") +// }, +// ResetNvLinkUtilizationCounterFunc: func(n1 int, n2 int) nvml.Return { +// panic("mock out the ResetNvLinkUtilizationCounter method") +// }, +// SetAPIRestrictionFunc: func(restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetAPIRestriction method") +// }, +// SetAccountingModeFunc: func(enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetAccountingMode method") +// }, +// SetApplicationsClocksFunc: func(v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the SetApplicationsClocks method") +// }, +// SetAutoBoostedClocksEnabledFunc: func(enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetAutoBoostedClocksEnabled method") +// }, +// SetClockOffsetsFunc: func(clockOffset nvml.ClockOffset) nvml.Return { +// panic("mock out the SetClockOffsets method") +// }, +// SetComputeModeFunc: func(computeMode nvml.ComputeMode) nvml.Return { +// panic("mock out the SetComputeMode method") +// }, +// SetConfComputeUnprotectedMemSizeFunc: func(v uint64) nvml.Return { +// panic("mock out the SetConfComputeUnprotectedMemSize method") +// }, +// SetCpuAffinityFunc: func() nvml.Return { +// panic("mock out the SetCpuAffinity method") +// }, +// SetDefaultAutoBoostedClocksEnabledFunc: func(enableState nvml.EnableState, v uint32) nvml.Return { +// panic("mock out the SetDefaultAutoBoostedClocksEnabled method") +// }, +// SetDefaultFanSpeed_v2Func: func(n int) nvml.Return { +// panic("mock out the SetDefaultFanSpeed_v2 method") +// }, +// SetDramEncryptionModeFunc: func(dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return { +// panic("mock out the SetDramEncryptionMode method") +// }, +// SetDriverModelFunc: func(driverModel nvml.DriverModel, v uint32) nvml.Return { +// panic("mock out the SetDriverModel method") +// }, +// SetEccModeFunc: func(enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetEccMode method") +// }, +// SetFanControlPolicyFunc: func(n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return { +// panic("mock out the SetFanControlPolicy method") +// }, +// SetFanSpeed_v2Func: func(n1 int, n2 int) nvml.Return { +// panic("mock out the SetFanSpeed_v2 method") +// }, +// SetGpcClkVfOffsetFunc: func(n int) nvml.Return { +// panic("mock out the SetGpcClkVfOffset method") +// }, +// SetGpuLockedClocksFunc: func(v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the SetGpuLockedClocks method") +// }, +// SetGpuOperationModeFunc: func(gpuOperationMode nvml.GpuOperationMode) nvml.Return { +// panic("mock out the SetGpuOperationMode method") +// }, +// SetMemClkVfOffsetFunc: func(n int) nvml.Return { +// panic("mock out the SetMemClkVfOffset method") +// }, +// SetMemoryLockedClocksFunc: func(v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the SetMemoryLockedClocks method") +// }, +// SetMigModeFunc: func(n int) (nvml.Return, nvml.Return) { +// panic("mock out the SetMigMode method") +// }, +// SetNvLinkDeviceLowPowerThresholdFunc: func(nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return { +// panic("mock out the SetNvLinkDeviceLowPowerThreshold method") +// }, +// SetNvLinkUtilizationControlFunc: func(n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return { +// panic("mock out the SetNvLinkUtilizationControl method") +// }, +// SetNvlinkBwModeFunc: func(nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return { +// panic("mock out the SetNvlinkBwMode method") +// }, +// SetPersistenceModeFunc: func(enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetPersistenceMode method") +// }, +// SetPowerManagementLimitFunc: func(v uint32) nvml.Return { +// panic("mock out the SetPowerManagementLimit method") +// }, +// SetPowerManagementLimit_v2Func: func(powerValue_v2 *nvml.PowerValue_v2) nvml.Return { +// panic("mock out the SetPowerManagementLimit_v2 method") +// }, +// SetTemperatureThresholdFunc: func(temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return { +// panic("mock out the SetTemperatureThreshold method") +// }, +// SetVgpuCapabilitiesFunc: func(deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return { +// panic("mock out the SetVgpuCapabilities method") +// }, +// SetVgpuHeterogeneousModeFunc: func(vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return { +// panic("mock out the SetVgpuHeterogeneousMode method") +// }, +// SetVgpuSchedulerStateFunc: func(vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return { +// panic("mock out the SetVgpuSchedulerState method") +// }, +// SetVirtualizationModeFunc: func(gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return { +// panic("mock out the SetVirtualizationMode method") +// }, +// ValidateInforomFunc: func() nvml.Return { +// panic("mock out the ValidateInforom method") +// }, +// VgpuTypeGetMaxInstancesFunc: func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { +// panic("mock out the VgpuTypeGetMaxInstances method") +// }, +// WorkloadPowerProfileClearRequestedProfilesFunc: func(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { +// panic("mock out the WorkloadPowerProfileClearRequestedProfiles method") +// }, +// WorkloadPowerProfileGetCurrentProfilesFunc: func() (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) { +// panic("mock out the WorkloadPowerProfileGetCurrentProfiles method") +// }, +// WorkloadPowerProfileGetProfilesInfoFunc: func() (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) { +// panic("mock out the WorkloadPowerProfileGetProfilesInfo method") +// }, +// WorkloadPowerProfileSetRequestedProfilesFunc: func(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { +// panic("mock out the WorkloadPowerProfileSetRequestedProfiles method") +// }, +// } +// +// // use mockedDevice in code that requires nvml.Device +// // and then make assertions. +// +// } +type Device struct { + // ClearAccountingPidsFunc mocks the ClearAccountingPids method. + ClearAccountingPidsFunc func() nvml.Return + + // ClearCpuAffinityFunc mocks the ClearCpuAffinity method. + ClearCpuAffinityFunc func() nvml.Return + + // ClearEccErrorCountsFunc mocks the ClearEccErrorCounts method. + ClearEccErrorCountsFunc func(eccCounterType nvml.EccCounterType) nvml.Return + + // ClearFieldValuesFunc mocks the ClearFieldValues method. + ClearFieldValuesFunc func(fieldValues []nvml.FieldValue) nvml.Return + + // CreateGpuInstanceFunc mocks the CreateGpuInstance method. + CreateGpuInstanceFunc func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) + + // CreateGpuInstanceWithPlacementFunc mocks the CreateGpuInstanceWithPlacement method. + CreateGpuInstanceWithPlacementFunc func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) + + // FreezeNvLinkUtilizationCounterFunc mocks the FreezeNvLinkUtilizationCounter method. + FreezeNvLinkUtilizationCounterFunc func(n1 int, n2 int, enableState nvml.EnableState) nvml.Return + + // GetAPIRestrictionFunc mocks the GetAPIRestriction method. + GetAPIRestrictionFunc func(restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) + + // GetAccountingBufferSizeFunc mocks the GetAccountingBufferSize method. + GetAccountingBufferSizeFunc func() (int, nvml.Return) + + // GetAccountingModeFunc mocks the GetAccountingMode method. + GetAccountingModeFunc func() (nvml.EnableState, nvml.Return) + + // GetAccountingPidsFunc mocks the GetAccountingPids method. + GetAccountingPidsFunc func() ([]int, nvml.Return) + + // GetAccountingStatsFunc mocks the GetAccountingStats method. + GetAccountingStatsFunc func(v uint32) (nvml.AccountingStats, nvml.Return) + + // GetActiveVgpusFunc mocks the GetActiveVgpus method. + GetActiveVgpusFunc func() ([]nvml.VgpuInstance, nvml.Return) + + // GetAdaptiveClockInfoStatusFunc mocks the GetAdaptiveClockInfoStatus method. + GetAdaptiveClockInfoStatusFunc func() (uint32, nvml.Return) + + // GetAddressingModeFunc mocks the GetAddressingMode method. + GetAddressingModeFunc func() (nvml.DeviceAddressingMode, nvml.Return) + + // GetApplicationsClockFunc mocks the GetApplicationsClock method. + GetApplicationsClockFunc func(clockType nvml.ClockType) (uint32, nvml.Return) + + // GetArchitectureFunc mocks the GetArchitecture method. + GetArchitectureFunc func() (nvml.DeviceArchitecture, nvml.Return) + + // GetAttributesFunc mocks the GetAttributes method. + GetAttributesFunc func() (nvml.DeviceAttributes, nvml.Return) + + // GetAutoBoostedClocksEnabledFunc mocks the GetAutoBoostedClocksEnabled method. + GetAutoBoostedClocksEnabledFunc func() (nvml.EnableState, nvml.EnableState, nvml.Return) + + // GetBAR1MemoryInfoFunc mocks the GetBAR1MemoryInfo method. + GetBAR1MemoryInfoFunc func() (nvml.BAR1Memory, nvml.Return) + + // GetBoardIdFunc mocks the GetBoardId method. + GetBoardIdFunc func() (uint32, nvml.Return) + + // GetBoardPartNumberFunc mocks the GetBoardPartNumber method. + GetBoardPartNumberFunc func() (string, nvml.Return) + + // GetBrandFunc mocks the GetBrand method. + GetBrandFunc func() (nvml.BrandType, nvml.Return) + + // GetBridgeChipInfoFunc mocks the GetBridgeChipInfo method. + GetBridgeChipInfoFunc func() (nvml.BridgeChipHierarchy, nvml.Return) + + // GetBusTypeFunc mocks the GetBusType method. + GetBusTypeFunc func() (nvml.BusType, nvml.Return) + + // GetC2cModeInfoVFunc mocks the GetC2cModeInfoV method. + GetC2cModeInfoVFunc func() nvml.C2cModeInfoHandler + + // GetCapabilitiesFunc mocks the GetCapabilities method. + GetCapabilitiesFunc func() (nvml.DeviceCapabilities, nvml.Return) + + // GetClkMonStatusFunc mocks the GetClkMonStatus method. + GetClkMonStatusFunc func() (nvml.ClkMonStatus, nvml.Return) + + // GetClockFunc mocks the GetClock method. + GetClockFunc func(clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) + + // GetClockInfoFunc mocks the GetClockInfo method. + GetClockInfoFunc func(clockType nvml.ClockType) (uint32, nvml.Return) + + // GetClockOffsetsFunc mocks the GetClockOffsets method. + GetClockOffsetsFunc func() (nvml.ClockOffset, nvml.Return) + + // GetComputeInstanceIdFunc mocks the GetComputeInstanceId method. + GetComputeInstanceIdFunc func() (int, nvml.Return) + + // GetComputeModeFunc mocks the GetComputeMode method. + GetComputeModeFunc func() (nvml.ComputeMode, nvml.Return) + + // GetComputeRunningProcessesFunc mocks the GetComputeRunningProcesses method. + GetComputeRunningProcessesFunc func() ([]nvml.ProcessInfo, nvml.Return) + + // GetConfComputeGpuAttestationReportFunc mocks the GetConfComputeGpuAttestationReport method. + GetConfComputeGpuAttestationReportFunc func(confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return + + // GetConfComputeGpuCertificateFunc mocks the GetConfComputeGpuCertificate method. + GetConfComputeGpuCertificateFunc func() (nvml.ConfComputeGpuCertificate, nvml.Return) + + // GetConfComputeMemSizeInfoFunc mocks the GetConfComputeMemSizeInfo method. + GetConfComputeMemSizeInfoFunc func() (nvml.ConfComputeMemSizeInfo, nvml.Return) + + // GetConfComputeProtectedMemoryUsageFunc mocks the GetConfComputeProtectedMemoryUsage method. + GetConfComputeProtectedMemoryUsageFunc func() (nvml.Memory, nvml.Return) + + // GetCoolerInfoFunc mocks the GetCoolerInfo method. + GetCoolerInfoFunc func() (nvml.CoolerInfo, nvml.Return) + + // GetCpuAffinityFunc mocks the GetCpuAffinity method. + GetCpuAffinityFunc func(n int) ([]uint, nvml.Return) + + // GetCpuAffinityWithinScopeFunc mocks the GetCpuAffinityWithinScope method. + GetCpuAffinityWithinScopeFunc func(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) + + // GetCreatableVgpusFunc mocks the GetCreatableVgpus method. + GetCreatableVgpusFunc func() ([]nvml.VgpuTypeId, nvml.Return) + + // GetCudaComputeCapabilityFunc mocks the GetCudaComputeCapability method. + GetCudaComputeCapabilityFunc func() (int, int, nvml.Return) + + // GetCurrPcieLinkGenerationFunc mocks the GetCurrPcieLinkGeneration method. + GetCurrPcieLinkGenerationFunc func() (int, nvml.Return) + + // GetCurrPcieLinkWidthFunc mocks the GetCurrPcieLinkWidth method. + GetCurrPcieLinkWidthFunc func() (int, nvml.Return) + + // GetCurrentClockFreqsFunc mocks the GetCurrentClockFreqs method. + GetCurrentClockFreqsFunc func() (nvml.DeviceCurrentClockFreqs, nvml.Return) + + // GetCurrentClocksEventReasonsFunc mocks the GetCurrentClocksEventReasons method. + GetCurrentClocksEventReasonsFunc func() (uint64, nvml.Return) + + // GetCurrentClocksThrottleReasonsFunc mocks the GetCurrentClocksThrottleReasons method. + GetCurrentClocksThrottleReasonsFunc func() (uint64, nvml.Return) + + // GetDecoderUtilizationFunc mocks the GetDecoderUtilization method. + GetDecoderUtilizationFunc func() (uint32, uint32, nvml.Return) + + // GetDefaultApplicationsClockFunc mocks the GetDefaultApplicationsClock method. + GetDefaultApplicationsClockFunc func(clockType nvml.ClockType) (uint32, nvml.Return) + + // GetDefaultEccModeFunc mocks the GetDefaultEccMode method. + GetDefaultEccModeFunc func() (nvml.EnableState, nvml.Return) + + // GetDetailedEccErrorsFunc mocks the GetDetailedEccErrors method. + GetDetailedEccErrorsFunc func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) + + // GetDeviceHandleFromMigDeviceHandleFunc mocks the GetDeviceHandleFromMigDeviceHandle method. + GetDeviceHandleFromMigDeviceHandleFunc func() (nvml.Device, nvml.Return) + + // GetDisplayActiveFunc mocks the GetDisplayActive method. + GetDisplayActiveFunc func() (nvml.EnableState, nvml.Return) + + // GetDisplayModeFunc mocks the GetDisplayMode method. + GetDisplayModeFunc func() (nvml.EnableState, nvml.Return) + + // GetDramEncryptionModeFunc mocks the GetDramEncryptionMode method. + GetDramEncryptionModeFunc func() (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) + + // GetDriverModelFunc mocks the GetDriverModel method. + GetDriverModelFunc func() (nvml.DriverModel, nvml.DriverModel, nvml.Return) + + // GetDriverModel_v2Func mocks the GetDriverModel_v2 method. + GetDriverModel_v2Func func() (nvml.DriverModel, nvml.DriverModel, nvml.Return) + + // GetDynamicPstatesInfoFunc mocks the GetDynamicPstatesInfo method. + GetDynamicPstatesInfoFunc func() (nvml.GpuDynamicPstatesInfo, nvml.Return) + + // GetEccModeFunc mocks the GetEccMode method. + GetEccModeFunc func() (nvml.EnableState, nvml.EnableState, nvml.Return) + + // GetEncoderCapacityFunc mocks the GetEncoderCapacity method. + GetEncoderCapacityFunc func(encoderType nvml.EncoderType) (int, nvml.Return) + + // GetEncoderSessionsFunc mocks the GetEncoderSessions method. + GetEncoderSessionsFunc func() ([]nvml.EncoderSessionInfo, nvml.Return) + + // GetEncoderStatsFunc mocks the GetEncoderStats method. + GetEncoderStatsFunc func() (int, uint32, uint32, nvml.Return) + + // GetEncoderUtilizationFunc mocks the GetEncoderUtilization method. + GetEncoderUtilizationFunc func() (uint32, uint32, nvml.Return) + + // GetEnforcedPowerLimitFunc mocks the GetEnforcedPowerLimit method. + GetEnforcedPowerLimitFunc func() (uint32, nvml.Return) + + // GetFBCSessionsFunc mocks the GetFBCSessions method. + GetFBCSessionsFunc func() ([]nvml.FBCSessionInfo, nvml.Return) + + // GetFBCStatsFunc mocks the GetFBCStats method. + GetFBCStatsFunc func() (nvml.FBCStats, nvml.Return) + + // GetFanControlPolicy_v2Func mocks the GetFanControlPolicy_v2 method. + GetFanControlPolicy_v2Func func(n int) (nvml.FanControlPolicy, nvml.Return) + + // GetFanSpeedFunc mocks the GetFanSpeed method. + GetFanSpeedFunc func() (uint32, nvml.Return) + + // GetFanSpeedRPMFunc mocks the GetFanSpeedRPM method. + GetFanSpeedRPMFunc func() (nvml.FanSpeedInfo, nvml.Return) + + // GetFanSpeed_v2Func mocks the GetFanSpeed_v2 method. + GetFanSpeed_v2Func func(n int) (uint32, nvml.Return) + + // GetFieldValuesFunc mocks the GetFieldValues method. + GetFieldValuesFunc func(fieldValues []nvml.FieldValue) nvml.Return + + // GetGpcClkMinMaxVfOffsetFunc mocks the GetGpcClkMinMaxVfOffset method. + GetGpcClkMinMaxVfOffsetFunc func() (int, int, nvml.Return) + + // GetGpcClkVfOffsetFunc mocks the GetGpcClkVfOffset method. + GetGpcClkVfOffsetFunc func() (int, nvml.Return) + + // GetGpuFabricInfoFunc mocks the GetGpuFabricInfo method. + GetGpuFabricInfoFunc func() (nvml.GpuFabricInfo, nvml.Return) + + // GetGpuFabricInfoVFunc mocks the GetGpuFabricInfoV method. + GetGpuFabricInfoVFunc func() nvml.GpuFabricInfoHandler + + // GetGpuInstanceByIdFunc mocks the GetGpuInstanceById method. + GetGpuInstanceByIdFunc func(n int) (nvml.GpuInstance, nvml.Return) + + // GetGpuInstanceIdFunc mocks the GetGpuInstanceId method. + GetGpuInstanceIdFunc func() (int, nvml.Return) + + // GetGpuInstancePossiblePlacementsFunc mocks the GetGpuInstancePossiblePlacements method. + GetGpuInstancePossiblePlacementsFunc func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) + + // GetGpuInstanceProfileInfoFunc mocks the GetGpuInstanceProfileInfo method. + GetGpuInstanceProfileInfoFunc func(n int) (nvml.GpuInstanceProfileInfo, nvml.Return) + + // GetGpuInstanceProfileInfoByIdVFunc mocks the GetGpuInstanceProfileInfoByIdV method. + GetGpuInstanceProfileInfoByIdVFunc func(n int) nvml.GpuInstanceProfileInfoByIdHandler + + // GetGpuInstanceProfileInfoVFunc mocks the GetGpuInstanceProfileInfoV method. + GetGpuInstanceProfileInfoVFunc func(n int) nvml.GpuInstanceProfileInfoHandler + + // GetGpuInstanceRemainingCapacityFunc mocks the GetGpuInstanceRemainingCapacity method. + GetGpuInstanceRemainingCapacityFunc func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) + + // GetGpuInstancesFunc mocks the GetGpuInstances method. + GetGpuInstancesFunc func(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) + + // GetGpuMaxPcieLinkGenerationFunc mocks the GetGpuMaxPcieLinkGeneration method. + GetGpuMaxPcieLinkGenerationFunc func() (int, nvml.Return) + + // GetGpuOperationModeFunc mocks the GetGpuOperationMode method. + GetGpuOperationModeFunc func() (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) + + // GetGraphicsRunningProcessesFunc mocks the GetGraphicsRunningProcesses method. + GetGraphicsRunningProcessesFunc func() ([]nvml.ProcessInfo, nvml.Return) + + // GetGridLicensableFeaturesFunc mocks the GetGridLicensableFeatures method. + GetGridLicensableFeaturesFunc func() (nvml.GridLicensableFeatures, nvml.Return) + + // GetGspFirmwareModeFunc mocks the GetGspFirmwareMode method. + GetGspFirmwareModeFunc func() (bool, bool, nvml.Return) + + // GetGspFirmwareVersionFunc mocks the GetGspFirmwareVersion method. + GetGspFirmwareVersionFunc func() (string, nvml.Return) + + // GetHostVgpuModeFunc mocks the GetHostVgpuMode method. + GetHostVgpuModeFunc func() (nvml.HostVgpuMode, nvml.Return) + + // GetIndexFunc mocks the GetIndex method. + GetIndexFunc func() (int, nvml.Return) + + // GetInforomConfigurationChecksumFunc mocks the GetInforomConfigurationChecksum method. + GetInforomConfigurationChecksumFunc func() (uint32, nvml.Return) + + // GetInforomImageVersionFunc mocks the GetInforomImageVersion method. + GetInforomImageVersionFunc func() (string, nvml.Return) + + // GetInforomVersionFunc mocks the GetInforomVersion method. + GetInforomVersionFunc func(inforomObject nvml.InforomObject) (string, nvml.Return) + + // GetIrqNumFunc mocks the GetIrqNum method. + GetIrqNumFunc func() (int, nvml.Return) + + // GetJpgUtilizationFunc mocks the GetJpgUtilization method. + GetJpgUtilizationFunc func() (uint32, uint32, nvml.Return) + + // GetLastBBXFlushTimeFunc mocks the GetLastBBXFlushTime method. + GetLastBBXFlushTimeFunc func() (uint64, uint, nvml.Return) + + // GetMPSComputeRunningProcessesFunc mocks the GetMPSComputeRunningProcesses method. + GetMPSComputeRunningProcessesFunc func() ([]nvml.ProcessInfo, nvml.Return) + + // GetMarginTemperatureFunc mocks the GetMarginTemperature method. + GetMarginTemperatureFunc func() (nvml.MarginTemperature, nvml.Return) + + // GetMaxClockInfoFunc mocks the GetMaxClockInfo method. + GetMaxClockInfoFunc func(clockType nvml.ClockType) (uint32, nvml.Return) + + // GetMaxCustomerBoostClockFunc mocks the GetMaxCustomerBoostClock method. + GetMaxCustomerBoostClockFunc func(clockType nvml.ClockType) (uint32, nvml.Return) + + // GetMaxMigDeviceCountFunc mocks the GetMaxMigDeviceCount method. + GetMaxMigDeviceCountFunc func() (int, nvml.Return) + + // GetMaxPcieLinkGenerationFunc mocks the GetMaxPcieLinkGeneration method. + GetMaxPcieLinkGenerationFunc func() (int, nvml.Return) + + // GetMaxPcieLinkWidthFunc mocks the GetMaxPcieLinkWidth method. + GetMaxPcieLinkWidthFunc func() (int, nvml.Return) + + // GetMemClkMinMaxVfOffsetFunc mocks the GetMemClkMinMaxVfOffset method. + GetMemClkMinMaxVfOffsetFunc func() (int, int, nvml.Return) + + // GetMemClkVfOffsetFunc mocks the GetMemClkVfOffset method. + GetMemClkVfOffsetFunc func() (int, nvml.Return) + + // GetMemoryAffinityFunc mocks the GetMemoryAffinity method. + GetMemoryAffinityFunc func(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) + + // GetMemoryBusWidthFunc mocks the GetMemoryBusWidth method. + GetMemoryBusWidthFunc func() (uint32, nvml.Return) + + // GetMemoryErrorCounterFunc mocks the GetMemoryErrorCounter method. + GetMemoryErrorCounterFunc func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) + + // GetMemoryInfoFunc mocks the GetMemoryInfo method. + GetMemoryInfoFunc func() (nvml.Memory, nvml.Return) + + // GetMemoryInfo_v2Func mocks the GetMemoryInfo_v2 method. + GetMemoryInfo_v2Func func() (nvml.Memory_v2, nvml.Return) + + // GetMigDeviceHandleByIndexFunc mocks the GetMigDeviceHandleByIndex method. + GetMigDeviceHandleByIndexFunc func(n int) (nvml.Device, nvml.Return) + + // GetMigModeFunc mocks the GetMigMode method. + GetMigModeFunc func() (int, int, nvml.Return) + + // GetMinMaxClockOfPStateFunc mocks the GetMinMaxClockOfPState method. + GetMinMaxClockOfPStateFunc func(clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) + + // GetMinMaxFanSpeedFunc mocks the GetMinMaxFanSpeed method. + GetMinMaxFanSpeedFunc func() (int, int, nvml.Return) + + // GetMinorNumberFunc mocks the GetMinorNumber method. + GetMinorNumberFunc func() (int, nvml.Return) + + // GetModuleIdFunc mocks the GetModuleId method. + GetModuleIdFunc func() (int, nvml.Return) + + // GetMultiGpuBoardFunc mocks the GetMultiGpuBoard method. + GetMultiGpuBoardFunc func() (int, nvml.Return) + + // GetNameFunc mocks the GetName method. + GetNameFunc func() (string, nvml.Return) + + // GetNumFansFunc mocks the GetNumFans method. + GetNumFansFunc func() (int, nvml.Return) + + // GetNumGpuCoresFunc mocks the GetNumGpuCores method. + GetNumGpuCoresFunc func() (int, nvml.Return) + + // GetNumaNodeIdFunc mocks the GetNumaNodeId method. + GetNumaNodeIdFunc func() (int, nvml.Return) + + // GetNvLinkCapabilityFunc mocks the GetNvLinkCapability method. + GetNvLinkCapabilityFunc func(n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) + + // GetNvLinkErrorCounterFunc mocks the GetNvLinkErrorCounter method. + GetNvLinkErrorCounterFunc func(n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) + + // GetNvLinkInfoFunc mocks the GetNvLinkInfo method. + GetNvLinkInfoFunc func() nvml.NvLinkInfoHandler + + // GetNvLinkRemoteDeviceTypeFunc mocks the GetNvLinkRemoteDeviceType method. + GetNvLinkRemoteDeviceTypeFunc func(n int) (nvml.IntNvLinkDeviceType, nvml.Return) + + // GetNvLinkRemotePciInfoFunc mocks the GetNvLinkRemotePciInfo method. + GetNvLinkRemotePciInfoFunc func(n int) (nvml.PciInfo, nvml.Return) + + // GetNvLinkStateFunc mocks the GetNvLinkState method. + GetNvLinkStateFunc func(n int) (nvml.EnableState, nvml.Return) + + // GetNvLinkUtilizationControlFunc mocks the GetNvLinkUtilizationControl method. + GetNvLinkUtilizationControlFunc func(n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) + + // GetNvLinkUtilizationCounterFunc mocks the GetNvLinkUtilizationCounter method. + GetNvLinkUtilizationCounterFunc func(n1 int, n2 int) (uint64, uint64, nvml.Return) + + // GetNvLinkVersionFunc mocks the GetNvLinkVersion method. + GetNvLinkVersionFunc func(n int) (uint32, nvml.Return) + + // GetNvlinkBwModeFunc mocks the GetNvlinkBwMode method. + GetNvlinkBwModeFunc func() (nvml.NvlinkGetBwMode, nvml.Return) + + // GetNvlinkSupportedBwModesFunc mocks the GetNvlinkSupportedBwModes method. + GetNvlinkSupportedBwModesFunc func() (nvml.NvlinkSupportedBwModes, nvml.Return) + + // GetOfaUtilizationFunc mocks the GetOfaUtilization method. + GetOfaUtilizationFunc func() (uint32, uint32, nvml.Return) + + // GetP2PStatusFunc mocks the GetP2PStatus method. + GetP2PStatusFunc func(device nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) + + // GetPciInfoFunc mocks the GetPciInfo method. + GetPciInfoFunc func() (nvml.PciInfo, nvml.Return) + + // GetPciInfoExtFunc mocks the GetPciInfoExt method. + GetPciInfoExtFunc func() (nvml.PciInfoExt, nvml.Return) + + // GetPcieLinkMaxSpeedFunc mocks the GetPcieLinkMaxSpeed method. + GetPcieLinkMaxSpeedFunc func() (uint32, nvml.Return) + + // GetPcieReplayCounterFunc mocks the GetPcieReplayCounter method. + GetPcieReplayCounterFunc func() (int, nvml.Return) + + // GetPcieSpeedFunc mocks the GetPcieSpeed method. + GetPcieSpeedFunc func() (int, nvml.Return) + + // GetPcieThroughputFunc mocks the GetPcieThroughput method. + GetPcieThroughputFunc func(pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) + + // GetPdiFunc mocks the GetPdi method. + GetPdiFunc func() (nvml.Pdi, nvml.Return) + + // GetPerformanceModesFunc mocks the GetPerformanceModes method. + GetPerformanceModesFunc func() (nvml.DevicePerfModes, nvml.Return) + + // GetPerformanceStateFunc mocks the GetPerformanceState method. + GetPerformanceStateFunc func() (nvml.Pstates, nvml.Return) + + // GetPersistenceModeFunc mocks the GetPersistenceMode method. + GetPersistenceModeFunc func() (nvml.EnableState, nvml.Return) + + // GetPgpuMetadataStringFunc mocks the GetPgpuMetadataString method. + GetPgpuMetadataStringFunc func() (string, nvml.Return) + + // GetPlatformInfoFunc mocks the GetPlatformInfo method. + GetPlatformInfoFunc func() (nvml.PlatformInfo, nvml.Return) + + // GetPowerManagementDefaultLimitFunc mocks the GetPowerManagementDefaultLimit method. + GetPowerManagementDefaultLimitFunc func() (uint32, nvml.Return) + + // GetPowerManagementLimitFunc mocks the GetPowerManagementLimit method. + GetPowerManagementLimitFunc func() (uint32, nvml.Return) + + // GetPowerManagementLimitConstraintsFunc mocks the GetPowerManagementLimitConstraints method. + GetPowerManagementLimitConstraintsFunc func() (uint32, uint32, nvml.Return) + + // GetPowerManagementModeFunc mocks the GetPowerManagementMode method. + GetPowerManagementModeFunc func() (nvml.EnableState, nvml.Return) + + // GetPowerMizerMode_v1Func mocks the GetPowerMizerMode_v1 method. + GetPowerMizerMode_v1Func func() (nvml.DevicePowerMizerModes_v1, nvml.Return) + + // GetPowerSourceFunc mocks the GetPowerSource method. + GetPowerSourceFunc func() (nvml.PowerSource, nvml.Return) + + // GetPowerStateFunc mocks the GetPowerState method. + GetPowerStateFunc func() (nvml.Pstates, nvml.Return) + + // GetPowerUsageFunc mocks the GetPowerUsage method. + GetPowerUsageFunc func() (uint32, nvml.Return) + + // GetProcessUtilizationFunc mocks the GetProcessUtilization method. + GetProcessUtilizationFunc func(v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) + + // GetProcessesUtilizationInfoFunc mocks the GetProcessesUtilizationInfo method. + GetProcessesUtilizationInfoFunc func() (nvml.ProcessesUtilizationInfo, nvml.Return) + + // GetRemappedRowsFunc mocks the GetRemappedRows method. + GetRemappedRowsFunc func() (int, int, bool, bool, nvml.Return) + + // GetRepairStatusFunc mocks the GetRepairStatus method. + GetRepairStatusFunc func() (nvml.RepairStatus, nvml.Return) + + // GetRetiredPagesFunc mocks the GetRetiredPages method. + GetRetiredPagesFunc func(pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) + + // GetRetiredPagesPendingStatusFunc mocks the GetRetiredPagesPendingStatus method. + GetRetiredPagesPendingStatusFunc func() (nvml.EnableState, nvml.Return) + + // GetRetiredPages_v2Func mocks the GetRetiredPages_v2 method. + GetRetiredPages_v2Func func(pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) + + // GetRowRemapperHistogramFunc mocks the GetRowRemapperHistogram method. + GetRowRemapperHistogramFunc func() (nvml.RowRemapperHistogramValues, nvml.Return) + + // GetRunningProcessDetailListFunc mocks the GetRunningProcessDetailList method. + GetRunningProcessDetailListFunc func() (nvml.ProcessDetailList, nvml.Return) + + // GetSamplesFunc mocks the GetSamples method. + GetSamplesFunc func(samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) + + // GetSerialFunc mocks the GetSerial method. + GetSerialFunc func() (string, nvml.Return) + + // GetSramEccErrorStatusFunc mocks the GetSramEccErrorStatus method. + GetSramEccErrorStatusFunc func() (nvml.EccSramErrorStatus, nvml.Return) + + // GetSramUniqueUncorrectedEccErrorCountsFunc mocks the GetSramUniqueUncorrectedEccErrorCounts method. + GetSramUniqueUncorrectedEccErrorCountsFunc func(eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return + + // GetSupportedClocksEventReasonsFunc mocks the GetSupportedClocksEventReasons method. + GetSupportedClocksEventReasonsFunc func() (uint64, nvml.Return) + + // GetSupportedClocksThrottleReasonsFunc mocks the GetSupportedClocksThrottleReasons method. + GetSupportedClocksThrottleReasonsFunc func() (uint64, nvml.Return) + + // GetSupportedEventTypesFunc mocks the GetSupportedEventTypes method. + GetSupportedEventTypesFunc func() (uint64, nvml.Return) + + // GetSupportedGraphicsClocksFunc mocks the GetSupportedGraphicsClocks method. + GetSupportedGraphicsClocksFunc func(n int) (int, uint32, nvml.Return) + + // GetSupportedMemoryClocksFunc mocks the GetSupportedMemoryClocks method. + GetSupportedMemoryClocksFunc func() (int, uint32, nvml.Return) + + // GetSupportedPerformanceStatesFunc mocks the GetSupportedPerformanceStates method. + GetSupportedPerformanceStatesFunc func() ([]nvml.Pstates, nvml.Return) + + // GetSupportedVgpusFunc mocks the GetSupportedVgpus method. + GetSupportedVgpusFunc func() ([]nvml.VgpuTypeId, nvml.Return) + + // GetTargetFanSpeedFunc mocks the GetTargetFanSpeed method. + GetTargetFanSpeedFunc func(n int) (int, nvml.Return) + + // GetTemperatureFunc mocks the GetTemperature method. + GetTemperatureFunc func(temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) + + // GetTemperatureThresholdFunc mocks the GetTemperatureThreshold method. + GetTemperatureThresholdFunc func(temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) + + // GetTemperatureVFunc mocks the GetTemperatureV method. + GetTemperatureVFunc func() nvml.TemperatureHandler + + // GetThermalSettingsFunc mocks the GetThermalSettings method. + GetThermalSettingsFunc func(v uint32) (nvml.GpuThermalSettings, nvml.Return) + + // GetTopologyCommonAncestorFunc mocks the GetTopologyCommonAncestor method. + GetTopologyCommonAncestorFunc func(device nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) + + // GetTopologyNearestGpusFunc mocks the GetTopologyNearestGpus method. + GetTopologyNearestGpusFunc func(gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) + + // GetTotalEccErrorsFunc mocks the GetTotalEccErrors method. + GetTotalEccErrorsFunc func(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) + + // GetTotalEnergyConsumptionFunc mocks the GetTotalEnergyConsumption method. + GetTotalEnergyConsumptionFunc func() (uint64, nvml.Return) + + // GetUUIDFunc mocks the GetUUID method. + GetUUIDFunc func() (string, nvml.Return) + + // GetUtilizationRatesFunc mocks the GetUtilizationRates method. + GetUtilizationRatesFunc func() (nvml.Utilization, nvml.Return) + + // GetVbiosVersionFunc mocks the GetVbiosVersion method. + GetVbiosVersionFunc func() (string, nvml.Return) + + // GetVgpuCapabilitiesFunc mocks the GetVgpuCapabilities method. + GetVgpuCapabilitiesFunc func(deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) + + // GetVgpuHeterogeneousModeFunc mocks the GetVgpuHeterogeneousMode method. + GetVgpuHeterogeneousModeFunc func() (nvml.VgpuHeterogeneousMode, nvml.Return) + + // GetVgpuInstancesUtilizationInfoFunc mocks the GetVgpuInstancesUtilizationInfo method. + GetVgpuInstancesUtilizationInfoFunc func() (nvml.VgpuInstancesUtilizationInfo, nvml.Return) + + // GetVgpuMetadataFunc mocks the GetVgpuMetadata method. + GetVgpuMetadataFunc func() (nvml.VgpuPgpuMetadata, nvml.Return) + + // GetVgpuProcessUtilizationFunc mocks the GetVgpuProcessUtilization method. + GetVgpuProcessUtilizationFunc func(v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) + + // GetVgpuProcessesUtilizationInfoFunc mocks the GetVgpuProcessesUtilizationInfo method. + GetVgpuProcessesUtilizationInfoFunc func() (nvml.VgpuProcessesUtilizationInfo, nvml.Return) + + // GetVgpuSchedulerCapabilitiesFunc mocks the GetVgpuSchedulerCapabilities method. + GetVgpuSchedulerCapabilitiesFunc func() (nvml.VgpuSchedulerCapabilities, nvml.Return) + + // GetVgpuSchedulerLogFunc mocks the GetVgpuSchedulerLog method. + GetVgpuSchedulerLogFunc func() (nvml.VgpuSchedulerLog, nvml.Return) + + // GetVgpuSchedulerStateFunc mocks the GetVgpuSchedulerState method. + GetVgpuSchedulerStateFunc func() (nvml.VgpuSchedulerGetState, nvml.Return) + + // GetVgpuTypeCreatablePlacementsFunc mocks the GetVgpuTypeCreatablePlacements method. + GetVgpuTypeCreatablePlacementsFunc func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) + + // GetVgpuTypeSupportedPlacementsFunc mocks the GetVgpuTypeSupportedPlacements method. + GetVgpuTypeSupportedPlacementsFunc func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) + + // GetVgpuUtilizationFunc mocks the GetVgpuUtilization method. + GetVgpuUtilizationFunc func(v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) + + // GetViolationStatusFunc mocks the GetViolationStatus method. + GetViolationStatusFunc func(perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) + + // GetVirtualizationModeFunc mocks the GetVirtualizationMode method. + GetVirtualizationModeFunc func() (nvml.GpuVirtualizationMode, nvml.Return) + + // GpmMigSampleGetFunc mocks the GpmMigSampleGet method. + GpmMigSampleGetFunc func(n int, gpmSample nvml.GpmSample) nvml.Return + + // GpmQueryDeviceSupportFunc mocks the GpmQueryDeviceSupport method. + GpmQueryDeviceSupportFunc func() (nvml.GpmSupport, nvml.Return) + + // GpmQueryDeviceSupportVFunc mocks the GpmQueryDeviceSupportV method. + GpmQueryDeviceSupportVFunc func() nvml.GpmSupportV + + // GpmQueryIfStreamingEnabledFunc mocks the GpmQueryIfStreamingEnabled method. + GpmQueryIfStreamingEnabledFunc func() (uint32, nvml.Return) + + // GpmSampleGetFunc mocks the GpmSampleGet method. + GpmSampleGetFunc func(gpmSample nvml.GpmSample) nvml.Return + + // GpmSetStreamingEnabledFunc mocks the GpmSetStreamingEnabled method. + GpmSetStreamingEnabledFunc func(v uint32) nvml.Return + + // IsMigDeviceHandleFunc mocks the IsMigDeviceHandle method. + IsMigDeviceHandleFunc func() (bool, nvml.Return) + + // OnSameBoardFunc mocks the OnSameBoard method. + OnSameBoardFunc func(device nvml.Device) (int, nvml.Return) + + // PowerSmoothingActivatePresetProfileFunc mocks the PowerSmoothingActivatePresetProfile method. + PowerSmoothingActivatePresetProfileFunc func(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return + + // PowerSmoothingSetStateFunc mocks the PowerSmoothingSetState method. + PowerSmoothingSetStateFunc func(powerSmoothingState *nvml.PowerSmoothingState) nvml.Return + + // PowerSmoothingUpdatePresetProfileParamFunc mocks the PowerSmoothingUpdatePresetProfileParam method. + PowerSmoothingUpdatePresetProfileParamFunc func(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return + + // ReadWritePRM_v1Func mocks the ReadWritePRM_v1 method. + ReadWritePRM_v1Func func(pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return + + // RegisterEventsFunc mocks the RegisterEvents method. + RegisterEventsFunc func(v uint64, eventSet nvml.EventSet) nvml.Return + + // ResetApplicationsClocksFunc mocks the ResetApplicationsClocks method. + ResetApplicationsClocksFunc func() nvml.Return + + // ResetGpuLockedClocksFunc mocks the ResetGpuLockedClocks method. + ResetGpuLockedClocksFunc func() nvml.Return + + // ResetMemoryLockedClocksFunc mocks the ResetMemoryLockedClocks method. + ResetMemoryLockedClocksFunc func() nvml.Return + + // ResetNvLinkErrorCountersFunc mocks the ResetNvLinkErrorCounters method. + ResetNvLinkErrorCountersFunc func(n int) nvml.Return + + // ResetNvLinkUtilizationCounterFunc mocks the ResetNvLinkUtilizationCounter method. + ResetNvLinkUtilizationCounterFunc func(n1 int, n2 int) nvml.Return + + // SetAPIRestrictionFunc mocks the SetAPIRestriction method. + SetAPIRestrictionFunc func(restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return + + // SetAccountingModeFunc mocks the SetAccountingMode method. + SetAccountingModeFunc func(enableState nvml.EnableState) nvml.Return + + // SetApplicationsClocksFunc mocks the SetApplicationsClocks method. + SetApplicationsClocksFunc func(v1 uint32, v2 uint32) nvml.Return + + // SetAutoBoostedClocksEnabledFunc mocks the SetAutoBoostedClocksEnabled method. + SetAutoBoostedClocksEnabledFunc func(enableState nvml.EnableState) nvml.Return + + // SetClockOffsetsFunc mocks the SetClockOffsets method. + SetClockOffsetsFunc func(clockOffset nvml.ClockOffset) nvml.Return + + // SetComputeModeFunc mocks the SetComputeMode method. + SetComputeModeFunc func(computeMode nvml.ComputeMode) nvml.Return + + // SetConfComputeUnprotectedMemSizeFunc mocks the SetConfComputeUnprotectedMemSize method. + SetConfComputeUnprotectedMemSizeFunc func(v uint64) nvml.Return + + // SetCpuAffinityFunc mocks the SetCpuAffinity method. + SetCpuAffinityFunc func() nvml.Return + + // SetDefaultAutoBoostedClocksEnabledFunc mocks the SetDefaultAutoBoostedClocksEnabled method. + SetDefaultAutoBoostedClocksEnabledFunc func(enableState nvml.EnableState, v uint32) nvml.Return + + // SetDefaultFanSpeed_v2Func mocks the SetDefaultFanSpeed_v2 method. + SetDefaultFanSpeed_v2Func func(n int) nvml.Return + + // SetDramEncryptionModeFunc mocks the SetDramEncryptionMode method. + SetDramEncryptionModeFunc func(dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return + + // SetDriverModelFunc mocks the SetDriverModel method. + SetDriverModelFunc func(driverModel nvml.DriverModel, v uint32) nvml.Return + + // SetEccModeFunc mocks the SetEccMode method. + SetEccModeFunc func(enableState nvml.EnableState) nvml.Return + + // SetFanControlPolicyFunc mocks the SetFanControlPolicy method. + SetFanControlPolicyFunc func(n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return + + // SetFanSpeed_v2Func mocks the SetFanSpeed_v2 method. + SetFanSpeed_v2Func func(n1 int, n2 int) nvml.Return + + // SetGpcClkVfOffsetFunc mocks the SetGpcClkVfOffset method. + SetGpcClkVfOffsetFunc func(n int) nvml.Return + + // SetGpuLockedClocksFunc mocks the SetGpuLockedClocks method. + SetGpuLockedClocksFunc func(v1 uint32, v2 uint32) nvml.Return + + // SetGpuOperationModeFunc mocks the SetGpuOperationMode method. + SetGpuOperationModeFunc func(gpuOperationMode nvml.GpuOperationMode) nvml.Return + + // SetMemClkVfOffsetFunc mocks the SetMemClkVfOffset method. + SetMemClkVfOffsetFunc func(n int) nvml.Return + + // SetMemoryLockedClocksFunc mocks the SetMemoryLockedClocks method. + SetMemoryLockedClocksFunc func(v1 uint32, v2 uint32) nvml.Return + + // SetMigModeFunc mocks the SetMigMode method. + SetMigModeFunc func(n int) (nvml.Return, nvml.Return) + + // SetNvLinkDeviceLowPowerThresholdFunc mocks the SetNvLinkDeviceLowPowerThreshold method. + SetNvLinkDeviceLowPowerThresholdFunc func(nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return + + // SetNvLinkUtilizationControlFunc mocks the SetNvLinkUtilizationControl method. + SetNvLinkUtilizationControlFunc func(n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return + + // SetNvlinkBwModeFunc mocks the SetNvlinkBwMode method. + SetNvlinkBwModeFunc func(nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return + + // SetPersistenceModeFunc mocks the SetPersistenceMode method. + SetPersistenceModeFunc func(enableState nvml.EnableState) nvml.Return + + // SetPowerManagementLimitFunc mocks the SetPowerManagementLimit method. + SetPowerManagementLimitFunc func(v uint32) nvml.Return + + // SetPowerManagementLimit_v2Func mocks the SetPowerManagementLimit_v2 method. + SetPowerManagementLimit_v2Func func(powerValue_v2 *nvml.PowerValue_v2) nvml.Return + + // SetTemperatureThresholdFunc mocks the SetTemperatureThreshold method. + SetTemperatureThresholdFunc func(temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return + + // SetVgpuCapabilitiesFunc mocks the SetVgpuCapabilities method. + SetVgpuCapabilitiesFunc func(deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return + + // SetVgpuHeterogeneousModeFunc mocks the SetVgpuHeterogeneousMode method. + SetVgpuHeterogeneousModeFunc func(vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return + + // SetVgpuSchedulerStateFunc mocks the SetVgpuSchedulerState method. + SetVgpuSchedulerStateFunc func(vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return + + // SetVirtualizationModeFunc mocks the SetVirtualizationMode method. + SetVirtualizationModeFunc func(gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return + + // ValidateInforomFunc mocks the ValidateInforom method. + ValidateInforomFunc func() nvml.Return + + // VgpuTypeGetMaxInstancesFunc mocks the VgpuTypeGetMaxInstances method. + VgpuTypeGetMaxInstancesFunc func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) + + // WorkloadPowerProfileClearRequestedProfilesFunc mocks the WorkloadPowerProfileClearRequestedProfiles method. + WorkloadPowerProfileClearRequestedProfilesFunc func(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return + + // WorkloadPowerProfileGetCurrentProfilesFunc mocks the WorkloadPowerProfileGetCurrentProfiles method. + WorkloadPowerProfileGetCurrentProfilesFunc func() (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) + + // WorkloadPowerProfileGetProfilesInfoFunc mocks the WorkloadPowerProfileGetProfilesInfo method. + WorkloadPowerProfileGetProfilesInfoFunc func() (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) + + // WorkloadPowerProfileSetRequestedProfilesFunc mocks the WorkloadPowerProfileSetRequestedProfiles method. + WorkloadPowerProfileSetRequestedProfilesFunc func(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return + + // calls tracks calls to the methods. + calls struct { + // ClearAccountingPids holds details about calls to the ClearAccountingPids method. + ClearAccountingPids []struct { + } + // ClearCpuAffinity holds details about calls to the ClearCpuAffinity method. + ClearCpuAffinity []struct { + } + // ClearEccErrorCounts holds details about calls to the ClearEccErrorCounts method. + ClearEccErrorCounts []struct { + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // ClearFieldValues holds details about calls to the ClearFieldValues method. + ClearFieldValues []struct { + // FieldValues is the fieldValues argument value. + FieldValues []nvml.FieldValue + } + // CreateGpuInstance holds details about calls to the CreateGpuInstance method. + CreateGpuInstance []struct { + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // CreateGpuInstanceWithPlacement holds details about calls to the CreateGpuInstanceWithPlacement method. + CreateGpuInstanceWithPlacement []struct { + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + // GpuInstancePlacement is the gpuInstancePlacement argument value. + GpuInstancePlacement *nvml.GpuInstancePlacement + } + // FreezeNvLinkUtilizationCounter holds details about calls to the FreezeNvLinkUtilizationCounter method. + FreezeNvLinkUtilizationCounter []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // GetAPIRestriction holds details about calls to the GetAPIRestriction method. + GetAPIRestriction []struct { + // RestrictedAPI is the restrictedAPI argument value. + RestrictedAPI nvml.RestrictedAPI + } + // GetAccountingBufferSize holds details about calls to the GetAccountingBufferSize method. + GetAccountingBufferSize []struct { + } + // GetAccountingMode holds details about calls to the GetAccountingMode method. + GetAccountingMode []struct { + } + // GetAccountingPids holds details about calls to the GetAccountingPids method. + GetAccountingPids []struct { + } + // GetAccountingStats holds details about calls to the GetAccountingStats method. + GetAccountingStats []struct { + // V is the v argument value. + V uint32 + } + // GetActiveVgpus holds details about calls to the GetActiveVgpus method. + GetActiveVgpus []struct { + } + // GetAdaptiveClockInfoStatus holds details about calls to the GetAdaptiveClockInfoStatus method. + GetAdaptiveClockInfoStatus []struct { + } + // GetAddressingMode holds details about calls to the GetAddressingMode method. + GetAddressingMode []struct { + } + // GetApplicationsClock holds details about calls to the GetApplicationsClock method. + GetApplicationsClock []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // GetArchitecture holds details about calls to the GetArchitecture method. + GetArchitecture []struct { + } + // GetAttributes holds details about calls to the GetAttributes method. + GetAttributes []struct { + } + // GetAutoBoostedClocksEnabled holds details about calls to the GetAutoBoostedClocksEnabled method. + GetAutoBoostedClocksEnabled []struct { + } + // GetBAR1MemoryInfo holds details about calls to the GetBAR1MemoryInfo method. + GetBAR1MemoryInfo []struct { + } + // GetBoardId holds details about calls to the GetBoardId method. + GetBoardId []struct { + } + // GetBoardPartNumber holds details about calls to the GetBoardPartNumber method. + GetBoardPartNumber []struct { + } + // GetBrand holds details about calls to the GetBrand method. + GetBrand []struct { + } + // GetBridgeChipInfo holds details about calls to the GetBridgeChipInfo method. + GetBridgeChipInfo []struct { + } + // GetBusType holds details about calls to the GetBusType method. + GetBusType []struct { + } + // GetC2cModeInfoV holds details about calls to the GetC2cModeInfoV method. + GetC2cModeInfoV []struct { + } + // GetCapabilities holds details about calls to the GetCapabilities method. + GetCapabilities []struct { + } + // GetClkMonStatus holds details about calls to the GetClkMonStatus method. + GetClkMonStatus []struct { + } + // GetClock holds details about calls to the GetClock method. + GetClock []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + // ClockId is the clockId argument value. + ClockId nvml.ClockId + } + // GetClockInfo holds details about calls to the GetClockInfo method. + GetClockInfo []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // GetClockOffsets holds details about calls to the GetClockOffsets method. + GetClockOffsets []struct { + } + // GetComputeInstanceId holds details about calls to the GetComputeInstanceId method. + GetComputeInstanceId []struct { + } + // GetComputeMode holds details about calls to the GetComputeMode method. + GetComputeMode []struct { + } + // GetComputeRunningProcesses holds details about calls to the GetComputeRunningProcesses method. + GetComputeRunningProcesses []struct { + } + // GetConfComputeGpuAttestationReport holds details about calls to the GetConfComputeGpuAttestationReport method. + GetConfComputeGpuAttestationReport []struct { + // ConfComputeGpuAttestationReport is the confComputeGpuAttestationReport argument value. + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + } + // GetConfComputeGpuCertificate holds details about calls to the GetConfComputeGpuCertificate method. + GetConfComputeGpuCertificate []struct { + } + // GetConfComputeMemSizeInfo holds details about calls to the GetConfComputeMemSizeInfo method. + GetConfComputeMemSizeInfo []struct { + } + // GetConfComputeProtectedMemoryUsage holds details about calls to the GetConfComputeProtectedMemoryUsage method. + GetConfComputeProtectedMemoryUsage []struct { + } + // GetCoolerInfo holds details about calls to the GetCoolerInfo method. + GetCoolerInfo []struct { + } + // GetCpuAffinity holds details about calls to the GetCpuAffinity method. + GetCpuAffinity []struct { + // N is the n argument value. + N int + } + // GetCpuAffinityWithinScope holds details about calls to the GetCpuAffinityWithinScope method. + GetCpuAffinityWithinScope []struct { + // N is the n argument value. + N int + // AffinityScope is the affinityScope argument value. + AffinityScope nvml.AffinityScope + } + // GetCreatableVgpus holds details about calls to the GetCreatableVgpus method. + GetCreatableVgpus []struct { + } + // GetCudaComputeCapability holds details about calls to the GetCudaComputeCapability method. + GetCudaComputeCapability []struct { + } + // GetCurrPcieLinkGeneration holds details about calls to the GetCurrPcieLinkGeneration method. + GetCurrPcieLinkGeneration []struct { + } + // GetCurrPcieLinkWidth holds details about calls to the GetCurrPcieLinkWidth method. + GetCurrPcieLinkWidth []struct { + } + // GetCurrentClockFreqs holds details about calls to the GetCurrentClockFreqs method. + GetCurrentClockFreqs []struct { + } + // GetCurrentClocksEventReasons holds details about calls to the GetCurrentClocksEventReasons method. + GetCurrentClocksEventReasons []struct { + } + // GetCurrentClocksThrottleReasons holds details about calls to the GetCurrentClocksThrottleReasons method. + GetCurrentClocksThrottleReasons []struct { + } + // GetDecoderUtilization holds details about calls to the GetDecoderUtilization method. + GetDecoderUtilization []struct { + } + // GetDefaultApplicationsClock holds details about calls to the GetDefaultApplicationsClock method. + GetDefaultApplicationsClock []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // GetDefaultEccMode holds details about calls to the GetDefaultEccMode method. + GetDefaultEccMode []struct { + } + // GetDetailedEccErrors holds details about calls to the GetDetailedEccErrors method. + GetDetailedEccErrors []struct { + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // GetDeviceHandleFromMigDeviceHandle holds details about calls to the GetDeviceHandleFromMigDeviceHandle method. + GetDeviceHandleFromMigDeviceHandle []struct { + } + // GetDisplayActive holds details about calls to the GetDisplayActive method. + GetDisplayActive []struct { + } + // GetDisplayMode holds details about calls to the GetDisplayMode method. + GetDisplayMode []struct { + } + // GetDramEncryptionMode holds details about calls to the GetDramEncryptionMode method. + GetDramEncryptionMode []struct { + } + // GetDriverModel holds details about calls to the GetDriverModel method. + GetDriverModel []struct { + } + // GetDriverModel_v2 holds details about calls to the GetDriverModel_v2 method. + GetDriverModel_v2 []struct { + } + // GetDynamicPstatesInfo holds details about calls to the GetDynamicPstatesInfo method. + GetDynamicPstatesInfo []struct { + } + // GetEccMode holds details about calls to the GetEccMode method. + GetEccMode []struct { + } + // GetEncoderCapacity holds details about calls to the GetEncoderCapacity method. + GetEncoderCapacity []struct { + // EncoderType is the encoderType argument value. + EncoderType nvml.EncoderType + } + // GetEncoderSessions holds details about calls to the GetEncoderSessions method. + GetEncoderSessions []struct { + } + // GetEncoderStats holds details about calls to the GetEncoderStats method. + GetEncoderStats []struct { + } + // GetEncoderUtilization holds details about calls to the GetEncoderUtilization method. + GetEncoderUtilization []struct { + } + // GetEnforcedPowerLimit holds details about calls to the GetEnforcedPowerLimit method. + GetEnforcedPowerLimit []struct { + } + // GetFBCSessions holds details about calls to the GetFBCSessions method. + GetFBCSessions []struct { + } + // GetFBCStats holds details about calls to the GetFBCStats method. + GetFBCStats []struct { + } + // GetFanControlPolicy_v2 holds details about calls to the GetFanControlPolicy_v2 method. + GetFanControlPolicy_v2 []struct { + // N is the n argument value. + N int + } + // GetFanSpeed holds details about calls to the GetFanSpeed method. + GetFanSpeed []struct { + } + // GetFanSpeedRPM holds details about calls to the GetFanSpeedRPM method. + GetFanSpeedRPM []struct { + } + // GetFanSpeed_v2 holds details about calls to the GetFanSpeed_v2 method. + GetFanSpeed_v2 []struct { + // N is the n argument value. + N int + } + // GetFieldValues holds details about calls to the GetFieldValues method. + GetFieldValues []struct { + // FieldValues is the fieldValues argument value. + FieldValues []nvml.FieldValue + } + // GetGpcClkMinMaxVfOffset holds details about calls to the GetGpcClkMinMaxVfOffset method. + GetGpcClkMinMaxVfOffset []struct { + } + // GetGpcClkVfOffset holds details about calls to the GetGpcClkVfOffset method. + GetGpcClkVfOffset []struct { + } + // GetGpuFabricInfo holds details about calls to the GetGpuFabricInfo method. + GetGpuFabricInfo []struct { + } + // GetGpuFabricInfoV holds details about calls to the GetGpuFabricInfoV method. + GetGpuFabricInfoV []struct { + } + // GetGpuInstanceById holds details about calls to the GetGpuInstanceById method. + GetGpuInstanceById []struct { + // N is the n argument value. + N int + } + // GetGpuInstanceId holds details about calls to the GetGpuInstanceId method. + GetGpuInstanceId []struct { + } + // GetGpuInstancePossiblePlacements holds details about calls to the GetGpuInstancePossiblePlacements method. + GetGpuInstancePossiblePlacements []struct { + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // GetGpuInstanceProfileInfo holds details about calls to the GetGpuInstanceProfileInfo method. + GetGpuInstanceProfileInfo []struct { + // N is the n argument value. + N int + } + // GetGpuInstanceProfileInfoByIdV holds details about calls to the GetGpuInstanceProfileInfoByIdV method. + GetGpuInstanceProfileInfoByIdV []struct { + // N is the n argument value. + N int + } + // GetGpuInstanceProfileInfoV holds details about calls to the GetGpuInstanceProfileInfoV method. + GetGpuInstanceProfileInfoV []struct { + // N is the n argument value. + N int + } + // GetGpuInstanceRemainingCapacity holds details about calls to the GetGpuInstanceRemainingCapacity method. + GetGpuInstanceRemainingCapacity []struct { + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // GetGpuInstances holds details about calls to the GetGpuInstances method. + GetGpuInstances []struct { + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // GetGpuMaxPcieLinkGeneration holds details about calls to the GetGpuMaxPcieLinkGeneration method. + GetGpuMaxPcieLinkGeneration []struct { + } + // GetGpuOperationMode holds details about calls to the GetGpuOperationMode method. + GetGpuOperationMode []struct { + } + // GetGraphicsRunningProcesses holds details about calls to the GetGraphicsRunningProcesses method. + GetGraphicsRunningProcesses []struct { + } + // GetGridLicensableFeatures holds details about calls to the GetGridLicensableFeatures method. + GetGridLicensableFeatures []struct { + } + // GetGspFirmwareMode holds details about calls to the GetGspFirmwareMode method. + GetGspFirmwareMode []struct { + } + // GetGspFirmwareVersion holds details about calls to the GetGspFirmwareVersion method. + GetGspFirmwareVersion []struct { + } + // GetHostVgpuMode holds details about calls to the GetHostVgpuMode method. + GetHostVgpuMode []struct { + } + // GetIndex holds details about calls to the GetIndex method. + GetIndex []struct { + } + // GetInforomConfigurationChecksum holds details about calls to the GetInforomConfigurationChecksum method. + GetInforomConfigurationChecksum []struct { + } + // GetInforomImageVersion holds details about calls to the GetInforomImageVersion method. + GetInforomImageVersion []struct { + } + // GetInforomVersion holds details about calls to the GetInforomVersion method. + GetInforomVersion []struct { + // InforomObject is the inforomObject argument value. + InforomObject nvml.InforomObject + } + // GetIrqNum holds details about calls to the GetIrqNum method. + GetIrqNum []struct { + } + // GetJpgUtilization holds details about calls to the GetJpgUtilization method. + GetJpgUtilization []struct { + } + // GetLastBBXFlushTime holds details about calls to the GetLastBBXFlushTime method. + GetLastBBXFlushTime []struct { + } + // GetMPSComputeRunningProcesses holds details about calls to the GetMPSComputeRunningProcesses method. + GetMPSComputeRunningProcesses []struct { + } + // GetMarginTemperature holds details about calls to the GetMarginTemperature method. + GetMarginTemperature []struct { + } + // GetMaxClockInfo holds details about calls to the GetMaxClockInfo method. + GetMaxClockInfo []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // GetMaxCustomerBoostClock holds details about calls to the GetMaxCustomerBoostClock method. + GetMaxCustomerBoostClock []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // GetMaxMigDeviceCount holds details about calls to the GetMaxMigDeviceCount method. + GetMaxMigDeviceCount []struct { + } + // GetMaxPcieLinkGeneration holds details about calls to the GetMaxPcieLinkGeneration method. + GetMaxPcieLinkGeneration []struct { + } + // GetMaxPcieLinkWidth holds details about calls to the GetMaxPcieLinkWidth method. + GetMaxPcieLinkWidth []struct { + } + // GetMemClkMinMaxVfOffset holds details about calls to the GetMemClkMinMaxVfOffset method. + GetMemClkMinMaxVfOffset []struct { + } + // GetMemClkVfOffset holds details about calls to the GetMemClkVfOffset method. + GetMemClkVfOffset []struct { + } + // GetMemoryAffinity holds details about calls to the GetMemoryAffinity method. + GetMemoryAffinity []struct { + // N is the n argument value. + N int + // AffinityScope is the affinityScope argument value. + AffinityScope nvml.AffinityScope + } + // GetMemoryBusWidth holds details about calls to the GetMemoryBusWidth method. + GetMemoryBusWidth []struct { + } + // GetMemoryErrorCounter holds details about calls to the GetMemoryErrorCounter method. + GetMemoryErrorCounter []struct { + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + // MemoryLocation is the memoryLocation argument value. + MemoryLocation nvml.MemoryLocation + } + // GetMemoryInfo holds details about calls to the GetMemoryInfo method. + GetMemoryInfo []struct { + } + // GetMemoryInfo_v2 holds details about calls to the GetMemoryInfo_v2 method. + GetMemoryInfo_v2 []struct { + } + // GetMigDeviceHandleByIndex holds details about calls to the GetMigDeviceHandleByIndex method. + GetMigDeviceHandleByIndex []struct { + // N is the n argument value. + N int + } + // GetMigMode holds details about calls to the GetMigMode method. + GetMigMode []struct { + } + // GetMinMaxClockOfPState holds details about calls to the GetMinMaxClockOfPState method. + GetMinMaxClockOfPState []struct { + // ClockType is the clockType argument value. + ClockType nvml.ClockType + // Pstates is the pstates argument value. + Pstates nvml.Pstates + } + // GetMinMaxFanSpeed holds details about calls to the GetMinMaxFanSpeed method. + GetMinMaxFanSpeed []struct { + } + // GetMinorNumber holds details about calls to the GetMinorNumber method. + GetMinorNumber []struct { + } + // GetModuleId holds details about calls to the GetModuleId method. + GetModuleId []struct { + } + // GetMultiGpuBoard holds details about calls to the GetMultiGpuBoard method. + GetMultiGpuBoard []struct { + } + // GetName holds details about calls to the GetName method. + GetName []struct { + } + // GetNumFans holds details about calls to the GetNumFans method. + GetNumFans []struct { + } + // GetNumGpuCores holds details about calls to the GetNumGpuCores method. + GetNumGpuCores []struct { + } + // GetNumaNodeId holds details about calls to the GetNumaNodeId method. + GetNumaNodeId []struct { + } + // GetNvLinkCapability holds details about calls to the GetNvLinkCapability method. + GetNvLinkCapability []struct { + // N is the n argument value. + N int + // NvLinkCapability is the nvLinkCapability argument value. + NvLinkCapability nvml.NvLinkCapability + } + // GetNvLinkErrorCounter holds details about calls to the GetNvLinkErrorCounter method. + GetNvLinkErrorCounter []struct { + // N is the n argument value. + N int + // NvLinkErrorCounter is the nvLinkErrorCounter argument value. + NvLinkErrorCounter nvml.NvLinkErrorCounter + } + // GetNvLinkInfo holds details about calls to the GetNvLinkInfo method. + GetNvLinkInfo []struct { + } + // GetNvLinkRemoteDeviceType holds details about calls to the GetNvLinkRemoteDeviceType method. + GetNvLinkRemoteDeviceType []struct { + // N is the n argument value. + N int + } + // GetNvLinkRemotePciInfo holds details about calls to the GetNvLinkRemotePciInfo method. + GetNvLinkRemotePciInfo []struct { + // N is the n argument value. + N int + } + // GetNvLinkState holds details about calls to the GetNvLinkState method. + GetNvLinkState []struct { + // N is the n argument value. + N int + } + // GetNvLinkUtilizationControl holds details about calls to the GetNvLinkUtilizationControl method. + GetNvLinkUtilizationControl []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GetNvLinkUtilizationCounter holds details about calls to the GetNvLinkUtilizationCounter method. + GetNvLinkUtilizationCounter []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GetNvLinkVersion holds details about calls to the GetNvLinkVersion method. + GetNvLinkVersion []struct { + // N is the n argument value. + N int + } + // GetNvlinkBwMode holds details about calls to the GetNvlinkBwMode method. + GetNvlinkBwMode []struct { + } + // GetNvlinkSupportedBwModes holds details about calls to the GetNvlinkSupportedBwModes method. + GetNvlinkSupportedBwModes []struct { + } + // GetOfaUtilization holds details about calls to the GetOfaUtilization method. + GetOfaUtilization []struct { + } + // GetP2PStatus holds details about calls to the GetP2PStatus method. + GetP2PStatus []struct { + // Device is the device argument value. + Device nvml.Device + // GpuP2PCapsIndex is the gpuP2PCapsIndex argument value. + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + } + // GetPciInfo holds details about calls to the GetPciInfo method. + GetPciInfo []struct { + } + // GetPciInfoExt holds details about calls to the GetPciInfoExt method. + GetPciInfoExt []struct { + } + // GetPcieLinkMaxSpeed holds details about calls to the GetPcieLinkMaxSpeed method. + GetPcieLinkMaxSpeed []struct { + } + // GetPcieReplayCounter holds details about calls to the GetPcieReplayCounter method. + GetPcieReplayCounter []struct { + } + // GetPcieSpeed holds details about calls to the GetPcieSpeed method. + GetPcieSpeed []struct { + } + // GetPcieThroughput holds details about calls to the GetPcieThroughput method. + GetPcieThroughput []struct { + // PcieUtilCounter is the pcieUtilCounter argument value. + PcieUtilCounter nvml.PcieUtilCounter + } + // GetPdi holds details about calls to the GetPdi method. + GetPdi []struct { + } + // GetPerformanceModes holds details about calls to the GetPerformanceModes method. + GetPerformanceModes []struct { + } + // GetPerformanceState holds details about calls to the GetPerformanceState method. + GetPerformanceState []struct { + } + // GetPersistenceMode holds details about calls to the GetPersistenceMode method. + GetPersistenceMode []struct { + } + // GetPgpuMetadataString holds details about calls to the GetPgpuMetadataString method. + GetPgpuMetadataString []struct { + } + // GetPlatformInfo holds details about calls to the GetPlatformInfo method. + GetPlatformInfo []struct { + } + // GetPowerManagementDefaultLimit holds details about calls to the GetPowerManagementDefaultLimit method. + GetPowerManagementDefaultLimit []struct { + } + // GetPowerManagementLimit holds details about calls to the GetPowerManagementLimit method. + GetPowerManagementLimit []struct { + } + // GetPowerManagementLimitConstraints holds details about calls to the GetPowerManagementLimitConstraints method. + GetPowerManagementLimitConstraints []struct { + } + // GetPowerManagementMode holds details about calls to the GetPowerManagementMode method. + GetPowerManagementMode []struct { + } + // GetPowerMizerMode_v1 holds details about calls to the GetPowerMizerMode_v1 method. + GetPowerMizerMode_v1 []struct { + } + // GetPowerSource holds details about calls to the GetPowerSource method. + GetPowerSource []struct { + } + // GetPowerState holds details about calls to the GetPowerState method. + GetPowerState []struct { + } + // GetPowerUsage holds details about calls to the GetPowerUsage method. + GetPowerUsage []struct { + } + // GetProcessUtilization holds details about calls to the GetProcessUtilization method. + GetProcessUtilization []struct { + // V is the v argument value. + V uint64 + } + // GetProcessesUtilizationInfo holds details about calls to the GetProcessesUtilizationInfo method. + GetProcessesUtilizationInfo []struct { + } + // GetRemappedRows holds details about calls to the GetRemappedRows method. + GetRemappedRows []struct { + } + // GetRepairStatus holds details about calls to the GetRepairStatus method. + GetRepairStatus []struct { + } + // GetRetiredPages holds details about calls to the GetRetiredPages method. + GetRetiredPages []struct { + // PageRetirementCause is the pageRetirementCause argument value. + PageRetirementCause nvml.PageRetirementCause + } + // GetRetiredPagesPendingStatus holds details about calls to the GetRetiredPagesPendingStatus method. + GetRetiredPagesPendingStatus []struct { + } + // GetRetiredPages_v2 holds details about calls to the GetRetiredPages_v2 method. + GetRetiredPages_v2 []struct { + // PageRetirementCause is the pageRetirementCause argument value. + PageRetirementCause nvml.PageRetirementCause + } + // GetRowRemapperHistogram holds details about calls to the GetRowRemapperHistogram method. + GetRowRemapperHistogram []struct { + } + // GetRunningProcessDetailList holds details about calls to the GetRunningProcessDetailList method. + GetRunningProcessDetailList []struct { + } + // GetSamples holds details about calls to the GetSamples method. + GetSamples []struct { + // SamplingType is the samplingType argument value. + SamplingType nvml.SamplingType + // V is the v argument value. + V uint64 + } + // GetSerial holds details about calls to the GetSerial method. + GetSerial []struct { + } + // GetSramEccErrorStatus holds details about calls to the GetSramEccErrorStatus method. + GetSramEccErrorStatus []struct { + } + // GetSramUniqueUncorrectedEccErrorCounts holds details about calls to the GetSramUniqueUncorrectedEccErrorCounts method. + GetSramUniqueUncorrectedEccErrorCounts []struct { + // EccSramUniqueUncorrectedErrorCounts is the eccSramUniqueUncorrectedErrorCounts argument value. + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + } + // GetSupportedClocksEventReasons holds details about calls to the GetSupportedClocksEventReasons method. + GetSupportedClocksEventReasons []struct { + } + // GetSupportedClocksThrottleReasons holds details about calls to the GetSupportedClocksThrottleReasons method. + GetSupportedClocksThrottleReasons []struct { + } + // GetSupportedEventTypes holds details about calls to the GetSupportedEventTypes method. + GetSupportedEventTypes []struct { + } + // GetSupportedGraphicsClocks holds details about calls to the GetSupportedGraphicsClocks method. + GetSupportedGraphicsClocks []struct { + // N is the n argument value. + N int + } + // GetSupportedMemoryClocks holds details about calls to the GetSupportedMemoryClocks method. + GetSupportedMemoryClocks []struct { + } + // GetSupportedPerformanceStates holds details about calls to the GetSupportedPerformanceStates method. + GetSupportedPerformanceStates []struct { + } + // GetSupportedVgpus holds details about calls to the GetSupportedVgpus method. + GetSupportedVgpus []struct { + } + // GetTargetFanSpeed holds details about calls to the GetTargetFanSpeed method. + GetTargetFanSpeed []struct { + // N is the n argument value. + N int + } + // GetTemperature holds details about calls to the GetTemperature method. + GetTemperature []struct { + // TemperatureSensors is the temperatureSensors argument value. + TemperatureSensors nvml.TemperatureSensors + } + // GetTemperatureThreshold holds details about calls to the GetTemperatureThreshold method. + GetTemperatureThreshold []struct { + // TemperatureThresholds is the temperatureThresholds argument value. + TemperatureThresholds nvml.TemperatureThresholds + } + // GetTemperatureV holds details about calls to the GetTemperatureV method. + GetTemperatureV []struct { + } + // GetThermalSettings holds details about calls to the GetThermalSettings method. + GetThermalSettings []struct { + // V is the v argument value. + V uint32 + } + // GetTopologyCommonAncestor holds details about calls to the GetTopologyCommonAncestor method. + GetTopologyCommonAncestor []struct { + // Device is the device argument value. + Device nvml.Device + } + // GetTopologyNearestGpus holds details about calls to the GetTopologyNearestGpus method. + GetTopologyNearestGpus []struct { + // GpuTopologyLevel is the gpuTopologyLevel argument value. + GpuTopologyLevel nvml.GpuTopologyLevel + } + // GetTotalEccErrors holds details about calls to the GetTotalEccErrors method. + GetTotalEccErrors []struct { + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // GetTotalEnergyConsumption holds details about calls to the GetTotalEnergyConsumption method. + GetTotalEnergyConsumption []struct { + } + // GetUUID holds details about calls to the GetUUID method. + GetUUID []struct { + } + // GetUtilizationRates holds details about calls to the GetUtilizationRates method. + GetUtilizationRates []struct { + } + // GetVbiosVersion holds details about calls to the GetVbiosVersion method. + GetVbiosVersion []struct { + } + // GetVgpuCapabilities holds details about calls to the GetVgpuCapabilities method. + GetVgpuCapabilities []struct { + // DeviceVgpuCapability is the deviceVgpuCapability argument value. + DeviceVgpuCapability nvml.DeviceVgpuCapability + } + // GetVgpuHeterogeneousMode holds details about calls to the GetVgpuHeterogeneousMode method. + GetVgpuHeterogeneousMode []struct { + } + // GetVgpuInstancesUtilizationInfo holds details about calls to the GetVgpuInstancesUtilizationInfo method. + GetVgpuInstancesUtilizationInfo []struct { + } + // GetVgpuMetadata holds details about calls to the GetVgpuMetadata method. + GetVgpuMetadata []struct { + } + // GetVgpuProcessUtilization holds details about calls to the GetVgpuProcessUtilization method. + GetVgpuProcessUtilization []struct { + // V is the v argument value. + V uint64 + } + // GetVgpuProcessesUtilizationInfo holds details about calls to the GetVgpuProcessesUtilizationInfo method. + GetVgpuProcessesUtilizationInfo []struct { + } + // GetVgpuSchedulerCapabilities holds details about calls to the GetVgpuSchedulerCapabilities method. + GetVgpuSchedulerCapabilities []struct { + } + // GetVgpuSchedulerLog holds details about calls to the GetVgpuSchedulerLog method. + GetVgpuSchedulerLog []struct { + } + // GetVgpuSchedulerState holds details about calls to the GetVgpuSchedulerState method. + GetVgpuSchedulerState []struct { + } + // GetVgpuTypeCreatablePlacements holds details about calls to the GetVgpuTypeCreatablePlacements method. + GetVgpuTypeCreatablePlacements []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // GetVgpuTypeSupportedPlacements holds details about calls to the GetVgpuTypeSupportedPlacements method. + GetVgpuTypeSupportedPlacements []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // GetVgpuUtilization holds details about calls to the GetVgpuUtilization method. + GetVgpuUtilization []struct { + // V is the v argument value. + V uint64 + } + // GetViolationStatus holds details about calls to the GetViolationStatus method. + GetViolationStatus []struct { + // PerfPolicyType is the perfPolicyType argument value. + PerfPolicyType nvml.PerfPolicyType + } + // GetVirtualizationMode holds details about calls to the GetVirtualizationMode method. + GetVirtualizationMode []struct { + } + // GpmMigSampleGet holds details about calls to the GpmMigSampleGet method. + GpmMigSampleGet []struct { + // N is the n argument value. + N int + // GpmSample is the gpmSample argument value. + GpmSample nvml.GpmSample + } + // GpmQueryDeviceSupport holds details about calls to the GpmQueryDeviceSupport method. + GpmQueryDeviceSupport []struct { + } + // GpmQueryDeviceSupportV holds details about calls to the GpmQueryDeviceSupportV method. + GpmQueryDeviceSupportV []struct { + } + // GpmQueryIfStreamingEnabled holds details about calls to the GpmQueryIfStreamingEnabled method. + GpmQueryIfStreamingEnabled []struct { + } + // GpmSampleGet holds details about calls to the GpmSampleGet method. + GpmSampleGet []struct { + // GpmSample is the gpmSample argument value. + GpmSample nvml.GpmSample + } + // GpmSetStreamingEnabled holds details about calls to the GpmSetStreamingEnabled method. + GpmSetStreamingEnabled []struct { + // V is the v argument value. + V uint32 + } + // IsMigDeviceHandle holds details about calls to the IsMigDeviceHandle method. + IsMigDeviceHandle []struct { + } + // OnSameBoard holds details about calls to the OnSameBoard method. + OnSameBoard []struct { + // Device is the device argument value. + Device nvml.Device + } + // PowerSmoothingActivatePresetProfile holds details about calls to the PowerSmoothingActivatePresetProfile method. + PowerSmoothingActivatePresetProfile []struct { + // PowerSmoothingProfile is the powerSmoothingProfile argument value. + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + // PowerSmoothingSetState holds details about calls to the PowerSmoothingSetState method. + PowerSmoothingSetState []struct { + // PowerSmoothingState is the powerSmoothingState argument value. + PowerSmoothingState *nvml.PowerSmoothingState + } + // PowerSmoothingUpdatePresetProfileParam holds details about calls to the PowerSmoothingUpdatePresetProfileParam method. + PowerSmoothingUpdatePresetProfileParam []struct { + // PowerSmoothingProfile is the powerSmoothingProfile argument value. + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + // ReadWritePRM_v1 holds details about calls to the ReadWritePRM_v1 method. + ReadWritePRM_v1 []struct { + // PRMTLV_v1 is the pRMTLV_v1 argument value. + PRMTLV_v1 *nvml.PRMTLV_v1 + } + // RegisterEvents holds details about calls to the RegisterEvents method. + RegisterEvents []struct { + // V is the v argument value. + V uint64 + // EventSet is the eventSet argument value. + EventSet nvml.EventSet + } + // ResetApplicationsClocks holds details about calls to the ResetApplicationsClocks method. + ResetApplicationsClocks []struct { + } + // ResetGpuLockedClocks holds details about calls to the ResetGpuLockedClocks method. + ResetGpuLockedClocks []struct { + } + // ResetMemoryLockedClocks holds details about calls to the ResetMemoryLockedClocks method. + ResetMemoryLockedClocks []struct { + } + // ResetNvLinkErrorCounters holds details about calls to the ResetNvLinkErrorCounters method. + ResetNvLinkErrorCounters []struct { + // N is the n argument value. + N int + } + // ResetNvLinkUtilizationCounter holds details about calls to the ResetNvLinkUtilizationCounter method. + ResetNvLinkUtilizationCounter []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // SetAPIRestriction holds details about calls to the SetAPIRestriction method. + SetAPIRestriction []struct { + // RestrictedAPI is the restrictedAPI argument value. + RestrictedAPI nvml.RestrictedAPI + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetAccountingMode holds details about calls to the SetAccountingMode method. + SetAccountingMode []struct { + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetApplicationsClocks holds details about calls to the SetApplicationsClocks method. + SetApplicationsClocks []struct { + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // SetAutoBoostedClocksEnabled holds details about calls to the SetAutoBoostedClocksEnabled method. + SetAutoBoostedClocksEnabled []struct { + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetClockOffsets holds details about calls to the SetClockOffsets method. + SetClockOffsets []struct { + // ClockOffset is the clockOffset argument value. + ClockOffset nvml.ClockOffset + } + // SetComputeMode holds details about calls to the SetComputeMode method. + SetComputeMode []struct { + // ComputeMode is the computeMode argument value. + ComputeMode nvml.ComputeMode + } + // SetConfComputeUnprotectedMemSize holds details about calls to the SetConfComputeUnprotectedMemSize method. + SetConfComputeUnprotectedMemSize []struct { + // V is the v argument value. + V uint64 + } + // SetCpuAffinity holds details about calls to the SetCpuAffinity method. + SetCpuAffinity []struct { + } + // SetDefaultAutoBoostedClocksEnabled holds details about calls to the SetDefaultAutoBoostedClocksEnabled method. + SetDefaultAutoBoostedClocksEnabled []struct { + // EnableState is the enableState argument value. + EnableState nvml.EnableState + // V is the v argument value. + V uint32 + } + // SetDefaultFanSpeed_v2 holds details about calls to the SetDefaultFanSpeed_v2 method. + SetDefaultFanSpeed_v2 []struct { + // N is the n argument value. + N int + } + // SetDramEncryptionMode holds details about calls to the SetDramEncryptionMode method. + SetDramEncryptionMode []struct { + // DramEncryptionInfo is the dramEncryptionInfo argument value. + DramEncryptionInfo *nvml.DramEncryptionInfo + } + // SetDriverModel holds details about calls to the SetDriverModel method. + SetDriverModel []struct { + // DriverModel is the driverModel argument value. + DriverModel nvml.DriverModel + // V is the v argument value. + V uint32 + } + // SetEccMode holds details about calls to the SetEccMode method. + SetEccMode []struct { + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetFanControlPolicy holds details about calls to the SetFanControlPolicy method. + SetFanControlPolicy []struct { + // N is the n argument value. + N int + // FanControlPolicy is the fanControlPolicy argument value. + FanControlPolicy nvml.FanControlPolicy + } + // SetFanSpeed_v2 holds details about calls to the SetFanSpeed_v2 method. + SetFanSpeed_v2 []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // SetGpcClkVfOffset holds details about calls to the SetGpcClkVfOffset method. + SetGpcClkVfOffset []struct { + // N is the n argument value. + N int + } + // SetGpuLockedClocks holds details about calls to the SetGpuLockedClocks method. + SetGpuLockedClocks []struct { + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // SetGpuOperationMode holds details about calls to the SetGpuOperationMode method. + SetGpuOperationMode []struct { + // GpuOperationMode is the gpuOperationMode argument value. + GpuOperationMode nvml.GpuOperationMode + } + // SetMemClkVfOffset holds details about calls to the SetMemClkVfOffset method. + SetMemClkVfOffset []struct { + // N is the n argument value. + N int + } + // SetMemoryLockedClocks holds details about calls to the SetMemoryLockedClocks method. + SetMemoryLockedClocks []struct { + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // SetMigMode holds details about calls to the SetMigMode method. + SetMigMode []struct { + // N is the n argument value. + N int + } + // SetNvLinkDeviceLowPowerThreshold holds details about calls to the SetNvLinkDeviceLowPowerThreshold method. + SetNvLinkDeviceLowPowerThreshold []struct { + // NvLinkPowerThres is the nvLinkPowerThres argument value. + NvLinkPowerThres *nvml.NvLinkPowerThres + } + // SetNvLinkUtilizationControl holds details about calls to the SetNvLinkUtilizationControl method. + SetNvLinkUtilizationControl []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + // NvLinkUtilizationControl is the nvLinkUtilizationControl argument value. + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + // B is the b argument value. + B bool + } + // SetNvlinkBwMode holds details about calls to the SetNvlinkBwMode method. + SetNvlinkBwMode []struct { + // NvlinkSetBwMode is the nvlinkSetBwMode argument value. + NvlinkSetBwMode *nvml.NvlinkSetBwMode + } + // SetPersistenceMode holds details about calls to the SetPersistenceMode method. + SetPersistenceMode []struct { + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetPowerManagementLimit holds details about calls to the SetPowerManagementLimit method. + SetPowerManagementLimit []struct { + // V is the v argument value. + V uint32 + } + // SetPowerManagementLimit_v2 holds details about calls to the SetPowerManagementLimit_v2 method. + SetPowerManagementLimit_v2 []struct { + // PowerValue_v2 is the powerValue_v2 argument value. + PowerValue_v2 *nvml.PowerValue_v2 + } + // SetTemperatureThreshold holds details about calls to the SetTemperatureThreshold method. + SetTemperatureThreshold []struct { + // TemperatureThresholds is the temperatureThresholds argument value. + TemperatureThresholds nvml.TemperatureThresholds + // N is the n argument value. + N int + } + // SetVgpuCapabilities holds details about calls to the SetVgpuCapabilities method. + SetVgpuCapabilities []struct { + // DeviceVgpuCapability is the deviceVgpuCapability argument value. + DeviceVgpuCapability nvml.DeviceVgpuCapability + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // SetVgpuHeterogeneousMode holds details about calls to the SetVgpuHeterogeneousMode method. + SetVgpuHeterogeneousMode []struct { + // VgpuHeterogeneousMode is the vgpuHeterogeneousMode argument value. + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + } + // SetVgpuSchedulerState holds details about calls to the SetVgpuSchedulerState method. + SetVgpuSchedulerState []struct { + // VgpuSchedulerSetState is the vgpuSchedulerSetState argument value. + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + } + // SetVirtualizationMode holds details about calls to the SetVirtualizationMode method. + SetVirtualizationMode []struct { + // GpuVirtualizationMode is the gpuVirtualizationMode argument value. + GpuVirtualizationMode nvml.GpuVirtualizationMode + } + // ValidateInforom holds details about calls to the ValidateInforom method. + ValidateInforom []struct { + } + // VgpuTypeGetMaxInstances holds details about calls to the VgpuTypeGetMaxInstances method. + VgpuTypeGetMaxInstances []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // WorkloadPowerProfileClearRequestedProfiles holds details about calls to the WorkloadPowerProfileClearRequestedProfiles method. + WorkloadPowerProfileClearRequestedProfiles []struct { + // WorkloadPowerProfileRequestedProfiles is the workloadPowerProfileRequestedProfiles argument value. + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + // WorkloadPowerProfileGetCurrentProfiles holds details about calls to the WorkloadPowerProfileGetCurrentProfiles method. + WorkloadPowerProfileGetCurrentProfiles []struct { + } + // WorkloadPowerProfileGetProfilesInfo holds details about calls to the WorkloadPowerProfileGetProfilesInfo method. + WorkloadPowerProfileGetProfilesInfo []struct { + } + // WorkloadPowerProfileSetRequestedProfiles holds details about calls to the WorkloadPowerProfileSetRequestedProfiles method. + WorkloadPowerProfileSetRequestedProfiles []struct { + // WorkloadPowerProfileRequestedProfiles is the workloadPowerProfileRequestedProfiles argument value. + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + } + lockClearAccountingPids sync.RWMutex + lockClearCpuAffinity sync.RWMutex + lockClearEccErrorCounts sync.RWMutex + lockClearFieldValues sync.RWMutex + lockCreateGpuInstance sync.RWMutex + lockCreateGpuInstanceWithPlacement sync.RWMutex + lockFreezeNvLinkUtilizationCounter sync.RWMutex + lockGetAPIRestriction sync.RWMutex + lockGetAccountingBufferSize sync.RWMutex + lockGetAccountingMode sync.RWMutex + lockGetAccountingPids sync.RWMutex + lockGetAccountingStats sync.RWMutex + lockGetActiveVgpus sync.RWMutex + lockGetAdaptiveClockInfoStatus sync.RWMutex + lockGetAddressingMode sync.RWMutex + lockGetApplicationsClock sync.RWMutex + lockGetArchitecture sync.RWMutex + lockGetAttributes sync.RWMutex + lockGetAutoBoostedClocksEnabled sync.RWMutex + lockGetBAR1MemoryInfo sync.RWMutex + lockGetBoardId sync.RWMutex + lockGetBoardPartNumber sync.RWMutex + lockGetBrand sync.RWMutex + lockGetBridgeChipInfo sync.RWMutex + lockGetBusType sync.RWMutex + lockGetC2cModeInfoV sync.RWMutex + lockGetCapabilities sync.RWMutex + lockGetClkMonStatus sync.RWMutex + lockGetClock sync.RWMutex + lockGetClockInfo sync.RWMutex + lockGetClockOffsets sync.RWMutex + lockGetComputeInstanceId sync.RWMutex + lockGetComputeMode sync.RWMutex + lockGetComputeRunningProcesses sync.RWMutex + lockGetConfComputeGpuAttestationReport sync.RWMutex + lockGetConfComputeGpuCertificate sync.RWMutex + lockGetConfComputeMemSizeInfo sync.RWMutex + lockGetConfComputeProtectedMemoryUsage sync.RWMutex + lockGetCoolerInfo sync.RWMutex + lockGetCpuAffinity sync.RWMutex + lockGetCpuAffinityWithinScope sync.RWMutex + lockGetCreatableVgpus sync.RWMutex + lockGetCudaComputeCapability sync.RWMutex + lockGetCurrPcieLinkGeneration sync.RWMutex + lockGetCurrPcieLinkWidth sync.RWMutex + lockGetCurrentClockFreqs sync.RWMutex + lockGetCurrentClocksEventReasons sync.RWMutex + lockGetCurrentClocksThrottleReasons sync.RWMutex + lockGetDecoderUtilization sync.RWMutex + lockGetDefaultApplicationsClock sync.RWMutex + lockGetDefaultEccMode sync.RWMutex + lockGetDetailedEccErrors sync.RWMutex + lockGetDeviceHandleFromMigDeviceHandle sync.RWMutex + lockGetDisplayActive sync.RWMutex + lockGetDisplayMode sync.RWMutex + lockGetDramEncryptionMode sync.RWMutex + lockGetDriverModel sync.RWMutex + lockGetDriverModel_v2 sync.RWMutex + lockGetDynamicPstatesInfo sync.RWMutex + lockGetEccMode sync.RWMutex + lockGetEncoderCapacity sync.RWMutex + lockGetEncoderSessions sync.RWMutex + lockGetEncoderStats sync.RWMutex + lockGetEncoderUtilization sync.RWMutex + lockGetEnforcedPowerLimit sync.RWMutex + lockGetFBCSessions sync.RWMutex + lockGetFBCStats sync.RWMutex + lockGetFanControlPolicy_v2 sync.RWMutex + lockGetFanSpeed sync.RWMutex + lockGetFanSpeedRPM sync.RWMutex + lockGetFanSpeed_v2 sync.RWMutex + lockGetFieldValues sync.RWMutex + lockGetGpcClkMinMaxVfOffset sync.RWMutex + lockGetGpcClkVfOffset sync.RWMutex + lockGetGpuFabricInfo sync.RWMutex + lockGetGpuFabricInfoV sync.RWMutex + lockGetGpuInstanceById sync.RWMutex + lockGetGpuInstanceId sync.RWMutex + lockGetGpuInstancePossiblePlacements sync.RWMutex + lockGetGpuInstanceProfileInfo sync.RWMutex + lockGetGpuInstanceProfileInfoByIdV sync.RWMutex + lockGetGpuInstanceProfileInfoV sync.RWMutex + lockGetGpuInstanceRemainingCapacity sync.RWMutex + lockGetGpuInstances sync.RWMutex + lockGetGpuMaxPcieLinkGeneration sync.RWMutex + lockGetGpuOperationMode sync.RWMutex + lockGetGraphicsRunningProcesses sync.RWMutex + lockGetGridLicensableFeatures sync.RWMutex + lockGetGspFirmwareMode sync.RWMutex + lockGetGspFirmwareVersion sync.RWMutex + lockGetHostVgpuMode sync.RWMutex + lockGetIndex sync.RWMutex + lockGetInforomConfigurationChecksum sync.RWMutex + lockGetInforomImageVersion sync.RWMutex + lockGetInforomVersion sync.RWMutex + lockGetIrqNum sync.RWMutex + lockGetJpgUtilization sync.RWMutex + lockGetLastBBXFlushTime sync.RWMutex + lockGetMPSComputeRunningProcesses sync.RWMutex + lockGetMarginTemperature sync.RWMutex + lockGetMaxClockInfo sync.RWMutex + lockGetMaxCustomerBoostClock sync.RWMutex + lockGetMaxMigDeviceCount sync.RWMutex + lockGetMaxPcieLinkGeneration sync.RWMutex + lockGetMaxPcieLinkWidth sync.RWMutex + lockGetMemClkMinMaxVfOffset sync.RWMutex + lockGetMemClkVfOffset sync.RWMutex + lockGetMemoryAffinity sync.RWMutex + lockGetMemoryBusWidth sync.RWMutex + lockGetMemoryErrorCounter sync.RWMutex + lockGetMemoryInfo sync.RWMutex + lockGetMemoryInfo_v2 sync.RWMutex + lockGetMigDeviceHandleByIndex sync.RWMutex + lockGetMigMode sync.RWMutex + lockGetMinMaxClockOfPState sync.RWMutex + lockGetMinMaxFanSpeed sync.RWMutex + lockGetMinorNumber sync.RWMutex + lockGetModuleId sync.RWMutex + lockGetMultiGpuBoard sync.RWMutex + lockGetName sync.RWMutex + lockGetNumFans sync.RWMutex + lockGetNumGpuCores sync.RWMutex + lockGetNumaNodeId sync.RWMutex + lockGetNvLinkCapability sync.RWMutex + lockGetNvLinkErrorCounter sync.RWMutex + lockGetNvLinkInfo sync.RWMutex + lockGetNvLinkRemoteDeviceType sync.RWMutex + lockGetNvLinkRemotePciInfo sync.RWMutex + lockGetNvLinkState sync.RWMutex + lockGetNvLinkUtilizationControl sync.RWMutex + lockGetNvLinkUtilizationCounter sync.RWMutex + lockGetNvLinkVersion sync.RWMutex + lockGetNvlinkBwMode sync.RWMutex + lockGetNvlinkSupportedBwModes sync.RWMutex + lockGetOfaUtilization sync.RWMutex + lockGetP2PStatus sync.RWMutex + lockGetPciInfo sync.RWMutex + lockGetPciInfoExt sync.RWMutex + lockGetPcieLinkMaxSpeed sync.RWMutex + lockGetPcieReplayCounter sync.RWMutex + lockGetPcieSpeed sync.RWMutex + lockGetPcieThroughput sync.RWMutex + lockGetPdi sync.RWMutex + lockGetPerformanceModes sync.RWMutex + lockGetPerformanceState sync.RWMutex + lockGetPersistenceMode sync.RWMutex + lockGetPgpuMetadataString sync.RWMutex + lockGetPlatformInfo sync.RWMutex + lockGetPowerManagementDefaultLimit sync.RWMutex + lockGetPowerManagementLimit sync.RWMutex + lockGetPowerManagementLimitConstraints sync.RWMutex + lockGetPowerManagementMode sync.RWMutex + lockGetPowerMizerMode_v1 sync.RWMutex + lockGetPowerSource sync.RWMutex + lockGetPowerState sync.RWMutex + lockGetPowerUsage sync.RWMutex + lockGetProcessUtilization sync.RWMutex + lockGetProcessesUtilizationInfo sync.RWMutex + lockGetRemappedRows sync.RWMutex + lockGetRepairStatus sync.RWMutex + lockGetRetiredPages sync.RWMutex + lockGetRetiredPagesPendingStatus sync.RWMutex + lockGetRetiredPages_v2 sync.RWMutex + lockGetRowRemapperHistogram sync.RWMutex + lockGetRunningProcessDetailList sync.RWMutex + lockGetSamples sync.RWMutex + lockGetSerial sync.RWMutex + lockGetSramEccErrorStatus sync.RWMutex + lockGetSramUniqueUncorrectedEccErrorCounts sync.RWMutex + lockGetSupportedClocksEventReasons sync.RWMutex + lockGetSupportedClocksThrottleReasons sync.RWMutex + lockGetSupportedEventTypes sync.RWMutex + lockGetSupportedGraphicsClocks sync.RWMutex + lockGetSupportedMemoryClocks sync.RWMutex + lockGetSupportedPerformanceStates sync.RWMutex + lockGetSupportedVgpus sync.RWMutex + lockGetTargetFanSpeed sync.RWMutex + lockGetTemperature sync.RWMutex + lockGetTemperatureThreshold sync.RWMutex + lockGetTemperatureV sync.RWMutex + lockGetThermalSettings sync.RWMutex + lockGetTopologyCommonAncestor sync.RWMutex + lockGetTopologyNearestGpus sync.RWMutex + lockGetTotalEccErrors sync.RWMutex + lockGetTotalEnergyConsumption sync.RWMutex + lockGetUUID sync.RWMutex + lockGetUtilizationRates sync.RWMutex + lockGetVbiosVersion sync.RWMutex + lockGetVgpuCapabilities sync.RWMutex + lockGetVgpuHeterogeneousMode sync.RWMutex + lockGetVgpuInstancesUtilizationInfo sync.RWMutex + lockGetVgpuMetadata sync.RWMutex + lockGetVgpuProcessUtilization sync.RWMutex + lockGetVgpuProcessesUtilizationInfo sync.RWMutex + lockGetVgpuSchedulerCapabilities sync.RWMutex + lockGetVgpuSchedulerLog sync.RWMutex + lockGetVgpuSchedulerState sync.RWMutex + lockGetVgpuTypeCreatablePlacements sync.RWMutex + lockGetVgpuTypeSupportedPlacements sync.RWMutex + lockGetVgpuUtilization sync.RWMutex + lockGetViolationStatus sync.RWMutex + lockGetVirtualizationMode sync.RWMutex + lockGpmMigSampleGet sync.RWMutex + lockGpmQueryDeviceSupport sync.RWMutex + lockGpmQueryDeviceSupportV sync.RWMutex + lockGpmQueryIfStreamingEnabled sync.RWMutex + lockGpmSampleGet sync.RWMutex + lockGpmSetStreamingEnabled sync.RWMutex + lockIsMigDeviceHandle sync.RWMutex + lockOnSameBoard sync.RWMutex + lockPowerSmoothingActivatePresetProfile sync.RWMutex + lockPowerSmoothingSetState sync.RWMutex + lockPowerSmoothingUpdatePresetProfileParam sync.RWMutex + lockReadWritePRM_v1 sync.RWMutex + lockRegisterEvents sync.RWMutex + lockResetApplicationsClocks sync.RWMutex + lockResetGpuLockedClocks sync.RWMutex + lockResetMemoryLockedClocks sync.RWMutex + lockResetNvLinkErrorCounters sync.RWMutex + lockResetNvLinkUtilizationCounter sync.RWMutex + lockSetAPIRestriction sync.RWMutex + lockSetAccountingMode sync.RWMutex + lockSetApplicationsClocks sync.RWMutex + lockSetAutoBoostedClocksEnabled sync.RWMutex + lockSetClockOffsets sync.RWMutex + lockSetComputeMode sync.RWMutex + lockSetConfComputeUnprotectedMemSize sync.RWMutex + lockSetCpuAffinity sync.RWMutex + lockSetDefaultAutoBoostedClocksEnabled sync.RWMutex + lockSetDefaultFanSpeed_v2 sync.RWMutex + lockSetDramEncryptionMode sync.RWMutex + lockSetDriverModel sync.RWMutex + lockSetEccMode sync.RWMutex + lockSetFanControlPolicy sync.RWMutex + lockSetFanSpeed_v2 sync.RWMutex + lockSetGpcClkVfOffset sync.RWMutex + lockSetGpuLockedClocks sync.RWMutex + lockSetGpuOperationMode sync.RWMutex + lockSetMemClkVfOffset sync.RWMutex + lockSetMemoryLockedClocks sync.RWMutex + lockSetMigMode sync.RWMutex + lockSetNvLinkDeviceLowPowerThreshold sync.RWMutex + lockSetNvLinkUtilizationControl sync.RWMutex + lockSetNvlinkBwMode sync.RWMutex + lockSetPersistenceMode sync.RWMutex + lockSetPowerManagementLimit sync.RWMutex + lockSetPowerManagementLimit_v2 sync.RWMutex + lockSetTemperatureThreshold sync.RWMutex + lockSetVgpuCapabilities sync.RWMutex + lockSetVgpuHeterogeneousMode sync.RWMutex + lockSetVgpuSchedulerState sync.RWMutex + lockSetVirtualizationMode sync.RWMutex + lockValidateInforom sync.RWMutex + lockVgpuTypeGetMaxInstances sync.RWMutex + lockWorkloadPowerProfileClearRequestedProfiles sync.RWMutex + lockWorkloadPowerProfileGetCurrentProfiles sync.RWMutex + lockWorkloadPowerProfileGetProfilesInfo sync.RWMutex + lockWorkloadPowerProfileSetRequestedProfiles sync.RWMutex +} + +// ClearAccountingPids calls ClearAccountingPidsFunc. +func (mock *Device) ClearAccountingPids() nvml.Return { + if mock.ClearAccountingPidsFunc == nil { + panic("Device.ClearAccountingPidsFunc: method is nil but Device.ClearAccountingPids was just called") + } + callInfo := struct { + }{} + mock.lockClearAccountingPids.Lock() + mock.calls.ClearAccountingPids = append(mock.calls.ClearAccountingPids, callInfo) + mock.lockClearAccountingPids.Unlock() + return mock.ClearAccountingPidsFunc() +} + +// ClearAccountingPidsCalls gets all the calls that were made to ClearAccountingPids. +// Check the length with: +// +// len(mockedDevice.ClearAccountingPidsCalls()) +func (mock *Device) ClearAccountingPidsCalls() []struct { +} { + var calls []struct { + } + mock.lockClearAccountingPids.RLock() + calls = mock.calls.ClearAccountingPids + mock.lockClearAccountingPids.RUnlock() + return calls +} + +// ClearCpuAffinity calls ClearCpuAffinityFunc. +func (mock *Device) ClearCpuAffinity() nvml.Return { + if mock.ClearCpuAffinityFunc == nil { + panic("Device.ClearCpuAffinityFunc: method is nil but Device.ClearCpuAffinity was just called") + } + callInfo := struct { + }{} + mock.lockClearCpuAffinity.Lock() + mock.calls.ClearCpuAffinity = append(mock.calls.ClearCpuAffinity, callInfo) + mock.lockClearCpuAffinity.Unlock() + return mock.ClearCpuAffinityFunc() +} + +// ClearCpuAffinityCalls gets all the calls that were made to ClearCpuAffinity. +// Check the length with: +// +// len(mockedDevice.ClearCpuAffinityCalls()) +func (mock *Device) ClearCpuAffinityCalls() []struct { +} { + var calls []struct { + } + mock.lockClearCpuAffinity.RLock() + calls = mock.calls.ClearCpuAffinity + mock.lockClearCpuAffinity.RUnlock() + return calls +} + +// ClearEccErrorCounts calls ClearEccErrorCountsFunc. +func (mock *Device) ClearEccErrorCounts(eccCounterType nvml.EccCounterType) nvml.Return { + if mock.ClearEccErrorCountsFunc == nil { + panic("Device.ClearEccErrorCountsFunc: method is nil but Device.ClearEccErrorCounts was just called") + } + callInfo := struct { + EccCounterType nvml.EccCounterType + }{ + EccCounterType: eccCounterType, + } + mock.lockClearEccErrorCounts.Lock() + mock.calls.ClearEccErrorCounts = append(mock.calls.ClearEccErrorCounts, callInfo) + mock.lockClearEccErrorCounts.Unlock() + return mock.ClearEccErrorCountsFunc(eccCounterType) +} + +// ClearEccErrorCountsCalls gets all the calls that were made to ClearEccErrorCounts. +// Check the length with: +// +// len(mockedDevice.ClearEccErrorCountsCalls()) +func (mock *Device) ClearEccErrorCountsCalls() []struct { + EccCounterType nvml.EccCounterType +} { + var calls []struct { + EccCounterType nvml.EccCounterType + } + mock.lockClearEccErrorCounts.RLock() + calls = mock.calls.ClearEccErrorCounts + mock.lockClearEccErrorCounts.RUnlock() + return calls +} + +// ClearFieldValues calls ClearFieldValuesFunc. +func (mock *Device) ClearFieldValues(fieldValues []nvml.FieldValue) nvml.Return { + if mock.ClearFieldValuesFunc == nil { + panic("Device.ClearFieldValuesFunc: method is nil but Device.ClearFieldValues was just called") + } + callInfo := struct { + FieldValues []nvml.FieldValue + }{ + FieldValues: fieldValues, + } + mock.lockClearFieldValues.Lock() + mock.calls.ClearFieldValues = append(mock.calls.ClearFieldValues, callInfo) + mock.lockClearFieldValues.Unlock() + return mock.ClearFieldValuesFunc(fieldValues) +} + +// ClearFieldValuesCalls gets all the calls that were made to ClearFieldValues. +// Check the length with: +// +// len(mockedDevice.ClearFieldValuesCalls()) +func (mock *Device) ClearFieldValuesCalls() []struct { + FieldValues []nvml.FieldValue +} { + var calls []struct { + FieldValues []nvml.FieldValue + } + mock.lockClearFieldValues.RLock() + calls = mock.calls.ClearFieldValues + mock.lockClearFieldValues.RUnlock() + return calls +} + +// CreateGpuInstance calls CreateGpuInstanceFunc. +func (mock *Device) CreateGpuInstance(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) { + if mock.CreateGpuInstanceFunc == nil { + panic("Device.CreateGpuInstanceFunc: method is nil but Device.CreateGpuInstance was just called") + } + callInfo := struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockCreateGpuInstance.Lock() + mock.calls.CreateGpuInstance = append(mock.calls.CreateGpuInstance, callInfo) + mock.lockCreateGpuInstance.Unlock() + return mock.CreateGpuInstanceFunc(gpuInstanceProfileInfo) +} + +// CreateGpuInstanceCalls gets all the calls that were made to CreateGpuInstance. +// Check the length with: +// +// len(mockedDevice.CreateGpuInstanceCalls()) +func (mock *Device) CreateGpuInstanceCalls() []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockCreateGpuInstance.RLock() + calls = mock.calls.CreateGpuInstance + mock.lockCreateGpuInstance.RUnlock() + return calls +} + +// CreateGpuInstanceWithPlacement calls CreateGpuInstanceWithPlacementFunc. +func (mock *Device) CreateGpuInstanceWithPlacement(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) { + if mock.CreateGpuInstanceWithPlacementFunc == nil { + panic("Device.CreateGpuInstanceWithPlacementFunc: method is nil but Device.CreateGpuInstanceWithPlacement was just called") + } + callInfo := struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement + }{ + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + GpuInstancePlacement: gpuInstancePlacement, + } + mock.lockCreateGpuInstanceWithPlacement.Lock() + mock.calls.CreateGpuInstanceWithPlacement = append(mock.calls.CreateGpuInstanceWithPlacement, callInfo) + mock.lockCreateGpuInstanceWithPlacement.Unlock() + return mock.CreateGpuInstanceWithPlacementFunc(gpuInstanceProfileInfo, gpuInstancePlacement) +} + +// CreateGpuInstanceWithPlacementCalls gets all the calls that were made to CreateGpuInstanceWithPlacement. +// Check the length with: +// +// len(mockedDevice.CreateGpuInstanceWithPlacementCalls()) +func (mock *Device) CreateGpuInstanceWithPlacementCalls() []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement +} { + var calls []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement + } + mock.lockCreateGpuInstanceWithPlacement.RLock() + calls = mock.calls.CreateGpuInstanceWithPlacement + mock.lockCreateGpuInstanceWithPlacement.RUnlock() + return calls +} + +// FreezeNvLinkUtilizationCounter calls FreezeNvLinkUtilizationCounterFunc. +func (mock *Device) FreezeNvLinkUtilizationCounter(n1 int, n2 int, enableState nvml.EnableState) nvml.Return { + if mock.FreezeNvLinkUtilizationCounterFunc == nil { + panic("Device.FreezeNvLinkUtilizationCounterFunc: method is nil but Device.FreezeNvLinkUtilizationCounter was just called") + } + callInfo := struct { + N1 int + N2 int + EnableState nvml.EnableState + }{ + N1: n1, + N2: n2, + EnableState: enableState, + } + mock.lockFreezeNvLinkUtilizationCounter.Lock() + mock.calls.FreezeNvLinkUtilizationCounter = append(mock.calls.FreezeNvLinkUtilizationCounter, callInfo) + mock.lockFreezeNvLinkUtilizationCounter.Unlock() + return mock.FreezeNvLinkUtilizationCounterFunc(n1, n2, enableState) +} + +// FreezeNvLinkUtilizationCounterCalls gets all the calls that were made to FreezeNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedDevice.FreezeNvLinkUtilizationCounterCalls()) +func (mock *Device) FreezeNvLinkUtilizationCounterCalls() []struct { + N1 int + N2 int + EnableState nvml.EnableState +} { + var calls []struct { + N1 int + N2 int + EnableState nvml.EnableState + } + mock.lockFreezeNvLinkUtilizationCounter.RLock() + calls = mock.calls.FreezeNvLinkUtilizationCounter + mock.lockFreezeNvLinkUtilizationCounter.RUnlock() + return calls +} + +// GetAPIRestriction calls GetAPIRestrictionFunc. +func (mock *Device) GetAPIRestriction(restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) { + if mock.GetAPIRestrictionFunc == nil { + panic("Device.GetAPIRestrictionFunc: method is nil but Device.GetAPIRestriction was just called") + } + callInfo := struct { + RestrictedAPI nvml.RestrictedAPI + }{ + RestrictedAPI: restrictedAPI, + } + mock.lockGetAPIRestriction.Lock() + mock.calls.GetAPIRestriction = append(mock.calls.GetAPIRestriction, callInfo) + mock.lockGetAPIRestriction.Unlock() + return mock.GetAPIRestrictionFunc(restrictedAPI) +} + +// GetAPIRestrictionCalls gets all the calls that were made to GetAPIRestriction. +// Check the length with: +// +// len(mockedDevice.GetAPIRestrictionCalls()) +func (mock *Device) GetAPIRestrictionCalls() []struct { + RestrictedAPI nvml.RestrictedAPI +} { + var calls []struct { + RestrictedAPI nvml.RestrictedAPI + } + mock.lockGetAPIRestriction.RLock() + calls = mock.calls.GetAPIRestriction + mock.lockGetAPIRestriction.RUnlock() + return calls +} + +// GetAccountingBufferSize calls GetAccountingBufferSizeFunc. +func (mock *Device) GetAccountingBufferSize() (int, nvml.Return) { + if mock.GetAccountingBufferSizeFunc == nil { + panic("Device.GetAccountingBufferSizeFunc: method is nil but Device.GetAccountingBufferSize was just called") + } + callInfo := struct { + }{} + mock.lockGetAccountingBufferSize.Lock() + mock.calls.GetAccountingBufferSize = append(mock.calls.GetAccountingBufferSize, callInfo) + mock.lockGetAccountingBufferSize.Unlock() + return mock.GetAccountingBufferSizeFunc() +} + +// GetAccountingBufferSizeCalls gets all the calls that were made to GetAccountingBufferSize. +// Check the length with: +// +// len(mockedDevice.GetAccountingBufferSizeCalls()) +func (mock *Device) GetAccountingBufferSizeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAccountingBufferSize.RLock() + calls = mock.calls.GetAccountingBufferSize + mock.lockGetAccountingBufferSize.RUnlock() + return calls +} + +// GetAccountingMode calls GetAccountingModeFunc. +func (mock *Device) GetAccountingMode() (nvml.EnableState, nvml.Return) { + if mock.GetAccountingModeFunc == nil { + panic("Device.GetAccountingModeFunc: method is nil but Device.GetAccountingMode was just called") + } + callInfo := struct { + }{} + mock.lockGetAccountingMode.Lock() + mock.calls.GetAccountingMode = append(mock.calls.GetAccountingMode, callInfo) + mock.lockGetAccountingMode.Unlock() + return mock.GetAccountingModeFunc() +} + +// GetAccountingModeCalls gets all the calls that were made to GetAccountingMode. +// Check the length with: +// +// len(mockedDevice.GetAccountingModeCalls()) +func (mock *Device) GetAccountingModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAccountingMode.RLock() + calls = mock.calls.GetAccountingMode + mock.lockGetAccountingMode.RUnlock() + return calls +} + +// GetAccountingPids calls GetAccountingPidsFunc. +func (mock *Device) GetAccountingPids() ([]int, nvml.Return) { + if mock.GetAccountingPidsFunc == nil { + panic("Device.GetAccountingPidsFunc: method is nil but Device.GetAccountingPids was just called") + } + callInfo := struct { + }{} + mock.lockGetAccountingPids.Lock() + mock.calls.GetAccountingPids = append(mock.calls.GetAccountingPids, callInfo) + mock.lockGetAccountingPids.Unlock() + return mock.GetAccountingPidsFunc() +} + +// GetAccountingPidsCalls gets all the calls that were made to GetAccountingPids. +// Check the length with: +// +// len(mockedDevice.GetAccountingPidsCalls()) +func (mock *Device) GetAccountingPidsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAccountingPids.RLock() + calls = mock.calls.GetAccountingPids + mock.lockGetAccountingPids.RUnlock() + return calls +} + +// GetAccountingStats calls GetAccountingStatsFunc. +func (mock *Device) GetAccountingStats(v uint32) (nvml.AccountingStats, nvml.Return) { + if mock.GetAccountingStatsFunc == nil { + panic("Device.GetAccountingStatsFunc: method is nil but Device.GetAccountingStats was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockGetAccountingStats.Lock() + mock.calls.GetAccountingStats = append(mock.calls.GetAccountingStats, callInfo) + mock.lockGetAccountingStats.Unlock() + return mock.GetAccountingStatsFunc(v) +} + +// GetAccountingStatsCalls gets all the calls that were made to GetAccountingStats. +// Check the length with: +// +// len(mockedDevice.GetAccountingStatsCalls()) +func (mock *Device) GetAccountingStatsCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockGetAccountingStats.RLock() + calls = mock.calls.GetAccountingStats + mock.lockGetAccountingStats.RUnlock() + return calls +} + +// GetActiveVgpus calls GetActiveVgpusFunc. +func (mock *Device) GetActiveVgpus() ([]nvml.VgpuInstance, nvml.Return) { + if mock.GetActiveVgpusFunc == nil { + panic("Device.GetActiveVgpusFunc: method is nil but Device.GetActiveVgpus was just called") + } + callInfo := struct { + }{} + mock.lockGetActiveVgpus.Lock() + mock.calls.GetActiveVgpus = append(mock.calls.GetActiveVgpus, callInfo) + mock.lockGetActiveVgpus.Unlock() + return mock.GetActiveVgpusFunc() +} + +// GetActiveVgpusCalls gets all the calls that were made to GetActiveVgpus. +// Check the length with: +// +// len(mockedDevice.GetActiveVgpusCalls()) +func (mock *Device) GetActiveVgpusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetActiveVgpus.RLock() + calls = mock.calls.GetActiveVgpus + mock.lockGetActiveVgpus.RUnlock() + return calls +} + +// GetAdaptiveClockInfoStatus calls GetAdaptiveClockInfoStatusFunc. +func (mock *Device) GetAdaptiveClockInfoStatus() (uint32, nvml.Return) { + if mock.GetAdaptiveClockInfoStatusFunc == nil { + panic("Device.GetAdaptiveClockInfoStatusFunc: method is nil but Device.GetAdaptiveClockInfoStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetAdaptiveClockInfoStatus.Lock() + mock.calls.GetAdaptiveClockInfoStatus = append(mock.calls.GetAdaptiveClockInfoStatus, callInfo) + mock.lockGetAdaptiveClockInfoStatus.Unlock() + return mock.GetAdaptiveClockInfoStatusFunc() +} + +// GetAdaptiveClockInfoStatusCalls gets all the calls that were made to GetAdaptiveClockInfoStatus. +// Check the length with: +// +// len(mockedDevice.GetAdaptiveClockInfoStatusCalls()) +func (mock *Device) GetAdaptiveClockInfoStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAdaptiveClockInfoStatus.RLock() + calls = mock.calls.GetAdaptiveClockInfoStatus + mock.lockGetAdaptiveClockInfoStatus.RUnlock() + return calls +} + +// GetAddressingMode calls GetAddressingModeFunc. +func (mock *Device) GetAddressingMode() (nvml.DeviceAddressingMode, nvml.Return) { + if mock.GetAddressingModeFunc == nil { + panic("Device.GetAddressingModeFunc: method is nil but Device.GetAddressingMode was just called") + } + callInfo := struct { + }{} + mock.lockGetAddressingMode.Lock() + mock.calls.GetAddressingMode = append(mock.calls.GetAddressingMode, callInfo) + mock.lockGetAddressingMode.Unlock() + return mock.GetAddressingModeFunc() +} + +// GetAddressingModeCalls gets all the calls that were made to GetAddressingMode. +// Check the length with: +// +// len(mockedDevice.GetAddressingModeCalls()) +func (mock *Device) GetAddressingModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAddressingMode.RLock() + calls = mock.calls.GetAddressingMode + mock.lockGetAddressingMode.RUnlock() + return calls +} + +// GetApplicationsClock calls GetApplicationsClockFunc. +func (mock *Device) GetApplicationsClock(clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.GetApplicationsClockFunc == nil { + panic("Device.GetApplicationsClockFunc: method is nil but Device.GetApplicationsClock was just called") + } + callInfo := struct { + ClockType nvml.ClockType + }{ + ClockType: clockType, + } + mock.lockGetApplicationsClock.Lock() + mock.calls.GetApplicationsClock = append(mock.calls.GetApplicationsClock, callInfo) + mock.lockGetApplicationsClock.Unlock() + return mock.GetApplicationsClockFunc(clockType) +} + +// GetApplicationsClockCalls gets all the calls that were made to GetApplicationsClock. +// Check the length with: +// +// len(mockedDevice.GetApplicationsClockCalls()) +func (mock *Device) GetApplicationsClockCalls() []struct { + ClockType nvml.ClockType +} { + var calls []struct { + ClockType nvml.ClockType + } + mock.lockGetApplicationsClock.RLock() + calls = mock.calls.GetApplicationsClock + mock.lockGetApplicationsClock.RUnlock() + return calls +} + +// GetArchitecture calls GetArchitectureFunc. +func (mock *Device) GetArchitecture() (nvml.DeviceArchitecture, nvml.Return) { + if mock.GetArchitectureFunc == nil { + panic("Device.GetArchitectureFunc: method is nil but Device.GetArchitecture was just called") + } + callInfo := struct { + }{} + mock.lockGetArchitecture.Lock() + mock.calls.GetArchitecture = append(mock.calls.GetArchitecture, callInfo) + mock.lockGetArchitecture.Unlock() + return mock.GetArchitectureFunc() +} + +// GetArchitectureCalls gets all the calls that were made to GetArchitecture. +// Check the length with: +// +// len(mockedDevice.GetArchitectureCalls()) +func (mock *Device) GetArchitectureCalls() []struct { +} { + var calls []struct { + } + mock.lockGetArchitecture.RLock() + calls = mock.calls.GetArchitecture + mock.lockGetArchitecture.RUnlock() + return calls +} + +// GetAttributes calls GetAttributesFunc. +func (mock *Device) GetAttributes() (nvml.DeviceAttributes, nvml.Return) { + if mock.GetAttributesFunc == nil { + panic("Device.GetAttributesFunc: method is nil but Device.GetAttributes was just called") + } + callInfo := struct { + }{} + mock.lockGetAttributes.Lock() + mock.calls.GetAttributes = append(mock.calls.GetAttributes, callInfo) + mock.lockGetAttributes.Unlock() + return mock.GetAttributesFunc() +} + +// GetAttributesCalls gets all the calls that were made to GetAttributes. +// Check the length with: +// +// len(mockedDevice.GetAttributesCalls()) +func (mock *Device) GetAttributesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAttributes.RLock() + calls = mock.calls.GetAttributes + mock.lockGetAttributes.RUnlock() + return calls +} + +// GetAutoBoostedClocksEnabled calls GetAutoBoostedClocksEnabledFunc. +func (mock *Device) GetAutoBoostedClocksEnabled() (nvml.EnableState, nvml.EnableState, nvml.Return) { + if mock.GetAutoBoostedClocksEnabledFunc == nil { + panic("Device.GetAutoBoostedClocksEnabledFunc: method is nil but Device.GetAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + }{} + mock.lockGetAutoBoostedClocksEnabled.Lock() + mock.calls.GetAutoBoostedClocksEnabled = append(mock.calls.GetAutoBoostedClocksEnabled, callInfo) + mock.lockGetAutoBoostedClocksEnabled.Unlock() + return mock.GetAutoBoostedClocksEnabledFunc() +} + +// GetAutoBoostedClocksEnabledCalls gets all the calls that were made to GetAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedDevice.GetAutoBoostedClocksEnabledCalls()) +func (mock *Device) GetAutoBoostedClocksEnabledCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAutoBoostedClocksEnabled.RLock() + calls = mock.calls.GetAutoBoostedClocksEnabled + mock.lockGetAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// GetBAR1MemoryInfo calls GetBAR1MemoryInfoFunc. +func (mock *Device) GetBAR1MemoryInfo() (nvml.BAR1Memory, nvml.Return) { + if mock.GetBAR1MemoryInfoFunc == nil { + panic("Device.GetBAR1MemoryInfoFunc: method is nil but Device.GetBAR1MemoryInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetBAR1MemoryInfo.Lock() + mock.calls.GetBAR1MemoryInfo = append(mock.calls.GetBAR1MemoryInfo, callInfo) + mock.lockGetBAR1MemoryInfo.Unlock() + return mock.GetBAR1MemoryInfoFunc() +} + +// GetBAR1MemoryInfoCalls gets all the calls that were made to GetBAR1MemoryInfo. +// Check the length with: +// +// len(mockedDevice.GetBAR1MemoryInfoCalls()) +func (mock *Device) GetBAR1MemoryInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBAR1MemoryInfo.RLock() + calls = mock.calls.GetBAR1MemoryInfo + mock.lockGetBAR1MemoryInfo.RUnlock() + return calls +} + +// GetBoardId calls GetBoardIdFunc. +func (mock *Device) GetBoardId() (uint32, nvml.Return) { + if mock.GetBoardIdFunc == nil { + panic("Device.GetBoardIdFunc: method is nil but Device.GetBoardId was just called") + } + callInfo := struct { + }{} + mock.lockGetBoardId.Lock() + mock.calls.GetBoardId = append(mock.calls.GetBoardId, callInfo) + mock.lockGetBoardId.Unlock() + return mock.GetBoardIdFunc() +} + +// GetBoardIdCalls gets all the calls that were made to GetBoardId. +// Check the length with: +// +// len(mockedDevice.GetBoardIdCalls()) +func (mock *Device) GetBoardIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBoardId.RLock() + calls = mock.calls.GetBoardId + mock.lockGetBoardId.RUnlock() + return calls +} + +// GetBoardPartNumber calls GetBoardPartNumberFunc. +func (mock *Device) GetBoardPartNumber() (string, nvml.Return) { + if mock.GetBoardPartNumberFunc == nil { + panic("Device.GetBoardPartNumberFunc: method is nil but Device.GetBoardPartNumber was just called") + } + callInfo := struct { + }{} + mock.lockGetBoardPartNumber.Lock() + mock.calls.GetBoardPartNumber = append(mock.calls.GetBoardPartNumber, callInfo) + mock.lockGetBoardPartNumber.Unlock() + return mock.GetBoardPartNumberFunc() +} + +// GetBoardPartNumberCalls gets all the calls that were made to GetBoardPartNumber. +// Check the length with: +// +// len(mockedDevice.GetBoardPartNumberCalls()) +func (mock *Device) GetBoardPartNumberCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBoardPartNumber.RLock() + calls = mock.calls.GetBoardPartNumber + mock.lockGetBoardPartNumber.RUnlock() + return calls +} + +// GetBrand calls GetBrandFunc. +func (mock *Device) GetBrand() (nvml.BrandType, nvml.Return) { + if mock.GetBrandFunc == nil { + panic("Device.GetBrandFunc: method is nil but Device.GetBrand was just called") + } + callInfo := struct { + }{} + mock.lockGetBrand.Lock() + mock.calls.GetBrand = append(mock.calls.GetBrand, callInfo) + mock.lockGetBrand.Unlock() + return mock.GetBrandFunc() +} + +// GetBrandCalls gets all the calls that were made to GetBrand. +// Check the length with: +// +// len(mockedDevice.GetBrandCalls()) +func (mock *Device) GetBrandCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBrand.RLock() + calls = mock.calls.GetBrand + mock.lockGetBrand.RUnlock() + return calls +} + +// GetBridgeChipInfo calls GetBridgeChipInfoFunc. +func (mock *Device) GetBridgeChipInfo() (nvml.BridgeChipHierarchy, nvml.Return) { + if mock.GetBridgeChipInfoFunc == nil { + panic("Device.GetBridgeChipInfoFunc: method is nil but Device.GetBridgeChipInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetBridgeChipInfo.Lock() + mock.calls.GetBridgeChipInfo = append(mock.calls.GetBridgeChipInfo, callInfo) + mock.lockGetBridgeChipInfo.Unlock() + return mock.GetBridgeChipInfoFunc() +} + +// GetBridgeChipInfoCalls gets all the calls that were made to GetBridgeChipInfo. +// Check the length with: +// +// len(mockedDevice.GetBridgeChipInfoCalls()) +func (mock *Device) GetBridgeChipInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBridgeChipInfo.RLock() + calls = mock.calls.GetBridgeChipInfo + mock.lockGetBridgeChipInfo.RUnlock() + return calls +} + +// GetBusType calls GetBusTypeFunc. +func (mock *Device) GetBusType() (nvml.BusType, nvml.Return) { + if mock.GetBusTypeFunc == nil { + panic("Device.GetBusTypeFunc: method is nil but Device.GetBusType was just called") + } + callInfo := struct { + }{} + mock.lockGetBusType.Lock() + mock.calls.GetBusType = append(mock.calls.GetBusType, callInfo) + mock.lockGetBusType.Unlock() + return mock.GetBusTypeFunc() +} + +// GetBusTypeCalls gets all the calls that were made to GetBusType. +// Check the length with: +// +// len(mockedDevice.GetBusTypeCalls()) +func (mock *Device) GetBusTypeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBusType.RLock() + calls = mock.calls.GetBusType + mock.lockGetBusType.RUnlock() + return calls +} + +// GetC2cModeInfoV calls GetC2cModeInfoVFunc. +func (mock *Device) GetC2cModeInfoV() nvml.C2cModeInfoHandler { + if mock.GetC2cModeInfoVFunc == nil { + panic("Device.GetC2cModeInfoVFunc: method is nil but Device.GetC2cModeInfoV was just called") + } + callInfo := struct { + }{} + mock.lockGetC2cModeInfoV.Lock() + mock.calls.GetC2cModeInfoV = append(mock.calls.GetC2cModeInfoV, callInfo) + mock.lockGetC2cModeInfoV.Unlock() + return mock.GetC2cModeInfoVFunc() +} + +// GetC2cModeInfoVCalls gets all the calls that were made to GetC2cModeInfoV. +// Check the length with: +// +// len(mockedDevice.GetC2cModeInfoVCalls()) +func (mock *Device) GetC2cModeInfoVCalls() []struct { +} { + var calls []struct { + } + mock.lockGetC2cModeInfoV.RLock() + calls = mock.calls.GetC2cModeInfoV + mock.lockGetC2cModeInfoV.RUnlock() + return calls +} + +// GetCapabilities calls GetCapabilitiesFunc. +func (mock *Device) GetCapabilities() (nvml.DeviceCapabilities, nvml.Return) { + if mock.GetCapabilitiesFunc == nil { + panic("Device.GetCapabilitiesFunc: method is nil but Device.GetCapabilities was just called") + } + callInfo := struct { + }{} + mock.lockGetCapabilities.Lock() + mock.calls.GetCapabilities = append(mock.calls.GetCapabilities, callInfo) + mock.lockGetCapabilities.Unlock() + return mock.GetCapabilitiesFunc() +} + +// GetCapabilitiesCalls gets all the calls that were made to GetCapabilities. +// Check the length with: +// +// len(mockedDevice.GetCapabilitiesCalls()) +func (mock *Device) GetCapabilitiesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCapabilities.RLock() + calls = mock.calls.GetCapabilities + mock.lockGetCapabilities.RUnlock() + return calls +} + +// GetClkMonStatus calls GetClkMonStatusFunc. +func (mock *Device) GetClkMonStatus() (nvml.ClkMonStatus, nvml.Return) { + if mock.GetClkMonStatusFunc == nil { + panic("Device.GetClkMonStatusFunc: method is nil but Device.GetClkMonStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetClkMonStatus.Lock() + mock.calls.GetClkMonStatus = append(mock.calls.GetClkMonStatus, callInfo) + mock.lockGetClkMonStatus.Unlock() + return mock.GetClkMonStatusFunc() +} + +// GetClkMonStatusCalls gets all the calls that were made to GetClkMonStatus. +// Check the length with: +// +// len(mockedDevice.GetClkMonStatusCalls()) +func (mock *Device) GetClkMonStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetClkMonStatus.RLock() + calls = mock.calls.GetClkMonStatus + mock.lockGetClkMonStatus.RUnlock() + return calls +} + +// GetClock calls GetClockFunc. +func (mock *Device) GetClock(clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) { + if mock.GetClockFunc == nil { + panic("Device.GetClockFunc: method is nil but Device.GetClock was just called") + } + callInfo := struct { + ClockType nvml.ClockType + ClockId nvml.ClockId + }{ + ClockType: clockType, + ClockId: clockId, + } + mock.lockGetClock.Lock() + mock.calls.GetClock = append(mock.calls.GetClock, callInfo) + mock.lockGetClock.Unlock() + return mock.GetClockFunc(clockType, clockId) +} + +// GetClockCalls gets all the calls that were made to GetClock. +// Check the length with: +// +// len(mockedDevice.GetClockCalls()) +func (mock *Device) GetClockCalls() []struct { + ClockType nvml.ClockType + ClockId nvml.ClockId +} { + var calls []struct { + ClockType nvml.ClockType + ClockId nvml.ClockId + } + mock.lockGetClock.RLock() + calls = mock.calls.GetClock + mock.lockGetClock.RUnlock() + return calls +} + +// GetClockInfo calls GetClockInfoFunc. +func (mock *Device) GetClockInfo(clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.GetClockInfoFunc == nil { + panic("Device.GetClockInfoFunc: method is nil but Device.GetClockInfo was just called") + } + callInfo := struct { + ClockType nvml.ClockType + }{ + ClockType: clockType, + } + mock.lockGetClockInfo.Lock() + mock.calls.GetClockInfo = append(mock.calls.GetClockInfo, callInfo) + mock.lockGetClockInfo.Unlock() + return mock.GetClockInfoFunc(clockType) +} + +// GetClockInfoCalls gets all the calls that were made to GetClockInfo. +// Check the length with: +// +// len(mockedDevice.GetClockInfoCalls()) +func (mock *Device) GetClockInfoCalls() []struct { + ClockType nvml.ClockType +} { + var calls []struct { + ClockType nvml.ClockType + } + mock.lockGetClockInfo.RLock() + calls = mock.calls.GetClockInfo + mock.lockGetClockInfo.RUnlock() + return calls +} + +// GetClockOffsets calls GetClockOffsetsFunc. +func (mock *Device) GetClockOffsets() (nvml.ClockOffset, nvml.Return) { + if mock.GetClockOffsetsFunc == nil { + panic("Device.GetClockOffsetsFunc: method is nil but Device.GetClockOffsets was just called") + } + callInfo := struct { + }{} + mock.lockGetClockOffsets.Lock() + mock.calls.GetClockOffsets = append(mock.calls.GetClockOffsets, callInfo) + mock.lockGetClockOffsets.Unlock() + return mock.GetClockOffsetsFunc() +} + +// GetClockOffsetsCalls gets all the calls that were made to GetClockOffsets. +// Check the length with: +// +// len(mockedDevice.GetClockOffsetsCalls()) +func (mock *Device) GetClockOffsetsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetClockOffsets.RLock() + calls = mock.calls.GetClockOffsets + mock.lockGetClockOffsets.RUnlock() + return calls +} + +// GetComputeInstanceId calls GetComputeInstanceIdFunc. +func (mock *Device) GetComputeInstanceId() (int, nvml.Return) { + if mock.GetComputeInstanceIdFunc == nil { + panic("Device.GetComputeInstanceIdFunc: method is nil but Device.GetComputeInstanceId was just called") + } + callInfo := struct { + }{} + mock.lockGetComputeInstanceId.Lock() + mock.calls.GetComputeInstanceId = append(mock.calls.GetComputeInstanceId, callInfo) + mock.lockGetComputeInstanceId.Unlock() + return mock.GetComputeInstanceIdFunc() +} + +// GetComputeInstanceIdCalls gets all the calls that were made to GetComputeInstanceId. +// Check the length with: +// +// len(mockedDevice.GetComputeInstanceIdCalls()) +func (mock *Device) GetComputeInstanceIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetComputeInstanceId.RLock() + calls = mock.calls.GetComputeInstanceId + mock.lockGetComputeInstanceId.RUnlock() + return calls +} + +// GetComputeMode calls GetComputeModeFunc. +func (mock *Device) GetComputeMode() (nvml.ComputeMode, nvml.Return) { + if mock.GetComputeModeFunc == nil { + panic("Device.GetComputeModeFunc: method is nil but Device.GetComputeMode was just called") + } + callInfo := struct { + }{} + mock.lockGetComputeMode.Lock() + mock.calls.GetComputeMode = append(mock.calls.GetComputeMode, callInfo) + mock.lockGetComputeMode.Unlock() + return mock.GetComputeModeFunc() +} + +// GetComputeModeCalls gets all the calls that were made to GetComputeMode. +// Check the length with: +// +// len(mockedDevice.GetComputeModeCalls()) +func (mock *Device) GetComputeModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetComputeMode.RLock() + calls = mock.calls.GetComputeMode + mock.lockGetComputeMode.RUnlock() + return calls +} + +// GetComputeRunningProcesses calls GetComputeRunningProcessesFunc. +func (mock *Device) GetComputeRunningProcesses() ([]nvml.ProcessInfo, nvml.Return) { + if mock.GetComputeRunningProcessesFunc == nil { + panic("Device.GetComputeRunningProcessesFunc: method is nil but Device.GetComputeRunningProcesses was just called") + } + callInfo := struct { + }{} + mock.lockGetComputeRunningProcesses.Lock() + mock.calls.GetComputeRunningProcesses = append(mock.calls.GetComputeRunningProcesses, callInfo) + mock.lockGetComputeRunningProcesses.Unlock() + return mock.GetComputeRunningProcessesFunc() +} + +// GetComputeRunningProcessesCalls gets all the calls that were made to GetComputeRunningProcesses. +// Check the length with: +// +// len(mockedDevice.GetComputeRunningProcessesCalls()) +func (mock *Device) GetComputeRunningProcessesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetComputeRunningProcesses.RLock() + calls = mock.calls.GetComputeRunningProcesses + mock.lockGetComputeRunningProcesses.RUnlock() + return calls +} + +// GetConfComputeGpuAttestationReport calls GetConfComputeGpuAttestationReportFunc. +func (mock *Device) GetConfComputeGpuAttestationReport(confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return { + if mock.GetConfComputeGpuAttestationReportFunc == nil { + panic("Device.GetConfComputeGpuAttestationReportFunc: method is nil but Device.GetConfComputeGpuAttestationReport was just called") + } + callInfo := struct { + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + }{ + ConfComputeGpuAttestationReport: confComputeGpuAttestationReport, + } + mock.lockGetConfComputeGpuAttestationReport.Lock() + mock.calls.GetConfComputeGpuAttestationReport = append(mock.calls.GetConfComputeGpuAttestationReport, callInfo) + mock.lockGetConfComputeGpuAttestationReport.Unlock() + return mock.GetConfComputeGpuAttestationReportFunc(confComputeGpuAttestationReport) +} + +// GetConfComputeGpuAttestationReportCalls gets all the calls that were made to GetConfComputeGpuAttestationReport. +// Check the length with: +// +// len(mockedDevice.GetConfComputeGpuAttestationReportCalls()) +func (mock *Device) GetConfComputeGpuAttestationReportCalls() []struct { + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport +} { + var calls []struct { + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + } + mock.lockGetConfComputeGpuAttestationReport.RLock() + calls = mock.calls.GetConfComputeGpuAttestationReport + mock.lockGetConfComputeGpuAttestationReport.RUnlock() + return calls +} + +// GetConfComputeGpuCertificate calls GetConfComputeGpuCertificateFunc. +func (mock *Device) GetConfComputeGpuCertificate() (nvml.ConfComputeGpuCertificate, nvml.Return) { + if mock.GetConfComputeGpuCertificateFunc == nil { + panic("Device.GetConfComputeGpuCertificateFunc: method is nil but Device.GetConfComputeGpuCertificate was just called") + } + callInfo := struct { + }{} + mock.lockGetConfComputeGpuCertificate.Lock() + mock.calls.GetConfComputeGpuCertificate = append(mock.calls.GetConfComputeGpuCertificate, callInfo) + mock.lockGetConfComputeGpuCertificate.Unlock() + return mock.GetConfComputeGpuCertificateFunc() +} + +// GetConfComputeGpuCertificateCalls gets all the calls that were made to GetConfComputeGpuCertificate. +// Check the length with: +// +// len(mockedDevice.GetConfComputeGpuCertificateCalls()) +func (mock *Device) GetConfComputeGpuCertificateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetConfComputeGpuCertificate.RLock() + calls = mock.calls.GetConfComputeGpuCertificate + mock.lockGetConfComputeGpuCertificate.RUnlock() + return calls +} + +// GetConfComputeMemSizeInfo calls GetConfComputeMemSizeInfoFunc. +func (mock *Device) GetConfComputeMemSizeInfo() (nvml.ConfComputeMemSizeInfo, nvml.Return) { + if mock.GetConfComputeMemSizeInfoFunc == nil { + panic("Device.GetConfComputeMemSizeInfoFunc: method is nil but Device.GetConfComputeMemSizeInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetConfComputeMemSizeInfo.Lock() + mock.calls.GetConfComputeMemSizeInfo = append(mock.calls.GetConfComputeMemSizeInfo, callInfo) + mock.lockGetConfComputeMemSizeInfo.Unlock() + return mock.GetConfComputeMemSizeInfoFunc() +} + +// GetConfComputeMemSizeInfoCalls gets all the calls that were made to GetConfComputeMemSizeInfo. +// Check the length with: +// +// len(mockedDevice.GetConfComputeMemSizeInfoCalls()) +func (mock *Device) GetConfComputeMemSizeInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetConfComputeMemSizeInfo.RLock() + calls = mock.calls.GetConfComputeMemSizeInfo + mock.lockGetConfComputeMemSizeInfo.RUnlock() + return calls +} + +// GetConfComputeProtectedMemoryUsage calls GetConfComputeProtectedMemoryUsageFunc. +func (mock *Device) GetConfComputeProtectedMemoryUsage() (nvml.Memory, nvml.Return) { + if mock.GetConfComputeProtectedMemoryUsageFunc == nil { + panic("Device.GetConfComputeProtectedMemoryUsageFunc: method is nil but Device.GetConfComputeProtectedMemoryUsage was just called") + } + callInfo := struct { + }{} + mock.lockGetConfComputeProtectedMemoryUsage.Lock() + mock.calls.GetConfComputeProtectedMemoryUsage = append(mock.calls.GetConfComputeProtectedMemoryUsage, callInfo) + mock.lockGetConfComputeProtectedMemoryUsage.Unlock() + return mock.GetConfComputeProtectedMemoryUsageFunc() +} + +// GetConfComputeProtectedMemoryUsageCalls gets all the calls that were made to GetConfComputeProtectedMemoryUsage. +// Check the length with: +// +// len(mockedDevice.GetConfComputeProtectedMemoryUsageCalls()) +func (mock *Device) GetConfComputeProtectedMemoryUsageCalls() []struct { +} { + var calls []struct { + } + mock.lockGetConfComputeProtectedMemoryUsage.RLock() + calls = mock.calls.GetConfComputeProtectedMemoryUsage + mock.lockGetConfComputeProtectedMemoryUsage.RUnlock() + return calls +} + +// GetCoolerInfo calls GetCoolerInfoFunc. +func (mock *Device) GetCoolerInfo() (nvml.CoolerInfo, nvml.Return) { + if mock.GetCoolerInfoFunc == nil { + panic("Device.GetCoolerInfoFunc: method is nil but Device.GetCoolerInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetCoolerInfo.Lock() + mock.calls.GetCoolerInfo = append(mock.calls.GetCoolerInfo, callInfo) + mock.lockGetCoolerInfo.Unlock() + return mock.GetCoolerInfoFunc() +} + +// GetCoolerInfoCalls gets all the calls that were made to GetCoolerInfo. +// Check the length with: +// +// len(mockedDevice.GetCoolerInfoCalls()) +func (mock *Device) GetCoolerInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCoolerInfo.RLock() + calls = mock.calls.GetCoolerInfo + mock.lockGetCoolerInfo.RUnlock() + return calls +} + +// GetCpuAffinity calls GetCpuAffinityFunc. +func (mock *Device) GetCpuAffinity(n int) ([]uint, nvml.Return) { + if mock.GetCpuAffinityFunc == nil { + panic("Device.GetCpuAffinityFunc: method is nil but Device.GetCpuAffinity was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetCpuAffinity.Lock() + mock.calls.GetCpuAffinity = append(mock.calls.GetCpuAffinity, callInfo) + mock.lockGetCpuAffinity.Unlock() + return mock.GetCpuAffinityFunc(n) +} + +// GetCpuAffinityCalls gets all the calls that were made to GetCpuAffinity. +// Check the length with: +// +// len(mockedDevice.GetCpuAffinityCalls()) +func (mock *Device) GetCpuAffinityCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetCpuAffinity.RLock() + calls = mock.calls.GetCpuAffinity + mock.lockGetCpuAffinity.RUnlock() + return calls +} + +// GetCpuAffinityWithinScope calls GetCpuAffinityWithinScopeFunc. +func (mock *Device) GetCpuAffinityWithinScope(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { + if mock.GetCpuAffinityWithinScopeFunc == nil { + panic("Device.GetCpuAffinityWithinScopeFunc: method is nil but Device.GetCpuAffinityWithinScope was just called") + } + callInfo := struct { + N int + AffinityScope nvml.AffinityScope + }{ + N: n, + AffinityScope: affinityScope, + } + mock.lockGetCpuAffinityWithinScope.Lock() + mock.calls.GetCpuAffinityWithinScope = append(mock.calls.GetCpuAffinityWithinScope, callInfo) + mock.lockGetCpuAffinityWithinScope.Unlock() + return mock.GetCpuAffinityWithinScopeFunc(n, affinityScope) +} + +// GetCpuAffinityWithinScopeCalls gets all the calls that were made to GetCpuAffinityWithinScope. +// Check the length with: +// +// len(mockedDevice.GetCpuAffinityWithinScopeCalls()) +func (mock *Device) GetCpuAffinityWithinScopeCalls() []struct { + N int + AffinityScope nvml.AffinityScope +} { + var calls []struct { + N int + AffinityScope nvml.AffinityScope + } + mock.lockGetCpuAffinityWithinScope.RLock() + calls = mock.calls.GetCpuAffinityWithinScope + mock.lockGetCpuAffinityWithinScope.RUnlock() + return calls +} + +// GetCreatableVgpus calls GetCreatableVgpusFunc. +func (mock *Device) GetCreatableVgpus() ([]nvml.VgpuTypeId, nvml.Return) { + if mock.GetCreatableVgpusFunc == nil { + panic("Device.GetCreatableVgpusFunc: method is nil but Device.GetCreatableVgpus was just called") + } + callInfo := struct { + }{} + mock.lockGetCreatableVgpus.Lock() + mock.calls.GetCreatableVgpus = append(mock.calls.GetCreatableVgpus, callInfo) + mock.lockGetCreatableVgpus.Unlock() + return mock.GetCreatableVgpusFunc() +} + +// GetCreatableVgpusCalls gets all the calls that were made to GetCreatableVgpus. +// Check the length with: +// +// len(mockedDevice.GetCreatableVgpusCalls()) +func (mock *Device) GetCreatableVgpusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCreatableVgpus.RLock() + calls = mock.calls.GetCreatableVgpus + mock.lockGetCreatableVgpus.RUnlock() + return calls +} + +// GetCudaComputeCapability calls GetCudaComputeCapabilityFunc. +func (mock *Device) GetCudaComputeCapability() (int, int, nvml.Return) { + if mock.GetCudaComputeCapabilityFunc == nil { + panic("Device.GetCudaComputeCapabilityFunc: method is nil but Device.GetCudaComputeCapability was just called") + } + callInfo := struct { + }{} + mock.lockGetCudaComputeCapability.Lock() + mock.calls.GetCudaComputeCapability = append(mock.calls.GetCudaComputeCapability, callInfo) + mock.lockGetCudaComputeCapability.Unlock() + return mock.GetCudaComputeCapabilityFunc() +} + +// GetCudaComputeCapabilityCalls gets all the calls that were made to GetCudaComputeCapability. +// Check the length with: +// +// len(mockedDevice.GetCudaComputeCapabilityCalls()) +func (mock *Device) GetCudaComputeCapabilityCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCudaComputeCapability.RLock() + calls = mock.calls.GetCudaComputeCapability + mock.lockGetCudaComputeCapability.RUnlock() + return calls +} + +// GetCurrPcieLinkGeneration calls GetCurrPcieLinkGenerationFunc. +func (mock *Device) GetCurrPcieLinkGeneration() (int, nvml.Return) { + if mock.GetCurrPcieLinkGenerationFunc == nil { + panic("Device.GetCurrPcieLinkGenerationFunc: method is nil but Device.GetCurrPcieLinkGeneration was just called") + } + callInfo := struct { + }{} + mock.lockGetCurrPcieLinkGeneration.Lock() + mock.calls.GetCurrPcieLinkGeneration = append(mock.calls.GetCurrPcieLinkGeneration, callInfo) + mock.lockGetCurrPcieLinkGeneration.Unlock() + return mock.GetCurrPcieLinkGenerationFunc() +} + +// GetCurrPcieLinkGenerationCalls gets all the calls that were made to GetCurrPcieLinkGeneration. +// Check the length with: +// +// len(mockedDevice.GetCurrPcieLinkGenerationCalls()) +func (mock *Device) GetCurrPcieLinkGenerationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCurrPcieLinkGeneration.RLock() + calls = mock.calls.GetCurrPcieLinkGeneration + mock.lockGetCurrPcieLinkGeneration.RUnlock() + return calls +} + +// GetCurrPcieLinkWidth calls GetCurrPcieLinkWidthFunc. +func (mock *Device) GetCurrPcieLinkWidth() (int, nvml.Return) { + if mock.GetCurrPcieLinkWidthFunc == nil { + panic("Device.GetCurrPcieLinkWidthFunc: method is nil but Device.GetCurrPcieLinkWidth was just called") + } + callInfo := struct { + }{} + mock.lockGetCurrPcieLinkWidth.Lock() + mock.calls.GetCurrPcieLinkWidth = append(mock.calls.GetCurrPcieLinkWidth, callInfo) + mock.lockGetCurrPcieLinkWidth.Unlock() + return mock.GetCurrPcieLinkWidthFunc() +} + +// GetCurrPcieLinkWidthCalls gets all the calls that were made to GetCurrPcieLinkWidth. +// Check the length with: +// +// len(mockedDevice.GetCurrPcieLinkWidthCalls()) +func (mock *Device) GetCurrPcieLinkWidthCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCurrPcieLinkWidth.RLock() + calls = mock.calls.GetCurrPcieLinkWidth + mock.lockGetCurrPcieLinkWidth.RUnlock() + return calls +} + +// GetCurrentClockFreqs calls GetCurrentClockFreqsFunc. +func (mock *Device) GetCurrentClockFreqs() (nvml.DeviceCurrentClockFreqs, nvml.Return) { + if mock.GetCurrentClockFreqsFunc == nil { + panic("Device.GetCurrentClockFreqsFunc: method is nil but Device.GetCurrentClockFreqs was just called") + } + callInfo := struct { + }{} + mock.lockGetCurrentClockFreqs.Lock() + mock.calls.GetCurrentClockFreqs = append(mock.calls.GetCurrentClockFreqs, callInfo) + mock.lockGetCurrentClockFreqs.Unlock() + return mock.GetCurrentClockFreqsFunc() +} + +// GetCurrentClockFreqsCalls gets all the calls that were made to GetCurrentClockFreqs. +// Check the length with: +// +// len(mockedDevice.GetCurrentClockFreqsCalls()) +func (mock *Device) GetCurrentClockFreqsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCurrentClockFreqs.RLock() + calls = mock.calls.GetCurrentClockFreqs + mock.lockGetCurrentClockFreqs.RUnlock() + return calls +} + +// GetCurrentClocksEventReasons calls GetCurrentClocksEventReasonsFunc. +func (mock *Device) GetCurrentClocksEventReasons() (uint64, nvml.Return) { + if mock.GetCurrentClocksEventReasonsFunc == nil { + panic("Device.GetCurrentClocksEventReasonsFunc: method is nil but Device.GetCurrentClocksEventReasons was just called") + } + callInfo := struct { + }{} + mock.lockGetCurrentClocksEventReasons.Lock() + mock.calls.GetCurrentClocksEventReasons = append(mock.calls.GetCurrentClocksEventReasons, callInfo) + mock.lockGetCurrentClocksEventReasons.Unlock() + return mock.GetCurrentClocksEventReasonsFunc() +} + +// GetCurrentClocksEventReasonsCalls gets all the calls that were made to GetCurrentClocksEventReasons. +// Check the length with: +// +// len(mockedDevice.GetCurrentClocksEventReasonsCalls()) +func (mock *Device) GetCurrentClocksEventReasonsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCurrentClocksEventReasons.RLock() + calls = mock.calls.GetCurrentClocksEventReasons + mock.lockGetCurrentClocksEventReasons.RUnlock() + return calls +} + +// GetCurrentClocksThrottleReasons calls GetCurrentClocksThrottleReasonsFunc. +func (mock *Device) GetCurrentClocksThrottleReasons() (uint64, nvml.Return) { + if mock.GetCurrentClocksThrottleReasonsFunc == nil { + panic("Device.GetCurrentClocksThrottleReasonsFunc: method is nil but Device.GetCurrentClocksThrottleReasons was just called") + } + callInfo := struct { + }{} + mock.lockGetCurrentClocksThrottleReasons.Lock() + mock.calls.GetCurrentClocksThrottleReasons = append(mock.calls.GetCurrentClocksThrottleReasons, callInfo) + mock.lockGetCurrentClocksThrottleReasons.Unlock() + return mock.GetCurrentClocksThrottleReasonsFunc() +} + +// GetCurrentClocksThrottleReasonsCalls gets all the calls that were made to GetCurrentClocksThrottleReasons. +// Check the length with: +// +// len(mockedDevice.GetCurrentClocksThrottleReasonsCalls()) +func (mock *Device) GetCurrentClocksThrottleReasonsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCurrentClocksThrottleReasons.RLock() + calls = mock.calls.GetCurrentClocksThrottleReasons + mock.lockGetCurrentClocksThrottleReasons.RUnlock() + return calls +} + +// GetDecoderUtilization calls GetDecoderUtilizationFunc. +func (mock *Device) GetDecoderUtilization() (uint32, uint32, nvml.Return) { + if mock.GetDecoderUtilizationFunc == nil { + panic("Device.GetDecoderUtilizationFunc: method is nil but Device.GetDecoderUtilization was just called") + } + callInfo := struct { + }{} + mock.lockGetDecoderUtilization.Lock() + mock.calls.GetDecoderUtilization = append(mock.calls.GetDecoderUtilization, callInfo) + mock.lockGetDecoderUtilization.Unlock() + return mock.GetDecoderUtilizationFunc() +} + +// GetDecoderUtilizationCalls gets all the calls that were made to GetDecoderUtilization. +// Check the length with: +// +// len(mockedDevice.GetDecoderUtilizationCalls()) +func (mock *Device) GetDecoderUtilizationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDecoderUtilization.RLock() + calls = mock.calls.GetDecoderUtilization + mock.lockGetDecoderUtilization.RUnlock() + return calls +} + +// GetDefaultApplicationsClock calls GetDefaultApplicationsClockFunc. +func (mock *Device) GetDefaultApplicationsClock(clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.GetDefaultApplicationsClockFunc == nil { + panic("Device.GetDefaultApplicationsClockFunc: method is nil but Device.GetDefaultApplicationsClock was just called") + } + callInfo := struct { + ClockType nvml.ClockType + }{ + ClockType: clockType, + } + mock.lockGetDefaultApplicationsClock.Lock() + mock.calls.GetDefaultApplicationsClock = append(mock.calls.GetDefaultApplicationsClock, callInfo) + mock.lockGetDefaultApplicationsClock.Unlock() + return mock.GetDefaultApplicationsClockFunc(clockType) +} + +// GetDefaultApplicationsClockCalls gets all the calls that were made to GetDefaultApplicationsClock. +// Check the length with: +// +// len(mockedDevice.GetDefaultApplicationsClockCalls()) +func (mock *Device) GetDefaultApplicationsClockCalls() []struct { + ClockType nvml.ClockType +} { + var calls []struct { + ClockType nvml.ClockType + } + mock.lockGetDefaultApplicationsClock.RLock() + calls = mock.calls.GetDefaultApplicationsClock + mock.lockGetDefaultApplicationsClock.RUnlock() + return calls +} + +// GetDefaultEccMode calls GetDefaultEccModeFunc. +func (mock *Device) GetDefaultEccMode() (nvml.EnableState, nvml.Return) { + if mock.GetDefaultEccModeFunc == nil { + panic("Device.GetDefaultEccModeFunc: method is nil but Device.GetDefaultEccMode was just called") + } + callInfo := struct { + }{} + mock.lockGetDefaultEccMode.Lock() + mock.calls.GetDefaultEccMode = append(mock.calls.GetDefaultEccMode, callInfo) + mock.lockGetDefaultEccMode.Unlock() + return mock.GetDefaultEccModeFunc() +} + +// GetDefaultEccModeCalls gets all the calls that were made to GetDefaultEccMode. +// Check the length with: +// +// len(mockedDevice.GetDefaultEccModeCalls()) +func (mock *Device) GetDefaultEccModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDefaultEccMode.RLock() + calls = mock.calls.GetDefaultEccMode + mock.lockGetDefaultEccMode.RUnlock() + return calls +} + +// GetDetailedEccErrors calls GetDetailedEccErrorsFunc. +func (mock *Device) GetDetailedEccErrors(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) { + if mock.GetDetailedEccErrorsFunc == nil { + panic("Device.GetDetailedEccErrorsFunc: method is nil but Device.GetDetailedEccErrors was just called") + } + callInfo := struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + }{ + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + } + mock.lockGetDetailedEccErrors.Lock() + mock.calls.GetDetailedEccErrors = append(mock.calls.GetDetailedEccErrors, callInfo) + mock.lockGetDetailedEccErrors.Unlock() + return mock.GetDetailedEccErrorsFunc(memoryErrorType, eccCounterType) +} + +// GetDetailedEccErrorsCalls gets all the calls that were made to GetDetailedEccErrors. +// Check the length with: +// +// len(mockedDevice.GetDetailedEccErrorsCalls()) +func (mock *Device) GetDetailedEccErrorsCalls() []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType +} { + var calls []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + } + mock.lockGetDetailedEccErrors.RLock() + calls = mock.calls.GetDetailedEccErrors + mock.lockGetDetailedEccErrors.RUnlock() + return calls +} + +// GetDeviceHandleFromMigDeviceHandle calls GetDeviceHandleFromMigDeviceHandleFunc. +func (mock *Device) GetDeviceHandleFromMigDeviceHandle() (nvml.Device, nvml.Return) { + if mock.GetDeviceHandleFromMigDeviceHandleFunc == nil { + panic("Device.GetDeviceHandleFromMigDeviceHandleFunc: method is nil but Device.GetDeviceHandleFromMigDeviceHandle was just called") + } + callInfo := struct { + }{} + mock.lockGetDeviceHandleFromMigDeviceHandle.Lock() + mock.calls.GetDeviceHandleFromMigDeviceHandle = append(mock.calls.GetDeviceHandleFromMigDeviceHandle, callInfo) + mock.lockGetDeviceHandleFromMigDeviceHandle.Unlock() + return mock.GetDeviceHandleFromMigDeviceHandleFunc() +} + +// GetDeviceHandleFromMigDeviceHandleCalls gets all the calls that were made to GetDeviceHandleFromMigDeviceHandle. +// Check the length with: +// +// len(mockedDevice.GetDeviceHandleFromMigDeviceHandleCalls()) +func (mock *Device) GetDeviceHandleFromMigDeviceHandleCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDeviceHandleFromMigDeviceHandle.RLock() + calls = mock.calls.GetDeviceHandleFromMigDeviceHandle + mock.lockGetDeviceHandleFromMigDeviceHandle.RUnlock() + return calls +} + +// GetDisplayActive calls GetDisplayActiveFunc. +func (mock *Device) GetDisplayActive() (nvml.EnableState, nvml.Return) { + if mock.GetDisplayActiveFunc == nil { + panic("Device.GetDisplayActiveFunc: method is nil but Device.GetDisplayActive was just called") + } + callInfo := struct { + }{} + mock.lockGetDisplayActive.Lock() + mock.calls.GetDisplayActive = append(mock.calls.GetDisplayActive, callInfo) + mock.lockGetDisplayActive.Unlock() + return mock.GetDisplayActiveFunc() +} + +// GetDisplayActiveCalls gets all the calls that were made to GetDisplayActive. +// Check the length with: +// +// len(mockedDevice.GetDisplayActiveCalls()) +func (mock *Device) GetDisplayActiveCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDisplayActive.RLock() + calls = mock.calls.GetDisplayActive + mock.lockGetDisplayActive.RUnlock() + return calls +} + +// GetDisplayMode calls GetDisplayModeFunc. +func (mock *Device) GetDisplayMode() (nvml.EnableState, nvml.Return) { + if mock.GetDisplayModeFunc == nil { + panic("Device.GetDisplayModeFunc: method is nil but Device.GetDisplayMode was just called") + } + callInfo := struct { + }{} + mock.lockGetDisplayMode.Lock() + mock.calls.GetDisplayMode = append(mock.calls.GetDisplayMode, callInfo) + mock.lockGetDisplayMode.Unlock() + return mock.GetDisplayModeFunc() +} + +// GetDisplayModeCalls gets all the calls that were made to GetDisplayMode. +// Check the length with: +// +// len(mockedDevice.GetDisplayModeCalls()) +func (mock *Device) GetDisplayModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDisplayMode.RLock() + calls = mock.calls.GetDisplayMode + mock.lockGetDisplayMode.RUnlock() + return calls +} + +// GetDramEncryptionMode calls GetDramEncryptionModeFunc. +func (mock *Device) GetDramEncryptionMode() (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) { + if mock.GetDramEncryptionModeFunc == nil { + panic("Device.GetDramEncryptionModeFunc: method is nil but Device.GetDramEncryptionMode was just called") + } + callInfo := struct { + }{} + mock.lockGetDramEncryptionMode.Lock() + mock.calls.GetDramEncryptionMode = append(mock.calls.GetDramEncryptionMode, callInfo) + mock.lockGetDramEncryptionMode.Unlock() + return mock.GetDramEncryptionModeFunc() +} + +// GetDramEncryptionModeCalls gets all the calls that were made to GetDramEncryptionMode. +// Check the length with: +// +// len(mockedDevice.GetDramEncryptionModeCalls()) +func (mock *Device) GetDramEncryptionModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDramEncryptionMode.RLock() + calls = mock.calls.GetDramEncryptionMode + mock.lockGetDramEncryptionMode.RUnlock() + return calls +} + +// GetDriverModel calls GetDriverModelFunc. +func (mock *Device) GetDriverModel() (nvml.DriverModel, nvml.DriverModel, nvml.Return) { + if mock.GetDriverModelFunc == nil { + panic("Device.GetDriverModelFunc: method is nil but Device.GetDriverModel was just called") + } + callInfo := struct { + }{} + mock.lockGetDriverModel.Lock() + mock.calls.GetDriverModel = append(mock.calls.GetDriverModel, callInfo) + mock.lockGetDriverModel.Unlock() + return mock.GetDriverModelFunc() +} + +// GetDriverModelCalls gets all the calls that were made to GetDriverModel. +// Check the length with: +// +// len(mockedDevice.GetDriverModelCalls()) +func (mock *Device) GetDriverModelCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDriverModel.RLock() + calls = mock.calls.GetDriverModel + mock.lockGetDriverModel.RUnlock() + return calls +} + +// GetDriverModel_v2 calls GetDriverModel_v2Func. +func (mock *Device) GetDriverModel_v2() (nvml.DriverModel, nvml.DriverModel, nvml.Return) { + if mock.GetDriverModel_v2Func == nil { + panic("Device.GetDriverModel_v2Func: method is nil but Device.GetDriverModel_v2 was just called") + } + callInfo := struct { + }{} + mock.lockGetDriverModel_v2.Lock() + mock.calls.GetDriverModel_v2 = append(mock.calls.GetDriverModel_v2, callInfo) + mock.lockGetDriverModel_v2.Unlock() + return mock.GetDriverModel_v2Func() +} + +// GetDriverModel_v2Calls gets all the calls that were made to GetDriverModel_v2. +// Check the length with: +// +// len(mockedDevice.GetDriverModel_v2Calls()) +func (mock *Device) GetDriverModel_v2Calls() []struct { +} { + var calls []struct { + } + mock.lockGetDriverModel_v2.RLock() + calls = mock.calls.GetDriverModel_v2 + mock.lockGetDriverModel_v2.RUnlock() + return calls +} + +// GetDynamicPstatesInfo calls GetDynamicPstatesInfoFunc. +func (mock *Device) GetDynamicPstatesInfo() (nvml.GpuDynamicPstatesInfo, nvml.Return) { + if mock.GetDynamicPstatesInfoFunc == nil { + panic("Device.GetDynamicPstatesInfoFunc: method is nil but Device.GetDynamicPstatesInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetDynamicPstatesInfo.Lock() + mock.calls.GetDynamicPstatesInfo = append(mock.calls.GetDynamicPstatesInfo, callInfo) + mock.lockGetDynamicPstatesInfo.Unlock() + return mock.GetDynamicPstatesInfoFunc() +} + +// GetDynamicPstatesInfoCalls gets all the calls that were made to GetDynamicPstatesInfo. +// Check the length with: +// +// len(mockedDevice.GetDynamicPstatesInfoCalls()) +func (mock *Device) GetDynamicPstatesInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDynamicPstatesInfo.RLock() + calls = mock.calls.GetDynamicPstatesInfo + mock.lockGetDynamicPstatesInfo.RUnlock() + return calls +} + +// GetEccMode calls GetEccModeFunc. +func (mock *Device) GetEccMode() (nvml.EnableState, nvml.EnableState, nvml.Return) { + if mock.GetEccModeFunc == nil { + panic("Device.GetEccModeFunc: method is nil but Device.GetEccMode was just called") + } + callInfo := struct { + }{} + mock.lockGetEccMode.Lock() + mock.calls.GetEccMode = append(mock.calls.GetEccMode, callInfo) + mock.lockGetEccMode.Unlock() + return mock.GetEccModeFunc() +} + +// GetEccModeCalls gets all the calls that were made to GetEccMode. +// Check the length with: +// +// len(mockedDevice.GetEccModeCalls()) +func (mock *Device) GetEccModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEccMode.RLock() + calls = mock.calls.GetEccMode + mock.lockGetEccMode.RUnlock() + return calls +} + +// GetEncoderCapacity calls GetEncoderCapacityFunc. +func (mock *Device) GetEncoderCapacity(encoderType nvml.EncoderType) (int, nvml.Return) { + if mock.GetEncoderCapacityFunc == nil { + panic("Device.GetEncoderCapacityFunc: method is nil but Device.GetEncoderCapacity was just called") + } + callInfo := struct { + EncoderType nvml.EncoderType + }{ + EncoderType: encoderType, + } + mock.lockGetEncoderCapacity.Lock() + mock.calls.GetEncoderCapacity = append(mock.calls.GetEncoderCapacity, callInfo) + mock.lockGetEncoderCapacity.Unlock() + return mock.GetEncoderCapacityFunc(encoderType) +} + +// GetEncoderCapacityCalls gets all the calls that were made to GetEncoderCapacity. +// Check the length with: +// +// len(mockedDevice.GetEncoderCapacityCalls()) +func (mock *Device) GetEncoderCapacityCalls() []struct { + EncoderType nvml.EncoderType +} { + var calls []struct { + EncoderType nvml.EncoderType + } + mock.lockGetEncoderCapacity.RLock() + calls = mock.calls.GetEncoderCapacity + mock.lockGetEncoderCapacity.RUnlock() + return calls +} + +// GetEncoderSessions calls GetEncoderSessionsFunc. +func (mock *Device) GetEncoderSessions() ([]nvml.EncoderSessionInfo, nvml.Return) { + if mock.GetEncoderSessionsFunc == nil { + panic("Device.GetEncoderSessionsFunc: method is nil but Device.GetEncoderSessions was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderSessions.Lock() + mock.calls.GetEncoderSessions = append(mock.calls.GetEncoderSessions, callInfo) + mock.lockGetEncoderSessions.Unlock() + return mock.GetEncoderSessionsFunc() +} + +// GetEncoderSessionsCalls gets all the calls that were made to GetEncoderSessions. +// Check the length with: +// +// len(mockedDevice.GetEncoderSessionsCalls()) +func (mock *Device) GetEncoderSessionsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderSessions.RLock() + calls = mock.calls.GetEncoderSessions + mock.lockGetEncoderSessions.RUnlock() + return calls +} + +// GetEncoderStats calls GetEncoderStatsFunc. +func (mock *Device) GetEncoderStats() (int, uint32, uint32, nvml.Return) { + if mock.GetEncoderStatsFunc == nil { + panic("Device.GetEncoderStatsFunc: method is nil but Device.GetEncoderStats was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderStats.Lock() + mock.calls.GetEncoderStats = append(mock.calls.GetEncoderStats, callInfo) + mock.lockGetEncoderStats.Unlock() + return mock.GetEncoderStatsFunc() +} + +// GetEncoderStatsCalls gets all the calls that were made to GetEncoderStats. +// Check the length with: +// +// len(mockedDevice.GetEncoderStatsCalls()) +func (mock *Device) GetEncoderStatsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderStats.RLock() + calls = mock.calls.GetEncoderStats + mock.lockGetEncoderStats.RUnlock() + return calls +} + +// GetEncoderUtilization calls GetEncoderUtilizationFunc. +func (mock *Device) GetEncoderUtilization() (uint32, uint32, nvml.Return) { + if mock.GetEncoderUtilizationFunc == nil { + panic("Device.GetEncoderUtilizationFunc: method is nil but Device.GetEncoderUtilization was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderUtilization.Lock() + mock.calls.GetEncoderUtilization = append(mock.calls.GetEncoderUtilization, callInfo) + mock.lockGetEncoderUtilization.Unlock() + return mock.GetEncoderUtilizationFunc() +} + +// GetEncoderUtilizationCalls gets all the calls that were made to GetEncoderUtilization. +// Check the length with: +// +// len(mockedDevice.GetEncoderUtilizationCalls()) +func (mock *Device) GetEncoderUtilizationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderUtilization.RLock() + calls = mock.calls.GetEncoderUtilization + mock.lockGetEncoderUtilization.RUnlock() + return calls +} + +// GetEnforcedPowerLimit calls GetEnforcedPowerLimitFunc. +func (mock *Device) GetEnforcedPowerLimit() (uint32, nvml.Return) { + if mock.GetEnforcedPowerLimitFunc == nil { + panic("Device.GetEnforcedPowerLimitFunc: method is nil but Device.GetEnforcedPowerLimit was just called") + } + callInfo := struct { + }{} + mock.lockGetEnforcedPowerLimit.Lock() + mock.calls.GetEnforcedPowerLimit = append(mock.calls.GetEnforcedPowerLimit, callInfo) + mock.lockGetEnforcedPowerLimit.Unlock() + return mock.GetEnforcedPowerLimitFunc() +} + +// GetEnforcedPowerLimitCalls gets all the calls that were made to GetEnforcedPowerLimit. +// Check the length with: +// +// len(mockedDevice.GetEnforcedPowerLimitCalls()) +func (mock *Device) GetEnforcedPowerLimitCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEnforcedPowerLimit.RLock() + calls = mock.calls.GetEnforcedPowerLimit + mock.lockGetEnforcedPowerLimit.RUnlock() + return calls +} + +// GetFBCSessions calls GetFBCSessionsFunc. +func (mock *Device) GetFBCSessions() ([]nvml.FBCSessionInfo, nvml.Return) { + if mock.GetFBCSessionsFunc == nil { + panic("Device.GetFBCSessionsFunc: method is nil but Device.GetFBCSessions was just called") + } + callInfo := struct { + }{} + mock.lockGetFBCSessions.Lock() + mock.calls.GetFBCSessions = append(mock.calls.GetFBCSessions, callInfo) + mock.lockGetFBCSessions.Unlock() + return mock.GetFBCSessionsFunc() +} + +// GetFBCSessionsCalls gets all the calls that were made to GetFBCSessions. +// Check the length with: +// +// len(mockedDevice.GetFBCSessionsCalls()) +func (mock *Device) GetFBCSessionsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFBCSessions.RLock() + calls = mock.calls.GetFBCSessions + mock.lockGetFBCSessions.RUnlock() + return calls +} + +// GetFBCStats calls GetFBCStatsFunc. +func (mock *Device) GetFBCStats() (nvml.FBCStats, nvml.Return) { + if mock.GetFBCStatsFunc == nil { + panic("Device.GetFBCStatsFunc: method is nil but Device.GetFBCStats was just called") + } + callInfo := struct { + }{} + mock.lockGetFBCStats.Lock() + mock.calls.GetFBCStats = append(mock.calls.GetFBCStats, callInfo) + mock.lockGetFBCStats.Unlock() + return mock.GetFBCStatsFunc() +} + +// GetFBCStatsCalls gets all the calls that were made to GetFBCStats. +// Check the length with: +// +// len(mockedDevice.GetFBCStatsCalls()) +func (mock *Device) GetFBCStatsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFBCStats.RLock() + calls = mock.calls.GetFBCStats + mock.lockGetFBCStats.RUnlock() + return calls +} + +// GetFanControlPolicy_v2 calls GetFanControlPolicy_v2Func. +func (mock *Device) GetFanControlPolicy_v2(n int) (nvml.FanControlPolicy, nvml.Return) { + if mock.GetFanControlPolicy_v2Func == nil { + panic("Device.GetFanControlPolicy_v2Func: method is nil but Device.GetFanControlPolicy_v2 was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetFanControlPolicy_v2.Lock() + mock.calls.GetFanControlPolicy_v2 = append(mock.calls.GetFanControlPolicy_v2, callInfo) + mock.lockGetFanControlPolicy_v2.Unlock() + return mock.GetFanControlPolicy_v2Func(n) +} + +// GetFanControlPolicy_v2Calls gets all the calls that were made to GetFanControlPolicy_v2. +// Check the length with: +// +// len(mockedDevice.GetFanControlPolicy_v2Calls()) +func (mock *Device) GetFanControlPolicy_v2Calls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetFanControlPolicy_v2.RLock() + calls = mock.calls.GetFanControlPolicy_v2 + mock.lockGetFanControlPolicy_v2.RUnlock() + return calls +} + +// GetFanSpeed calls GetFanSpeedFunc. +func (mock *Device) GetFanSpeed() (uint32, nvml.Return) { + if mock.GetFanSpeedFunc == nil { + panic("Device.GetFanSpeedFunc: method is nil but Device.GetFanSpeed was just called") + } + callInfo := struct { + }{} + mock.lockGetFanSpeed.Lock() + mock.calls.GetFanSpeed = append(mock.calls.GetFanSpeed, callInfo) + mock.lockGetFanSpeed.Unlock() + return mock.GetFanSpeedFunc() +} + +// GetFanSpeedCalls gets all the calls that were made to GetFanSpeed. +// Check the length with: +// +// len(mockedDevice.GetFanSpeedCalls()) +func (mock *Device) GetFanSpeedCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFanSpeed.RLock() + calls = mock.calls.GetFanSpeed + mock.lockGetFanSpeed.RUnlock() + return calls +} + +// GetFanSpeedRPM calls GetFanSpeedRPMFunc. +func (mock *Device) GetFanSpeedRPM() (nvml.FanSpeedInfo, nvml.Return) { + if mock.GetFanSpeedRPMFunc == nil { + panic("Device.GetFanSpeedRPMFunc: method is nil but Device.GetFanSpeedRPM was just called") + } + callInfo := struct { + }{} + mock.lockGetFanSpeedRPM.Lock() + mock.calls.GetFanSpeedRPM = append(mock.calls.GetFanSpeedRPM, callInfo) + mock.lockGetFanSpeedRPM.Unlock() + return mock.GetFanSpeedRPMFunc() +} + +// GetFanSpeedRPMCalls gets all the calls that were made to GetFanSpeedRPM. +// Check the length with: +// +// len(mockedDevice.GetFanSpeedRPMCalls()) +func (mock *Device) GetFanSpeedRPMCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFanSpeedRPM.RLock() + calls = mock.calls.GetFanSpeedRPM + mock.lockGetFanSpeedRPM.RUnlock() + return calls +} + +// GetFanSpeed_v2 calls GetFanSpeed_v2Func. +func (mock *Device) GetFanSpeed_v2(n int) (uint32, nvml.Return) { + if mock.GetFanSpeed_v2Func == nil { + panic("Device.GetFanSpeed_v2Func: method is nil but Device.GetFanSpeed_v2 was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetFanSpeed_v2.Lock() + mock.calls.GetFanSpeed_v2 = append(mock.calls.GetFanSpeed_v2, callInfo) + mock.lockGetFanSpeed_v2.Unlock() + return mock.GetFanSpeed_v2Func(n) +} + +// GetFanSpeed_v2Calls gets all the calls that were made to GetFanSpeed_v2. +// Check the length with: +// +// len(mockedDevice.GetFanSpeed_v2Calls()) +func (mock *Device) GetFanSpeed_v2Calls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetFanSpeed_v2.RLock() + calls = mock.calls.GetFanSpeed_v2 + mock.lockGetFanSpeed_v2.RUnlock() + return calls +} + +// GetFieldValues calls GetFieldValuesFunc. +func (mock *Device) GetFieldValues(fieldValues []nvml.FieldValue) nvml.Return { + if mock.GetFieldValuesFunc == nil { + panic("Device.GetFieldValuesFunc: method is nil but Device.GetFieldValues was just called") + } + callInfo := struct { + FieldValues []nvml.FieldValue + }{ + FieldValues: fieldValues, + } + mock.lockGetFieldValues.Lock() + mock.calls.GetFieldValues = append(mock.calls.GetFieldValues, callInfo) + mock.lockGetFieldValues.Unlock() + return mock.GetFieldValuesFunc(fieldValues) +} + +// GetFieldValuesCalls gets all the calls that were made to GetFieldValues. +// Check the length with: +// +// len(mockedDevice.GetFieldValuesCalls()) +func (mock *Device) GetFieldValuesCalls() []struct { + FieldValues []nvml.FieldValue +} { + var calls []struct { + FieldValues []nvml.FieldValue + } + mock.lockGetFieldValues.RLock() + calls = mock.calls.GetFieldValues + mock.lockGetFieldValues.RUnlock() + return calls +} + +// GetGpcClkMinMaxVfOffset calls GetGpcClkMinMaxVfOffsetFunc. +func (mock *Device) GetGpcClkMinMaxVfOffset() (int, int, nvml.Return) { + if mock.GetGpcClkMinMaxVfOffsetFunc == nil { + panic("Device.GetGpcClkMinMaxVfOffsetFunc: method is nil but Device.GetGpcClkMinMaxVfOffset was just called") + } + callInfo := struct { + }{} + mock.lockGetGpcClkMinMaxVfOffset.Lock() + mock.calls.GetGpcClkMinMaxVfOffset = append(mock.calls.GetGpcClkMinMaxVfOffset, callInfo) + mock.lockGetGpcClkMinMaxVfOffset.Unlock() + return mock.GetGpcClkMinMaxVfOffsetFunc() +} + +// GetGpcClkMinMaxVfOffsetCalls gets all the calls that were made to GetGpcClkMinMaxVfOffset. +// Check the length with: +// +// len(mockedDevice.GetGpcClkMinMaxVfOffsetCalls()) +func (mock *Device) GetGpcClkMinMaxVfOffsetCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpcClkMinMaxVfOffset.RLock() + calls = mock.calls.GetGpcClkMinMaxVfOffset + mock.lockGetGpcClkMinMaxVfOffset.RUnlock() + return calls +} + +// GetGpcClkVfOffset calls GetGpcClkVfOffsetFunc. +func (mock *Device) GetGpcClkVfOffset() (int, nvml.Return) { + if mock.GetGpcClkVfOffsetFunc == nil { + panic("Device.GetGpcClkVfOffsetFunc: method is nil but Device.GetGpcClkVfOffset was just called") + } + callInfo := struct { + }{} + mock.lockGetGpcClkVfOffset.Lock() + mock.calls.GetGpcClkVfOffset = append(mock.calls.GetGpcClkVfOffset, callInfo) + mock.lockGetGpcClkVfOffset.Unlock() + return mock.GetGpcClkVfOffsetFunc() +} + +// GetGpcClkVfOffsetCalls gets all the calls that were made to GetGpcClkVfOffset. +// Check the length with: +// +// len(mockedDevice.GetGpcClkVfOffsetCalls()) +func (mock *Device) GetGpcClkVfOffsetCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpcClkVfOffset.RLock() + calls = mock.calls.GetGpcClkVfOffset + mock.lockGetGpcClkVfOffset.RUnlock() + return calls +} + +// GetGpuFabricInfo calls GetGpuFabricInfoFunc. +func (mock *Device) GetGpuFabricInfo() (nvml.GpuFabricInfo, nvml.Return) { + if mock.GetGpuFabricInfoFunc == nil { + panic("Device.GetGpuFabricInfoFunc: method is nil but Device.GetGpuFabricInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuFabricInfo.Lock() + mock.calls.GetGpuFabricInfo = append(mock.calls.GetGpuFabricInfo, callInfo) + mock.lockGetGpuFabricInfo.Unlock() + return mock.GetGpuFabricInfoFunc() +} + +// GetGpuFabricInfoCalls gets all the calls that were made to GetGpuFabricInfo. +// Check the length with: +// +// len(mockedDevice.GetGpuFabricInfoCalls()) +func (mock *Device) GetGpuFabricInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuFabricInfo.RLock() + calls = mock.calls.GetGpuFabricInfo + mock.lockGetGpuFabricInfo.RUnlock() + return calls +} + +// GetGpuFabricInfoV calls GetGpuFabricInfoVFunc. +func (mock *Device) GetGpuFabricInfoV() nvml.GpuFabricInfoHandler { + if mock.GetGpuFabricInfoVFunc == nil { + panic("Device.GetGpuFabricInfoVFunc: method is nil but Device.GetGpuFabricInfoV was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuFabricInfoV.Lock() + mock.calls.GetGpuFabricInfoV = append(mock.calls.GetGpuFabricInfoV, callInfo) + mock.lockGetGpuFabricInfoV.Unlock() + return mock.GetGpuFabricInfoVFunc() +} + +// GetGpuFabricInfoVCalls gets all the calls that were made to GetGpuFabricInfoV. +// Check the length with: +// +// len(mockedDevice.GetGpuFabricInfoVCalls()) +func (mock *Device) GetGpuFabricInfoVCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuFabricInfoV.RLock() + calls = mock.calls.GetGpuFabricInfoV + mock.lockGetGpuFabricInfoV.RUnlock() + return calls +} + +// GetGpuInstanceById calls GetGpuInstanceByIdFunc. +func (mock *Device) GetGpuInstanceById(n int) (nvml.GpuInstance, nvml.Return) { + if mock.GetGpuInstanceByIdFunc == nil { + panic("Device.GetGpuInstanceByIdFunc: method is nil but Device.GetGpuInstanceById was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetGpuInstanceById.Lock() + mock.calls.GetGpuInstanceById = append(mock.calls.GetGpuInstanceById, callInfo) + mock.lockGetGpuInstanceById.Unlock() + return mock.GetGpuInstanceByIdFunc(n) +} + +// GetGpuInstanceByIdCalls gets all the calls that were made to GetGpuInstanceById. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceByIdCalls()) +func (mock *Device) GetGpuInstanceByIdCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetGpuInstanceById.RLock() + calls = mock.calls.GetGpuInstanceById + mock.lockGetGpuInstanceById.RUnlock() + return calls +} + +// GetGpuInstanceId calls GetGpuInstanceIdFunc. +func (mock *Device) GetGpuInstanceId() (int, nvml.Return) { + if mock.GetGpuInstanceIdFunc == nil { + panic("Device.GetGpuInstanceIdFunc: method is nil but Device.GetGpuInstanceId was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuInstanceId.Lock() + mock.calls.GetGpuInstanceId = append(mock.calls.GetGpuInstanceId, callInfo) + mock.lockGetGpuInstanceId.Unlock() + return mock.GetGpuInstanceIdFunc() +} + +// GetGpuInstanceIdCalls gets all the calls that were made to GetGpuInstanceId. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceIdCalls()) +func (mock *Device) GetGpuInstanceIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuInstanceId.RLock() + calls = mock.calls.GetGpuInstanceId + mock.lockGetGpuInstanceId.RUnlock() + return calls +} + +// GetGpuInstancePossiblePlacements calls GetGpuInstancePossiblePlacementsFunc. +func (mock *Device) GetGpuInstancePossiblePlacements(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) { + if mock.GetGpuInstancePossiblePlacementsFunc == nil { + panic("Device.GetGpuInstancePossiblePlacementsFunc: method is nil but Device.GetGpuInstancePossiblePlacements was just called") + } + callInfo := struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockGetGpuInstancePossiblePlacements.Lock() + mock.calls.GetGpuInstancePossiblePlacements = append(mock.calls.GetGpuInstancePossiblePlacements, callInfo) + mock.lockGetGpuInstancePossiblePlacements.Unlock() + return mock.GetGpuInstancePossiblePlacementsFunc(gpuInstanceProfileInfo) +} + +// GetGpuInstancePossiblePlacementsCalls gets all the calls that were made to GetGpuInstancePossiblePlacements. +// Check the length with: +// +// len(mockedDevice.GetGpuInstancePossiblePlacementsCalls()) +func (mock *Device) GetGpuInstancePossiblePlacementsCalls() []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockGetGpuInstancePossiblePlacements.RLock() + calls = mock.calls.GetGpuInstancePossiblePlacements + mock.lockGetGpuInstancePossiblePlacements.RUnlock() + return calls +} + +// GetGpuInstanceProfileInfo calls GetGpuInstanceProfileInfoFunc. +func (mock *Device) GetGpuInstanceProfileInfo(n int) (nvml.GpuInstanceProfileInfo, nvml.Return) { + if mock.GetGpuInstanceProfileInfoFunc == nil { + panic("Device.GetGpuInstanceProfileInfoFunc: method is nil but Device.GetGpuInstanceProfileInfo was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetGpuInstanceProfileInfo.Lock() + mock.calls.GetGpuInstanceProfileInfo = append(mock.calls.GetGpuInstanceProfileInfo, callInfo) + mock.lockGetGpuInstanceProfileInfo.Unlock() + return mock.GetGpuInstanceProfileInfoFunc(n) +} + +// GetGpuInstanceProfileInfoCalls gets all the calls that were made to GetGpuInstanceProfileInfo. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceProfileInfoCalls()) +func (mock *Device) GetGpuInstanceProfileInfoCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetGpuInstanceProfileInfo.RLock() + calls = mock.calls.GetGpuInstanceProfileInfo + mock.lockGetGpuInstanceProfileInfo.RUnlock() + return calls +} + +// GetGpuInstanceProfileInfoByIdV calls GetGpuInstanceProfileInfoByIdVFunc. +func (mock *Device) GetGpuInstanceProfileInfoByIdV(n int) nvml.GpuInstanceProfileInfoByIdHandler { + if mock.GetGpuInstanceProfileInfoByIdVFunc == nil { + panic("Device.GetGpuInstanceProfileInfoByIdVFunc: method is nil but Device.GetGpuInstanceProfileInfoByIdV was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetGpuInstanceProfileInfoByIdV.Lock() + mock.calls.GetGpuInstanceProfileInfoByIdV = append(mock.calls.GetGpuInstanceProfileInfoByIdV, callInfo) + mock.lockGetGpuInstanceProfileInfoByIdV.Unlock() + return mock.GetGpuInstanceProfileInfoByIdVFunc(n) +} + +// GetGpuInstanceProfileInfoByIdVCalls gets all the calls that were made to GetGpuInstanceProfileInfoByIdV. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceProfileInfoByIdVCalls()) +func (mock *Device) GetGpuInstanceProfileInfoByIdVCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetGpuInstanceProfileInfoByIdV.RLock() + calls = mock.calls.GetGpuInstanceProfileInfoByIdV + mock.lockGetGpuInstanceProfileInfoByIdV.RUnlock() + return calls +} + +// GetGpuInstanceProfileInfoV calls GetGpuInstanceProfileInfoVFunc. +func (mock *Device) GetGpuInstanceProfileInfoV(n int) nvml.GpuInstanceProfileInfoHandler { + if mock.GetGpuInstanceProfileInfoVFunc == nil { + panic("Device.GetGpuInstanceProfileInfoVFunc: method is nil but Device.GetGpuInstanceProfileInfoV was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetGpuInstanceProfileInfoV.Lock() + mock.calls.GetGpuInstanceProfileInfoV = append(mock.calls.GetGpuInstanceProfileInfoV, callInfo) + mock.lockGetGpuInstanceProfileInfoV.Unlock() + return mock.GetGpuInstanceProfileInfoVFunc(n) +} + +// GetGpuInstanceProfileInfoVCalls gets all the calls that were made to GetGpuInstanceProfileInfoV. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceProfileInfoVCalls()) +func (mock *Device) GetGpuInstanceProfileInfoVCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetGpuInstanceProfileInfoV.RLock() + calls = mock.calls.GetGpuInstanceProfileInfoV + mock.lockGetGpuInstanceProfileInfoV.RUnlock() + return calls +} + +// GetGpuInstanceRemainingCapacity calls GetGpuInstanceRemainingCapacityFunc. +func (mock *Device) GetGpuInstanceRemainingCapacity(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) { + if mock.GetGpuInstanceRemainingCapacityFunc == nil { + panic("Device.GetGpuInstanceRemainingCapacityFunc: method is nil but Device.GetGpuInstanceRemainingCapacity was just called") + } + callInfo := struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockGetGpuInstanceRemainingCapacity.Lock() + mock.calls.GetGpuInstanceRemainingCapacity = append(mock.calls.GetGpuInstanceRemainingCapacity, callInfo) + mock.lockGetGpuInstanceRemainingCapacity.Unlock() + return mock.GetGpuInstanceRemainingCapacityFunc(gpuInstanceProfileInfo) +} + +// GetGpuInstanceRemainingCapacityCalls gets all the calls that were made to GetGpuInstanceRemainingCapacity. +// Check the length with: +// +// len(mockedDevice.GetGpuInstanceRemainingCapacityCalls()) +func (mock *Device) GetGpuInstanceRemainingCapacityCalls() []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockGetGpuInstanceRemainingCapacity.RLock() + calls = mock.calls.GetGpuInstanceRemainingCapacity + mock.lockGetGpuInstanceRemainingCapacity.RUnlock() + return calls +} + +// GetGpuInstances calls GetGpuInstancesFunc. +func (mock *Device) GetGpuInstances(gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { + if mock.GetGpuInstancesFunc == nil { + panic("Device.GetGpuInstancesFunc: method is nil but Device.GetGpuInstances was just called") + } + callInfo := struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockGetGpuInstances.Lock() + mock.calls.GetGpuInstances = append(mock.calls.GetGpuInstances, callInfo) + mock.lockGetGpuInstances.Unlock() + return mock.GetGpuInstancesFunc(gpuInstanceProfileInfo) +} + +// GetGpuInstancesCalls gets all the calls that were made to GetGpuInstances. +// Check the length with: +// +// len(mockedDevice.GetGpuInstancesCalls()) +func (mock *Device) GetGpuInstancesCalls() []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockGetGpuInstances.RLock() + calls = mock.calls.GetGpuInstances + mock.lockGetGpuInstances.RUnlock() + return calls +} + +// GetGpuMaxPcieLinkGeneration calls GetGpuMaxPcieLinkGenerationFunc. +func (mock *Device) GetGpuMaxPcieLinkGeneration() (int, nvml.Return) { + if mock.GetGpuMaxPcieLinkGenerationFunc == nil { + panic("Device.GetGpuMaxPcieLinkGenerationFunc: method is nil but Device.GetGpuMaxPcieLinkGeneration was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuMaxPcieLinkGeneration.Lock() + mock.calls.GetGpuMaxPcieLinkGeneration = append(mock.calls.GetGpuMaxPcieLinkGeneration, callInfo) + mock.lockGetGpuMaxPcieLinkGeneration.Unlock() + return mock.GetGpuMaxPcieLinkGenerationFunc() +} + +// GetGpuMaxPcieLinkGenerationCalls gets all the calls that were made to GetGpuMaxPcieLinkGeneration. +// Check the length with: +// +// len(mockedDevice.GetGpuMaxPcieLinkGenerationCalls()) +func (mock *Device) GetGpuMaxPcieLinkGenerationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuMaxPcieLinkGeneration.RLock() + calls = mock.calls.GetGpuMaxPcieLinkGeneration + mock.lockGetGpuMaxPcieLinkGeneration.RUnlock() + return calls +} + +// GetGpuOperationMode calls GetGpuOperationModeFunc. +func (mock *Device) GetGpuOperationMode() (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) { + if mock.GetGpuOperationModeFunc == nil { + panic("Device.GetGpuOperationModeFunc: method is nil but Device.GetGpuOperationMode was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuOperationMode.Lock() + mock.calls.GetGpuOperationMode = append(mock.calls.GetGpuOperationMode, callInfo) + mock.lockGetGpuOperationMode.Unlock() + return mock.GetGpuOperationModeFunc() +} + +// GetGpuOperationModeCalls gets all the calls that were made to GetGpuOperationMode. +// Check the length with: +// +// len(mockedDevice.GetGpuOperationModeCalls()) +func (mock *Device) GetGpuOperationModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuOperationMode.RLock() + calls = mock.calls.GetGpuOperationMode + mock.lockGetGpuOperationMode.RUnlock() + return calls +} + +// GetGraphicsRunningProcesses calls GetGraphicsRunningProcessesFunc. +func (mock *Device) GetGraphicsRunningProcesses() ([]nvml.ProcessInfo, nvml.Return) { + if mock.GetGraphicsRunningProcessesFunc == nil { + panic("Device.GetGraphicsRunningProcessesFunc: method is nil but Device.GetGraphicsRunningProcesses was just called") + } + callInfo := struct { + }{} + mock.lockGetGraphicsRunningProcesses.Lock() + mock.calls.GetGraphicsRunningProcesses = append(mock.calls.GetGraphicsRunningProcesses, callInfo) + mock.lockGetGraphicsRunningProcesses.Unlock() + return mock.GetGraphicsRunningProcessesFunc() +} + +// GetGraphicsRunningProcessesCalls gets all the calls that were made to GetGraphicsRunningProcesses. +// Check the length with: +// +// len(mockedDevice.GetGraphicsRunningProcessesCalls()) +func (mock *Device) GetGraphicsRunningProcessesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGraphicsRunningProcesses.RLock() + calls = mock.calls.GetGraphicsRunningProcesses + mock.lockGetGraphicsRunningProcesses.RUnlock() + return calls +} + +// GetGridLicensableFeatures calls GetGridLicensableFeaturesFunc. +func (mock *Device) GetGridLicensableFeatures() (nvml.GridLicensableFeatures, nvml.Return) { + if mock.GetGridLicensableFeaturesFunc == nil { + panic("Device.GetGridLicensableFeaturesFunc: method is nil but Device.GetGridLicensableFeatures was just called") + } + callInfo := struct { + }{} + mock.lockGetGridLicensableFeatures.Lock() + mock.calls.GetGridLicensableFeatures = append(mock.calls.GetGridLicensableFeatures, callInfo) + mock.lockGetGridLicensableFeatures.Unlock() + return mock.GetGridLicensableFeaturesFunc() +} + +// GetGridLicensableFeaturesCalls gets all the calls that were made to GetGridLicensableFeatures. +// Check the length with: +// +// len(mockedDevice.GetGridLicensableFeaturesCalls()) +func (mock *Device) GetGridLicensableFeaturesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGridLicensableFeatures.RLock() + calls = mock.calls.GetGridLicensableFeatures + mock.lockGetGridLicensableFeatures.RUnlock() + return calls +} + +// GetGspFirmwareMode calls GetGspFirmwareModeFunc. +func (mock *Device) GetGspFirmwareMode() (bool, bool, nvml.Return) { + if mock.GetGspFirmwareModeFunc == nil { + panic("Device.GetGspFirmwareModeFunc: method is nil but Device.GetGspFirmwareMode was just called") + } + callInfo := struct { + }{} + mock.lockGetGspFirmwareMode.Lock() + mock.calls.GetGspFirmwareMode = append(mock.calls.GetGspFirmwareMode, callInfo) + mock.lockGetGspFirmwareMode.Unlock() + return mock.GetGspFirmwareModeFunc() +} + +// GetGspFirmwareModeCalls gets all the calls that were made to GetGspFirmwareMode. +// Check the length with: +// +// len(mockedDevice.GetGspFirmwareModeCalls()) +func (mock *Device) GetGspFirmwareModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGspFirmwareMode.RLock() + calls = mock.calls.GetGspFirmwareMode + mock.lockGetGspFirmwareMode.RUnlock() + return calls +} + +// GetGspFirmwareVersion calls GetGspFirmwareVersionFunc. +func (mock *Device) GetGspFirmwareVersion() (string, nvml.Return) { + if mock.GetGspFirmwareVersionFunc == nil { + panic("Device.GetGspFirmwareVersionFunc: method is nil but Device.GetGspFirmwareVersion was just called") + } + callInfo := struct { + }{} + mock.lockGetGspFirmwareVersion.Lock() + mock.calls.GetGspFirmwareVersion = append(mock.calls.GetGspFirmwareVersion, callInfo) + mock.lockGetGspFirmwareVersion.Unlock() + return mock.GetGspFirmwareVersionFunc() +} + +// GetGspFirmwareVersionCalls gets all the calls that were made to GetGspFirmwareVersion. +// Check the length with: +// +// len(mockedDevice.GetGspFirmwareVersionCalls()) +func (mock *Device) GetGspFirmwareVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGspFirmwareVersion.RLock() + calls = mock.calls.GetGspFirmwareVersion + mock.lockGetGspFirmwareVersion.RUnlock() + return calls +} + +// GetHostVgpuMode calls GetHostVgpuModeFunc. +func (mock *Device) GetHostVgpuMode() (nvml.HostVgpuMode, nvml.Return) { + if mock.GetHostVgpuModeFunc == nil { + panic("Device.GetHostVgpuModeFunc: method is nil but Device.GetHostVgpuMode was just called") + } + callInfo := struct { + }{} + mock.lockGetHostVgpuMode.Lock() + mock.calls.GetHostVgpuMode = append(mock.calls.GetHostVgpuMode, callInfo) + mock.lockGetHostVgpuMode.Unlock() + return mock.GetHostVgpuModeFunc() +} + +// GetHostVgpuModeCalls gets all the calls that were made to GetHostVgpuMode. +// Check the length with: +// +// len(mockedDevice.GetHostVgpuModeCalls()) +func (mock *Device) GetHostVgpuModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetHostVgpuMode.RLock() + calls = mock.calls.GetHostVgpuMode + mock.lockGetHostVgpuMode.RUnlock() + return calls +} + +// GetIndex calls GetIndexFunc. +func (mock *Device) GetIndex() (int, nvml.Return) { + if mock.GetIndexFunc == nil { + panic("Device.GetIndexFunc: method is nil but Device.GetIndex was just called") + } + callInfo := struct { + }{} + mock.lockGetIndex.Lock() + mock.calls.GetIndex = append(mock.calls.GetIndex, callInfo) + mock.lockGetIndex.Unlock() + return mock.GetIndexFunc() +} + +// GetIndexCalls gets all the calls that were made to GetIndex. +// Check the length with: +// +// len(mockedDevice.GetIndexCalls()) +func (mock *Device) GetIndexCalls() []struct { +} { + var calls []struct { + } + mock.lockGetIndex.RLock() + calls = mock.calls.GetIndex + mock.lockGetIndex.RUnlock() + return calls +} + +// GetInforomConfigurationChecksum calls GetInforomConfigurationChecksumFunc. +func (mock *Device) GetInforomConfigurationChecksum() (uint32, nvml.Return) { + if mock.GetInforomConfigurationChecksumFunc == nil { + panic("Device.GetInforomConfigurationChecksumFunc: method is nil but Device.GetInforomConfigurationChecksum was just called") + } + callInfo := struct { + }{} + mock.lockGetInforomConfigurationChecksum.Lock() + mock.calls.GetInforomConfigurationChecksum = append(mock.calls.GetInforomConfigurationChecksum, callInfo) + mock.lockGetInforomConfigurationChecksum.Unlock() + return mock.GetInforomConfigurationChecksumFunc() +} + +// GetInforomConfigurationChecksumCalls gets all the calls that were made to GetInforomConfigurationChecksum. +// Check the length with: +// +// len(mockedDevice.GetInforomConfigurationChecksumCalls()) +func (mock *Device) GetInforomConfigurationChecksumCalls() []struct { +} { + var calls []struct { + } + mock.lockGetInforomConfigurationChecksum.RLock() + calls = mock.calls.GetInforomConfigurationChecksum + mock.lockGetInforomConfigurationChecksum.RUnlock() + return calls +} + +// GetInforomImageVersion calls GetInforomImageVersionFunc. +func (mock *Device) GetInforomImageVersion() (string, nvml.Return) { + if mock.GetInforomImageVersionFunc == nil { + panic("Device.GetInforomImageVersionFunc: method is nil but Device.GetInforomImageVersion was just called") + } + callInfo := struct { + }{} + mock.lockGetInforomImageVersion.Lock() + mock.calls.GetInforomImageVersion = append(mock.calls.GetInforomImageVersion, callInfo) + mock.lockGetInforomImageVersion.Unlock() + return mock.GetInforomImageVersionFunc() +} + +// GetInforomImageVersionCalls gets all the calls that were made to GetInforomImageVersion. +// Check the length with: +// +// len(mockedDevice.GetInforomImageVersionCalls()) +func (mock *Device) GetInforomImageVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetInforomImageVersion.RLock() + calls = mock.calls.GetInforomImageVersion + mock.lockGetInforomImageVersion.RUnlock() + return calls +} + +// GetInforomVersion calls GetInforomVersionFunc. +func (mock *Device) GetInforomVersion(inforomObject nvml.InforomObject) (string, nvml.Return) { + if mock.GetInforomVersionFunc == nil { + panic("Device.GetInforomVersionFunc: method is nil but Device.GetInforomVersion was just called") + } + callInfo := struct { + InforomObject nvml.InforomObject + }{ + InforomObject: inforomObject, + } + mock.lockGetInforomVersion.Lock() + mock.calls.GetInforomVersion = append(mock.calls.GetInforomVersion, callInfo) + mock.lockGetInforomVersion.Unlock() + return mock.GetInforomVersionFunc(inforomObject) +} + +// GetInforomVersionCalls gets all the calls that were made to GetInforomVersion. +// Check the length with: +// +// len(mockedDevice.GetInforomVersionCalls()) +func (mock *Device) GetInforomVersionCalls() []struct { + InforomObject nvml.InforomObject +} { + var calls []struct { + InforomObject nvml.InforomObject + } + mock.lockGetInforomVersion.RLock() + calls = mock.calls.GetInforomVersion + mock.lockGetInforomVersion.RUnlock() + return calls +} + +// GetIrqNum calls GetIrqNumFunc. +func (mock *Device) GetIrqNum() (int, nvml.Return) { + if mock.GetIrqNumFunc == nil { + panic("Device.GetIrqNumFunc: method is nil but Device.GetIrqNum was just called") + } + callInfo := struct { + }{} + mock.lockGetIrqNum.Lock() + mock.calls.GetIrqNum = append(mock.calls.GetIrqNum, callInfo) + mock.lockGetIrqNum.Unlock() + return mock.GetIrqNumFunc() +} + +// GetIrqNumCalls gets all the calls that were made to GetIrqNum. +// Check the length with: +// +// len(mockedDevice.GetIrqNumCalls()) +func (mock *Device) GetIrqNumCalls() []struct { +} { + var calls []struct { + } + mock.lockGetIrqNum.RLock() + calls = mock.calls.GetIrqNum + mock.lockGetIrqNum.RUnlock() + return calls +} + +// GetJpgUtilization calls GetJpgUtilizationFunc. +func (mock *Device) GetJpgUtilization() (uint32, uint32, nvml.Return) { + if mock.GetJpgUtilizationFunc == nil { + panic("Device.GetJpgUtilizationFunc: method is nil but Device.GetJpgUtilization was just called") + } + callInfo := struct { + }{} + mock.lockGetJpgUtilization.Lock() + mock.calls.GetJpgUtilization = append(mock.calls.GetJpgUtilization, callInfo) + mock.lockGetJpgUtilization.Unlock() + return mock.GetJpgUtilizationFunc() +} + +// GetJpgUtilizationCalls gets all the calls that were made to GetJpgUtilization. +// Check the length with: +// +// len(mockedDevice.GetJpgUtilizationCalls()) +func (mock *Device) GetJpgUtilizationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetJpgUtilization.RLock() + calls = mock.calls.GetJpgUtilization + mock.lockGetJpgUtilization.RUnlock() + return calls +} + +// GetLastBBXFlushTime calls GetLastBBXFlushTimeFunc. +func (mock *Device) GetLastBBXFlushTime() (uint64, uint, nvml.Return) { + if mock.GetLastBBXFlushTimeFunc == nil { + panic("Device.GetLastBBXFlushTimeFunc: method is nil but Device.GetLastBBXFlushTime was just called") + } + callInfo := struct { + }{} + mock.lockGetLastBBXFlushTime.Lock() + mock.calls.GetLastBBXFlushTime = append(mock.calls.GetLastBBXFlushTime, callInfo) + mock.lockGetLastBBXFlushTime.Unlock() + return mock.GetLastBBXFlushTimeFunc() +} + +// GetLastBBXFlushTimeCalls gets all the calls that were made to GetLastBBXFlushTime. +// Check the length with: +// +// len(mockedDevice.GetLastBBXFlushTimeCalls()) +func (mock *Device) GetLastBBXFlushTimeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetLastBBXFlushTime.RLock() + calls = mock.calls.GetLastBBXFlushTime + mock.lockGetLastBBXFlushTime.RUnlock() + return calls +} + +// GetMPSComputeRunningProcesses calls GetMPSComputeRunningProcessesFunc. +func (mock *Device) GetMPSComputeRunningProcesses() ([]nvml.ProcessInfo, nvml.Return) { + if mock.GetMPSComputeRunningProcessesFunc == nil { + panic("Device.GetMPSComputeRunningProcessesFunc: method is nil but Device.GetMPSComputeRunningProcesses was just called") + } + callInfo := struct { + }{} + mock.lockGetMPSComputeRunningProcesses.Lock() + mock.calls.GetMPSComputeRunningProcesses = append(mock.calls.GetMPSComputeRunningProcesses, callInfo) + mock.lockGetMPSComputeRunningProcesses.Unlock() + return mock.GetMPSComputeRunningProcessesFunc() +} + +// GetMPSComputeRunningProcessesCalls gets all the calls that were made to GetMPSComputeRunningProcesses. +// Check the length with: +// +// len(mockedDevice.GetMPSComputeRunningProcessesCalls()) +func (mock *Device) GetMPSComputeRunningProcessesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMPSComputeRunningProcesses.RLock() + calls = mock.calls.GetMPSComputeRunningProcesses + mock.lockGetMPSComputeRunningProcesses.RUnlock() + return calls +} + +// GetMarginTemperature calls GetMarginTemperatureFunc. +func (mock *Device) GetMarginTemperature() (nvml.MarginTemperature, nvml.Return) { + if mock.GetMarginTemperatureFunc == nil { + panic("Device.GetMarginTemperatureFunc: method is nil but Device.GetMarginTemperature was just called") + } + callInfo := struct { + }{} + mock.lockGetMarginTemperature.Lock() + mock.calls.GetMarginTemperature = append(mock.calls.GetMarginTemperature, callInfo) + mock.lockGetMarginTemperature.Unlock() + return mock.GetMarginTemperatureFunc() +} + +// GetMarginTemperatureCalls gets all the calls that were made to GetMarginTemperature. +// Check the length with: +// +// len(mockedDevice.GetMarginTemperatureCalls()) +func (mock *Device) GetMarginTemperatureCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMarginTemperature.RLock() + calls = mock.calls.GetMarginTemperature + mock.lockGetMarginTemperature.RUnlock() + return calls +} + +// GetMaxClockInfo calls GetMaxClockInfoFunc. +func (mock *Device) GetMaxClockInfo(clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.GetMaxClockInfoFunc == nil { + panic("Device.GetMaxClockInfoFunc: method is nil but Device.GetMaxClockInfo was just called") + } + callInfo := struct { + ClockType nvml.ClockType + }{ + ClockType: clockType, + } + mock.lockGetMaxClockInfo.Lock() + mock.calls.GetMaxClockInfo = append(mock.calls.GetMaxClockInfo, callInfo) + mock.lockGetMaxClockInfo.Unlock() + return mock.GetMaxClockInfoFunc(clockType) +} + +// GetMaxClockInfoCalls gets all the calls that were made to GetMaxClockInfo. +// Check the length with: +// +// len(mockedDevice.GetMaxClockInfoCalls()) +func (mock *Device) GetMaxClockInfoCalls() []struct { + ClockType nvml.ClockType +} { + var calls []struct { + ClockType nvml.ClockType + } + mock.lockGetMaxClockInfo.RLock() + calls = mock.calls.GetMaxClockInfo + mock.lockGetMaxClockInfo.RUnlock() + return calls +} + +// GetMaxCustomerBoostClock calls GetMaxCustomerBoostClockFunc. +func (mock *Device) GetMaxCustomerBoostClock(clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.GetMaxCustomerBoostClockFunc == nil { + panic("Device.GetMaxCustomerBoostClockFunc: method is nil but Device.GetMaxCustomerBoostClock was just called") + } + callInfo := struct { + ClockType nvml.ClockType + }{ + ClockType: clockType, + } + mock.lockGetMaxCustomerBoostClock.Lock() + mock.calls.GetMaxCustomerBoostClock = append(mock.calls.GetMaxCustomerBoostClock, callInfo) + mock.lockGetMaxCustomerBoostClock.Unlock() + return mock.GetMaxCustomerBoostClockFunc(clockType) +} + +// GetMaxCustomerBoostClockCalls gets all the calls that were made to GetMaxCustomerBoostClock. +// Check the length with: +// +// len(mockedDevice.GetMaxCustomerBoostClockCalls()) +func (mock *Device) GetMaxCustomerBoostClockCalls() []struct { + ClockType nvml.ClockType +} { + var calls []struct { + ClockType nvml.ClockType + } + mock.lockGetMaxCustomerBoostClock.RLock() + calls = mock.calls.GetMaxCustomerBoostClock + mock.lockGetMaxCustomerBoostClock.RUnlock() + return calls +} + +// GetMaxMigDeviceCount calls GetMaxMigDeviceCountFunc. +func (mock *Device) GetMaxMigDeviceCount() (int, nvml.Return) { + if mock.GetMaxMigDeviceCountFunc == nil { + panic("Device.GetMaxMigDeviceCountFunc: method is nil but Device.GetMaxMigDeviceCount was just called") + } + callInfo := struct { + }{} + mock.lockGetMaxMigDeviceCount.Lock() + mock.calls.GetMaxMigDeviceCount = append(mock.calls.GetMaxMigDeviceCount, callInfo) + mock.lockGetMaxMigDeviceCount.Unlock() + return mock.GetMaxMigDeviceCountFunc() +} + +// GetMaxMigDeviceCountCalls gets all the calls that were made to GetMaxMigDeviceCount. +// Check the length with: +// +// len(mockedDevice.GetMaxMigDeviceCountCalls()) +func (mock *Device) GetMaxMigDeviceCountCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMaxMigDeviceCount.RLock() + calls = mock.calls.GetMaxMigDeviceCount + mock.lockGetMaxMigDeviceCount.RUnlock() + return calls +} + +// GetMaxPcieLinkGeneration calls GetMaxPcieLinkGenerationFunc. +func (mock *Device) GetMaxPcieLinkGeneration() (int, nvml.Return) { + if mock.GetMaxPcieLinkGenerationFunc == nil { + panic("Device.GetMaxPcieLinkGenerationFunc: method is nil but Device.GetMaxPcieLinkGeneration was just called") + } + callInfo := struct { + }{} + mock.lockGetMaxPcieLinkGeneration.Lock() + mock.calls.GetMaxPcieLinkGeneration = append(mock.calls.GetMaxPcieLinkGeneration, callInfo) + mock.lockGetMaxPcieLinkGeneration.Unlock() + return mock.GetMaxPcieLinkGenerationFunc() +} + +// GetMaxPcieLinkGenerationCalls gets all the calls that were made to GetMaxPcieLinkGeneration. +// Check the length with: +// +// len(mockedDevice.GetMaxPcieLinkGenerationCalls()) +func (mock *Device) GetMaxPcieLinkGenerationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMaxPcieLinkGeneration.RLock() + calls = mock.calls.GetMaxPcieLinkGeneration + mock.lockGetMaxPcieLinkGeneration.RUnlock() + return calls +} + +// GetMaxPcieLinkWidth calls GetMaxPcieLinkWidthFunc. +func (mock *Device) GetMaxPcieLinkWidth() (int, nvml.Return) { + if mock.GetMaxPcieLinkWidthFunc == nil { + panic("Device.GetMaxPcieLinkWidthFunc: method is nil but Device.GetMaxPcieLinkWidth was just called") + } + callInfo := struct { + }{} + mock.lockGetMaxPcieLinkWidth.Lock() + mock.calls.GetMaxPcieLinkWidth = append(mock.calls.GetMaxPcieLinkWidth, callInfo) + mock.lockGetMaxPcieLinkWidth.Unlock() + return mock.GetMaxPcieLinkWidthFunc() +} + +// GetMaxPcieLinkWidthCalls gets all the calls that were made to GetMaxPcieLinkWidth. +// Check the length with: +// +// len(mockedDevice.GetMaxPcieLinkWidthCalls()) +func (mock *Device) GetMaxPcieLinkWidthCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMaxPcieLinkWidth.RLock() + calls = mock.calls.GetMaxPcieLinkWidth + mock.lockGetMaxPcieLinkWidth.RUnlock() + return calls +} + +// GetMemClkMinMaxVfOffset calls GetMemClkMinMaxVfOffsetFunc. +func (mock *Device) GetMemClkMinMaxVfOffset() (int, int, nvml.Return) { + if mock.GetMemClkMinMaxVfOffsetFunc == nil { + panic("Device.GetMemClkMinMaxVfOffsetFunc: method is nil but Device.GetMemClkMinMaxVfOffset was just called") + } + callInfo := struct { + }{} + mock.lockGetMemClkMinMaxVfOffset.Lock() + mock.calls.GetMemClkMinMaxVfOffset = append(mock.calls.GetMemClkMinMaxVfOffset, callInfo) + mock.lockGetMemClkMinMaxVfOffset.Unlock() + return mock.GetMemClkMinMaxVfOffsetFunc() +} + +// GetMemClkMinMaxVfOffsetCalls gets all the calls that were made to GetMemClkMinMaxVfOffset. +// Check the length with: +// +// len(mockedDevice.GetMemClkMinMaxVfOffsetCalls()) +func (mock *Device) GetMemClkMinMaxVfOffsetCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMemClkMinMaxVfOffset.RLock() + calls = mock.calls.GetMemClkMinMaxVfOffset + mock.lockGetMemClkMinMaxVfOffset.RUnlock() + return calls +} + +// GetMemClkVfOffset calls GetMemClkVfOffsetFunc. +func (mock *Device) GetMemClkVfOffset() (int, nvml.Return) { + if mock.GetMemClkVfOffsetFunc == nil { + panic("Device.GetMemClkVfOffsetFunc: method is nil but Device.GetMemClkVfOffset was just called") + } + callInfo := struct { + }{} + mock.lockGetMemClkVfOffset.Lock() + mock.calls.GetMemClkVfOffset = append(mock.calls.GetMemClkVfOffset, callInfo) + mock.lockGetMemClkVfOffset.Unlock() + return mock.GetMemClkVfOffsetFunc() +} + +// GetMemClkVfOffsetCalls gets all the calls that were made to GetMemClkVfOffset. +// Check the length with: +// +// len(mockedDevice.GetMemClkVfOffsetCalls()) +func (mock *Device) GetMemClkVfOffsetCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMemClkVfOffset.RLock() + calls = mock.calls.GetMemClkVfOffset + mock.lockGetMemClkVfOffset.RUnlock() + return calls +} + +// GetMemoryAffinity calls GetMemoryAffinityFunc. +func (mock *Device) GetMemoryAffinity(n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { + if mock.GetMemoryAffinityFunc == nil { + panic("Device.GetMemoryAffinityFunc: method is nil but Device.GetMemoryAffinity was just called") + } + callInfo := struct { + N int + AffinityScope nvml.AffinityScope + }{ + N: n, + AffinityScope: affinityScope, + } + mock.lockGetMemoryAffinity.Lock() + mock.calls.GetMemoryAffinity = append(mock.calls.GetMemoryAffinity, callInfo) + mock.lockGetMemoryAffinity.Unlock() + return mock.GetMemoryAffinityFunc(n, affinityScope) +} + +// GetMemoryAffinityCalls gets all the calls that were made to GetMemoryAffinity. +// Check the length with: +// +// len(mockedDevice.GetMemoryAffinityCalls()) +func (mock *Device) GetMemoryAffinityCalls() []struct { + N int + AffinityScope nvml.AffinityScope +} { + var calls []struct { + N int + AffinityScope nvml.AffinityScope + } + mock.lockGetMemoryAffinity.RLock() + calls = mock.calls.GetMemoryAffinity + mock.lockGetMemoryAffinity.RUnlock() + return calls +} + +// GetMemoryBusWidth calls GetMemoryBusWidthFunc. +func (mock *Device) GetMemoryBusWidth() (uint32, nvml.Return) { + if mock.GetMemoryBusWidthFunc == nil { + panic("Device.GetMemoryBusWidthFunc: method is nil but Device.GetMemoryBusWidth was just called") + } + callInfo := struct { + }{} + mock.lockGetMemoryBusWidth.Lock() + mock.calls.GetMemoryBusWidth = append(mock.calls.GetMemoryBusWidth, callInfo) + mock.lockGetMemoryBusWidth.Unlock() + return mock.GetMemoryBusWidthFunc() +} + +// GetMemoryBusWidthCalls gets all the calls that were made to GetMemoryBusWidth. +// Check the length with: +// +// len(mockedDevice.GetMemoryBusWidthCalls()) +func (mock *Device) GetMemoryBusWidthCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMemoryBusWidth.RLock() + calls = mock.calls.GetMemoryBusWidth + mock.lockGetMemoryBusWidth.RUnlock() + return calls +} + +// GetMemoryErrorCounter calls GetMemoryErrorCounterFunc. +func (mock *Device) GetMemoryErrorCounter(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) { + if mock.GetMemoryErrorCounterFunc == nil { + panic("Device.GetMemoryErrorCounterFunc: method is nil but Device.GetMemoryErrorCounter was just called") + } + callInfo := struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation + }{ + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + MemoryLocation: memoryLocation, + } + mock.lockGetMemoryErrorCounter.Lock() + mock.calls.GetMemoryErrorCounter = append(mock.calls.GetMemoryErrorCounter, callInfo) + mock.lockGetMemoryErrorCounter.Unlock() + return mock.GetMemoryErrorCounterFunc(memoryErrorType, eccCounterType, memoryLocation) +} + +// GetMemoryErrorCounterCalls gets all the calls that were made to GetMemoryErrorCounter. +// Check the length with: +// +// len(mockedDevice.GetMemoryErrorCounterCalls()) +func (mock *Device) GetMemoryErrorCounterCalls() []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation +} { + var calls []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation + } + mock.lockGetMemoryErrorCounter.RLock() + calls = mock.calls.GetMemoryErrorCounter + mock.lockGetMemoryErrorCounter.RUnlock() + return calls +} + +// GetMemoryInfo calls GetMemoryInfoFunc. +func (mock *Device) GetMemoryInfo() (nvml.Memory, nvml.Return) { + if mock.GetMemoryInfoFunc == nil { + panic("Device.GetMemoryInfoFunc: method is nil but Device.GetMemoryInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetMemoryInfo.Lock() + mock.calls.GetMemoryInfo = append(mock.calls.GetMemoryInfo, callInfo) + mock.lockGetMemoryInfo.Unlock() + return mock.GetMemoryInfoFunc() +} + +// GetMemoryInfoCalls gets all the calls that were made to GetMemoryInfo. +// Check the length with: +// +// len(mockedDevice.GetMemoryInfoCalls()) +func (mock *Device) GetMemoryInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMemoryInfo.RLock() + calls = mock.calls.GetMemoryInfo + mock.lockGetMemoryInfo.RUnlock() + return calls +} + +// GetMemoryInfo_v2 calls GetMemoryInfo_v2Func. +func (mock *Device) GetMemoryInfo_v2() (nvml.Memory_v2, nvml.Return) { + if mock.GetMemoryInfo_v2Func == nil { + panic("Device.GetMemoryInfo_v2Func: method is nil but Device.GetMemoryInfo_v2 was just called") + } + callInfo := struct { + }{} + mock.lockGetMemoryInfo_v2.Lock() + mock.calls.GetMemoryInfo_v2 = append(mock.calls.GetMemoryInfo_v2, callInfo) + mock.lockGetMemoryInfo_v2.Unlock() + return mock.GetMemoryInfo_v2Func() +} + +// GetMemoryInfo_v2Calls gets all the calls that were made to GetMemoryInfo_v2. +// Check the length with: +// +// len(mockedDevice.GetMemoryInfo_v2Calls()) +func (mock *Device) GetMemoryInfo_v2Calls() []struct { +} { + var calls []struct { + } + mock.lockGetMemoryInfo_v2.RLock() + calls = mock.calls.GetMemoryInfo_v2 + mock.lockGetMemoryInfo_v2.RUnlock() + return calls +} + +// GetMigDeviceHandleByIndex calls GetMigDeviceHandleByIndexFunc. +func (mock *Device) GetMigDeviceHandleByIndex(n int) (nvml.Device, nvml.Return) { + if mock.GetMigDeviceHandleByIndexFunc == nil { + panic("Device.GetMigDeviceHandleByIndexFunc: method is nil but Device.GetMigDeviceHandleByIndex was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetMigDeviceHandleByIndex.Lock() + mock.calls.GetMigDeviceHandleByIndex = append(mock.calls.GetMigDeviceHandleByIndex, callInfo) + mock.lockGetMigDeviceHandleByIndex.Unlock() + return mock.GetMigDeviceHandleByIndexFunc(n) +} + +// GetMigDeviceHandleByIndexCalls gets all the calls that were made to GetMigDeviceHandleByIndex. +// Check the length with: +// +// len(mockedDevice.GetMigDeviceHandleByIndexCalls()) +func (mock *Device) GetMigDeviceHandleByIndexCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetMigDeviceHandleByIndex.RLock() + calls = mock.calls.GetMigDeviceHandleByIndex + mock.lockGetMigDeviceHandleByIndex.RUnlock() + return calls +} + +// GetMigMode calls GetMigModeFunc. +func (mock *Device) GetMigMode() (int, int, nvml.Return) { + if mock.GetMigModeFunc == nil { + panic("Device.GetMigModeFunc: method is nil but Device.GetMigMode was just called") + } + callInfo := struct { + }{} + mock.lockGetMigMode.Lock() + mock.calls.GetMigMode = append(mock.calls.GetMigMode, callInfo) + mock.lockGetMigMode.Unlock() + return mock.GetMigModeFunc() +} + +// GetMigModeCalls gets all the calls that were made to GetMigMode. +// Check the length with: +// +// len(mockedDevice.GetMigModeCalls()) +func (mock *Device) GetMigModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMigMode.RLock() + calls = mock.calls.GetMigMode + mock.lockGetMigMode.RUnlock() + return calls +} + +// GetMinMaxClockOfPState calls GetMinMaxClockOfPStateFunc. +func (mock *Device) GetMinMaxClockOfPState(clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) { + if mock.GetMinMaxClockOfPStateFunc == nil { + panic("Device.GetMinMaxClockOfPStateFunc: method is nil but Device.GetMinMaxClockOfPState was just called") + } + callInfo := struct { + ClockType nvml.ClockType + Pstates nvml.Pstates + }{ + ClockType: clockType, + Pstates: pstates, + } + mock.lockGetMinMaxClockOfPState.Lock() + mock.calls.GetMinMaxClockOfPState = append(mock.calls.GetMinMaxClockOfPState, callInfo) + mock.lockGetMinMaxClockOfPState.Unlock() + return mock.GetMinMaxClockOfPStateFunc(clockType, pstates) +} + +// GetMinMaxClockOfPStateCalls gets all the calls that were made to GetMinMaxClockOfPState. +// Check the length with: +// +// len(mockedDevice.GetMinMaxClockOfPStateCalls()) +func (mock *Device) GetMinMaxClockOfPStateCalls() []struct { + ClockType nvml.ClockType + Pstates nvml.Pstates +} { + var calls []struct { + ClockType nvml.ClockType + Pstates nvml.Pstates + } + mock.lockGetMinMaxClockOfPState.RLock() + calls = mock.calls.GetMinMaxClockOfPState + mock.lockGetMinMaxClockOfPState.RUnlock() + return calls +} + +// GetMinMaxFanSpeed calls GetMinMaxFanSpeedFunc. +func (mock *Device) GetMinMaxFanSpeed() (int, int, nvml.Return) { + if mock.GetMinMaxFanSpeedFunc == nil { + panic("Device.GetMinMaxFanSpeedFunc: method is nil but Device.GetMinMaxFanSpeed was just called") + } + callInfo := struct { + }{} + mock.lockGetMinMaxFanSpeed.Lock() + mock.calls.GetMinMaxFanSpeed = append(mock.calls.GetMinMaxFanSpeed, callInfo) + mock.lockGetMinMaxFanSpeed.Unlock() + return mock.GetMinMaxFanSpeedFunc() +} + +// GetMinMaxFanSpeedCalls gets all the calls that were made to GetMinMaxFanSpeed. +// Check the length with: +// +// len(mockedDevice.GetMinMaxFanSpeedCalls()) +func (mock *Device) GetMinMaxFanSpeedCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMinMaxFanSpeed.RLock() + calls = mock.calls.GetMinMaxFanSpeed + mock.lockGetMinMaxFanSpeed.RUnlock() + return calls +} + +// GetMinorNumber calls GetMinorNumberFunc. +func (mock *Device) GetMinorNumber() (int, nvml.Return) { + if mock.GetMinorNumberFunc == nil { + panic("Device.GetMinorNumberFunc: method is nil but Device.GetMinorNumber was just called") + } + callInfo := struct { + }{} + mock.lockGetMinorNumber.Lock() + mock.calls.GetMinorNumber = append(mock.calls.GetMinorNumber, callInfo) + mock.lockGetMinorNumber.Unlock() + return mock.GetMinorNumberFunc() +} + +// GetMinorNumberCalls gets all the calls that were made to GetMinorNumber. +// Check the length with: +// +// len(mockedDevice.GetMinorNumberCalls()) +func (mock *Device) GetMinorNumberCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMinorNumber.RLock() + calls = mock.calls.GetMinorNumber + mock.lockGetMinorNumber.RUnlock() + return calls +} + +// GetModuleId calls GetModuleIdFunc. +func (mock *Device) GetModuleId() (int, nvml.Return) { + if mock.GetModuleIdFunc == nil { + panic("Device.GetModuleIdFunc: method is nil but Device.GetModuleId was just called") + } + callInfo := struct { + }{} + mock.lockGetModuleId.Lock() + mock.calls.GetModuleId = append(mock.calls.GetModuleId, callInfo) + mock.lockGetModuleId.Unlock() + return mock.GetModuleIdFunc() +} + +// GetModuleIdCalls gets all the calls that were made to GetModuleId. +// Check the length with: +// +// len(mockedDevice.GetModuleIdCalls()) +func (mock *Device) GetModuleIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetModuleId.RLock() + calls = mock.calls.GetModuleId + mock.lockGetModuleId.RUnlock() + return calls +} + +// GetMultiGpuBoard calls GetMultiGpuBoardFunc. +func (mock *Device) GetMultiGpuBoard() (int, nvml.Return) { + if mock.GetMultiGpuBoardFunc == nil { + panic("Device.GetMultiGpuBoardFunc: method is nil but Device.GetMultiGpuBoard was just called") + } + callInfo := struct { + }{} + mock.lockGetMultiGpuBoard.Lock() + mock.calls.GetMultiGpuBoard = append(mock.calls.GetMultiGpuBoard, callInfo) + mock.lockGetMultiGpuBoard.Unlock() + return mock.GetMultiGpuBoardFunc() +} + +// GetMultiGpuBoardCalls gets all the calls that were made to GetMultiGpuBoard. +// Check the length with: +// +// len(mockedDevice.GetMultiGpuBoardCalls()) +func (mock *Device) GetMultiGpuBoardCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMultiGpuBoard.RLock() + calls = mock.calls.GetMultiGpuBoard + mock.lockGetMultiGpuBoard.RUnlock() + return calls +} + +// GetName calls GetNameFunc. +func (mock *Device) GetName() (string, nvml.Return) { + if mock.GetNameFunc == nil { + panic("Device.GetNameFunc: method is nil but Device.GetName was just called") + } + callInfo := struct { + }{} + mock.lockGetName.Lock() + mock.calls.GetName = append(mock.calls.GetName, callInfo) + mock.lockGetName.Unlock() + return mock.GetNameFunc() +} + +// GetNameCalls gets all the calls that were made to GetName. +// Check the length with: +// +// len(mockedDevice.GetNameCalls()) +func (mock *Device) GetNameCalls() []struct { +} { + var calls []struct { + } + mock.lockGetName.RLock() + calls = mock.calls.GetName + mock.lockGetName.RUnlock() + return calls +} + +// GetNumFans calls GetNumFansFunc. +func (mock *Device) GetNumFans() (int, nvml.Return) { + if mock.GetNumFansFunc == nil { + panic("Device.GetNumFansFunc: method is nil but Device.GetNumFans was just called") + } + callInfo := struct { + }{} + mock.lockGetNumFans.Lock() + mock.calls.GetNumFans = append(mock.calls.GetNumFans, callInfo) + mock.lockGetNumFans.Unlock() + return mock.GetNumFansFunc() +} + +// GetNumFansCalls gets all the calls that were made to GetNumFans. +// Check the length with: +// +// len(mockedDevice.GetNumFansCalls()) +func (mock *Device) GetNumFansCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNumFans.RLock() + calls = mock.calls.GetNumFans + mock.lockGetNumFans.RUnlock() + return calls +} + +// GetNumGpuCores calls GetNumGpuCoresFunc. +func (mock *Device) GetNumGpuCores() (int, nvml.Return) { + if mock.GetNumGpuCoresFunc == nil { + panic("Device.GetNumGpuCoresFunc: method is nil but Device.GetNumGpuCores was just called") + } + callInfo := struct { + }{} + mock.lockGetNumGpuCores.Lock() + mock.calls.GetNumGpuCores = append(mock.calls.GetNumGpuCores, callInfo) + mock.lockGetNumGpuCores.Unlock() + return mock.GetNumGpuCoresFunc() +} + +// GetNumGpuCoresCalls gets all the calls that were made to GetNumGpuCores. +// Check the length with: +// +// len(mockedDevice.GetNumGpuCoresCalls()) +func (mock *Device) GetNumGpuCoresCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNumGpuCores.RLock() + calls = mock.calls.GetNumGpuCores + mock.lockGetNumGpuCores.RUnlock() + return calls +} + +// GetNumaNodeId calls GetNumaNodeIdFunc. +func (mock *Device) GetNumaNodeId() (int, nvml.Return) { + if mock.GetNumaNodeIdFunc == nil { + panic("Device.GetNumaNodeIdFunc: method is nil but Device.GetNumaNodeId was just called") + } + callInfo := struct { + }{} + mock.lockGetNumaNodeId.Lock() + mock.calls.GetNumaNodeId = append(mock.calls.GetNumaNodeId, callInfo) + mock.lockGetNumaNodeId.Unlock() + return mock.GetNumaNodeIdFunc() +} + +// GetNumaNodeIdCalls gets all the calls that were made to GetNumaNodeId. +// Check the length with: +// +// len(mockedDevice.GetNumaNodeIdCalls()) +func (mock *Device) GetNumaNodeIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNumaNodeId.RLock() + calls = mock.calls.GetNumaNodeId + mock.lockGetNumaNodeId.RUnlock() + return calls +} + +// GetNvLinkCapability calls GetNvLinkCapabilityFunc. +func (mock *Device) GetNvLinkCapability(n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) { + if mock.GetNvLinkCapabilityFunc == nil { + panic("Device.GetNvLinkCapabilityFunc: method is nil but Device.GetNvLinkCapability was just called") + } + callInfo := struct { + N int + NvLinkCapability nvml.NvLinkCapability + }{ + N: n, + NvLinkCapability: nvLinkCapability, + } + mock.lockGetNvLinkCapability.Lock() + mock.calls.GetNvLinkCapability = append(mock.calls.GetNvLinkCapability, callInfo) + mock.lockGetNvLinkCapability.Unlock() + return mock.GetNvLinkCapabilityFunc(n, nvLinkCapability) +} + +// GetNvLinkCapabilityCalls gets all the calls that were made to GetNvLinkCapability. +// Check the length with: +// +// len(mockedDevice.GetNvLinkCapabilityCalls()) +func (mock *Device) GetNvLinkCapabilityCalls() []struct { + N int + NvLinkCapability nvml.NvLinkCapability +} { + var calls []struct { + N int + NvLinkCapability nvml.NvLinkCapability + } + mock.lockGetNvLinkCapability.RLock() + calls = mock.calls.GetNvLinkCapability + mock.lockGetNvLinkCapability.RUnlock() + return calls +} + +// GetNvLinkErrorCounter calls GetNvLinkErrorCounterFunc. +func (mock *Device) GetNvLinkErrorCounter(n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) { + if mock.GetNvLinkErrorCounterFunc == nil { + panic("Device.GetNvLinkErrorCounterFunc: method is nil but Device.GetNvLinkErrorCounter was just called") + } + callInfo := struct { + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter + }{ + N: n, + NvLinkErrorCounter: nvLinkErrorCounter, + } + mock.lockGetNvLinkErrorCounter.Lock() + mock.calls.GetNvLinkErrorCounter = append(mock.calls.GetNvLinkErrorCounter, callInfo) + mock.lockGetNvLinkErrorCounter.Unlock() + return mock.GetNvLinkErrorCounterFunc(n, nvLinkErrorCounter) +} + +// GetNvLinkErrorCounterCalls gets all the calls that were made to GetNvLinkErrorCounter. +// Check the length with: +// +// len(mockedDevice.GetNvLinkErrorCounterCalls()) +func (mock *Device) GetNvLinkErrorCounterCalls() []struct { + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter +} { + var calls []struct { + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter + } + mock.lockGetNvLinkErrorCounter.RLock() + calls = mock.calls.GetNvLinkErrorCounter + mock.lockGetNvLinkErrorCounter.RUnlock() + return calls +} + +// GetNvLinkInfo calls GetNvLinkInfoFunc. +func (mock *Device) GetNvLinkInfo() nvml.NvLinkInfoHandler { + if mock.GetNvLinkInfoFunc == nil { + panic("Device.GetNvLinkInfoFunc: method is nil but Device.GetNvLinkInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetNvLinkInfo.Lock() + mock.calls.GetNvLinkInfo = append(mock.calls.GetNvLinkInfo, callInfo) + mock.lockGetNvLinkInfo.Unlock() + return mock.GetNvLinkInfoFunc() +} + +// GetNvLinkInfoCalls gets all the calls that were made to GetNvLinkInfo. +// Check the length with: +// +// len(mockedDevice.GetNvLinkInfoCalls()) +func (mock *Device) GetNvLinkInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNvLinkInfo.RLock() + calls = mock.calls.GetNvLinkInfo + mock.lockGetNvLinkInfo.RUnlock() + return calls +} + +// GetNvLinkRemoteDeviceType calls GetNvLinkRemoteDeviceTypeFunc. +func (mock *Device) GetNvLinkRemoteDeviceType(n int) (nvml.IntNvLinkDeviceType, nvml.Return) { + if mock.GetNvLinkRemoteDeviceTypeFunc == nil { + panic("Device.GetNvLinkRemoteDeviceTypeFunc: method is nil but Device.GetNvLinkRemoteDeviceType was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetNvLinkRemoteDeviceType.Lock() + mock.calls.GetNvLinkRemoteDeviceType = append(mock.calls.GetNvLinkRemoteDeviceType, callInfo) + mock.lockGetNvLinkRemoteDeviceType.Unlock() + return mock.GetNvLinkRemoteDeviceTypeFunc(n) +} + +// GetNvLinkRemoteDeviceTypeCalls gets all the calls that were made to GetNvLinkRemoteDeviceType. +// Check the length with: +// +// len(mockedDevice.GetNvLinkRemoteDeviceTypeCalls()) +func (mock *Device) GetNvLinkRemoteDeviceTypeCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetNvLinkRemoteDeviceType.RLock() + calls = mock.calls.GetNvLinkRemoteDeviceType + mock.lockGetNvLinkRemoteDeviceType.RUnlock() + return calls +} + +// GetNvLinkRemotePciInfo calls GetNvLinkRemotePciInfoFunc. +func (mock *Device) GetNvLinkRemotePciInfo(n int) (nvml.PciInfo, nvml.Return) { + if mock.GetNvLinkRemotePciInfoFunc == nil { + panic("Device.GetNvLinkRemotePciInfoFunc: method is nil but Device.GetNvLinkRemotePciInfo was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetNvLinkRemotePciInfo.Lock() + mock.calls.GetNvLinkRemotePciInfo = append(mock.calls.GetNvLinkRemotePciInfo, callInfo) + mock.lockGetNvLinkRemotePciInfo.Unlock() + return mock.GetNvLinkRemotePciInfoFunc(n) +} + +// GetNvLinkRemotePciInfoCalls gets all the calls that were made to GetNvLinkRemotePciInfo. +// Check the length with: +// +// len(mockedDevice.GetNvLinkRemotePciInfoCalls()) +func (mock *Device) GetNvLinkRemotePciInfoCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetNvLinkRemotePciInfo.RLock() + calls = mock.calls.GetNvLinkRemotePciInfo + mock.lockGetNvLinkRemotePciInfo.RUnlock() + return calls +} + +// GetNvLinkState calls GetNvLinkStateFunc. +func (mock *Device) GetNvLinkState(n int) (nvml.EnableState, nvml.Return) { + if mock.GetNvLinkStateFunc == nil { + panic("Device.GetNvLinkStateFunc: method is nil but Device.GetNvLinkState was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetNvLinkState.Lock() + mock.calls.GetNvLinkState = append(mock.calls.GetNvLinkState, callInfo) + mock.lockGetNvLinkState.Unlock() + return mock.GetNvLinkStateFunc(n) +} + +// GetNvLinkStateCalls gets all the calls that were made to GetNvLinkState. +// Check the length with: +// +// len(mockedDevice.GetNvLinkStateCalls()) +func (mock *Device) GetNvLinkStateCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetNvLinkState.RLock() + calls = mock.calls.GetNvLinkState + mock.lockGetNvLinkState.RUnlock() + return calls +} + +// GetNvLinkUtilizationControl calls GetNvLinkUtilizationControlFunc. +func (mock *Device) GetNvLinkUtilizationControl(n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) { + if mock.GetNvLinkUtilizationControlFunc == nil { + panic("Device.GetNvLinkUtilizationControlFunc: method is nil but Device.GetNvLinkUtilizationControl was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockGetNvLinkUtilizationControl.Lock() + mock.calls.GetNvLinkUtilizationControl = append(mock.calls.GetNvLinkUtilizationControl, callInfo) + mock.lockGetNvLinkUtilizationControl.Unlock() + return mock.GetNvLinkUtilizationControlFunc(n1, n2) +} + +// GetNvLinkUtilizationControlCalls gets all the calls that were made to GetNvLinkUtilizationControl. +// Check the length with: +// +// len(mockedDevice.GetNvLinkUtilizationControlCalls()) +func (mock *Device) GetNvLinkUtilizationControlCalls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockGetNvLinkUtilizationControl.RLock() + calls = mock.calls.GetNvLinkUtilizationControl + mock.lockGetNvLinkUtilizationControl.RUnlock() + return calls +} + +// GetNvLinkUtilizationCounter calls GetNvLinkUtilizationCounterFunc. +func (mock *Device) GetNvLinkUtilizationCounter(n1 int, n2 int) (uint64, uint64, nvml.Return) { + if mock.GetNvLinkUtilizationCounterFunc == nil { + panic("Device.GetNvLinkUtilizationCounterFunc: method is nil but Device.GetNvLinkUtilizationCounter was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockGetNvLinkUtilizationCounter.Lock() + mock.calls.GetNvLinkUtilizationCounter = append(mock.calls.GetNvLinkUtilizationCounter, callInfo) + mock.lockGetNvLinkUtilizationCounter.Unlock() + return mock.GetNvLinkUtilizationCounterFunc(n1, n2) +} + +// GetNvLinkUtilizationCounterCalls gets all the calls that were made to GetNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedDevice.GetNvLinkUtilizationCounterCalls()) +func (mock *Device) GetNvLinkUtilizationCounterCalls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockGetNvLinkUtilizationCounter.RLock() + calls = mock.calls.GetNvLinkUtilizationCounter + mock.lockGetNvLinkUtilizationCounter.RUnlock() + return calls +} + +// GetNvLinkVersion calls GetNvLinkVersionFunc. +func (mock *Device) GetNvLinkVersion(n int) (uint32, nvml.Return) { + if mock.GetNvLinkVersionFunc == nil { + panic("Device.GetNvLinkVersionFunc: method is nil but Device.GetNvLinkVersion was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetNvLinkVersion.Lock() + mock.calls.GetNvLinkVersion = append(mock.calls.GetNvLinkVersion, callInfo) + mock.lockGetNvLinkVersion.Unlock() + return mock.GetNvLinkVersionFunc(n) +} + +// GetNvLinkVersionCalls gets all the calls that were made to GetNvLinkVersion. +// Check the length with: +// +// len(mockedDevice.GetNvLinkVersionCalls()) +func (mock *Device) GetNvLinkVersionCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetNvLinkVersion.RLock() + calls = mock.calls.GetNvLinkVersion + mock.lockGetNvLinkVersion.RUnlock() + return calls +} + +// GetNvlinkBwMode calls GetNvlinkBwModeFunc. +func (mock *Device) GetNvlinkBwMode() (nvml.NvlinkGetBwMode, nvml.Return) { + if mock.GetNvlinkBwModeFunc == nil { + panic("Device.GetNvlinkBwModeFunc: method is nil but Device.GetNvlinkBwMode was just called") + } + callInfo := struct { + }{} + mock.lockGetNvlinkBwMode.Lock() + mock.calls.GetNvlinkBwMode = append(mock.calls.GetNvlinkBwMode, callInfo) + mock.lockGetNvlinkBwMode.Unlock() + return mock.GetNvlinkBwModeFunc() +} + +// GetNvlinkBwModeCalls gets all the calls that were made to GetNvlinkBwMode. +// Check the length with: +// +// len(mockedDevice.GetNvlinkBwModeCalls()) +func (mock *Device) GetNvlinkBwModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNvlinkBwMode.RLock() + calls = mock.calls.GetNvlinkBwMode + mock.lockGetNvlinkBwMode.RUnlock() + return calls +} + +// GetNvlinkSupportedBwModes calls GetNvlinkSupportedBwModesFunc. +func (mock *Device) GetNvlinkSupportedBwModes() (nvml.NvlinkSupportedBwModes, nvml.Return) { + if mock.GetNvlinkSupportedBwModesFunc == nil { + panic("Device.GetNvlinkSupportedBwModesFunc: method is nil but Device.GetNvlinkSupportedBwModes was just called") + } + callInfo := struct { + }{} + mock.lockGetNvlinkSupportedBwModes.Lock() + mock.calls.GetNvlinkSupportedBwModes = append(mock.calls.GetNvlinkSupportedBwModes, callInfo) + mock.lockGetNvlinkSupportedBwModes.Unlock() + return mock.GetNvlinkSupportedBwModesFunc() +} + +// GetNvlinkSupportedBwModesCalls gets all the calls that were made to GetNvlinkSupportedBwModes. +// Check the length with: +// +// len(mockedDevice.GetNvlinkSupportedBwModesCalls()) +func (mock *Device) GetNvlinkSupportedBwModesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNvlinkSupportedBwModes.RLock() + calls = mock.calls.GetNvlinkSupportedBwModes + mock.lockGetNvlinkSupportedBwModes.RUnlock() + return calls +} + +// GetOfaUtilization calls GetOfaUtilizationFunc. +func (mock *Device) GetOfaUtilization() (uint32, uint32, nvml.Return) { + if mock.GetOfaUtilizationFunc == nil { + panic("Device.GetOfaUtilizationFunc: method is nil but Device.GetOfaUtilization was just called") + } + callInfo := struct { + }{} + mock.lockGetOfaUtilization.Lock() + mock.calls.GetOfaUtilization = append(mock.calls.GetOfaUtilization, callInfo) + mock.lockGetOfaUtilization.Unlock() + return mock.GetOfaUtilizationFunc() +} + +// GetOfaUtilizationCalls gets all the calls that were made to GetOfaUtilization. +// Check the length with: +// +// len(mockedDevice.GetOfaUtilizationCalls()) +func (mock *Device) GetOfaUtilizationCalls() []struct { +} { + var calls []struct { + } + mock.lockGetOfaUtilization.RLock() + calls = mock.calls.GetOfaUtilization + mock.lockGetOfaUtilization.RUnlock() + return calls +} + +// GetP2PStatus calls GetP2PStatusFunc. +func (mock *Device) GetP2PStatus(device nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) { + if mock.GetP2PStatusFunc == nil { + panic("Device.GetP2PStatusFunc: method is nil but Device.GetP2PStatus was just called") + } + callInfo := struct { + Device nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + }{ + Device: device, + GpuP2PCapsIndex: gpuP2PCapsIndex, + } + mock.lockGetP2PStatus.Lock() + mock.calls.GetP2PStatus = append(mock.calls.GetP2PStatus, callInfo) + mock.lockGetP2PStatus.Unlock() + return mock.GetP2PStatusFunc(device, gpuP2PCapsIndex) +} + +// GetP2PStatusCalls gets all the calls that were made to GetP2PStatus. +// Check the length with: +// +// len(mockedDevice.GetP2PStatusCalls()) +func (mock *Device) GetP2PStatusCalls() []struct { + Device nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex +} { + var calls []struct { + Device nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + } + mock.lockGetP2PStatus.RLock() + calls = mock.calls.GetP2PStatus + mock.lockGetP2PStatus.RUnlock() + return calls +} + +// GetPciInfo calls GetPciInfoFunc. +func (mock *Device) GetPciInfo() (nvml.PciInfo, nvml.Return) { + if mock.GetPciInfoFunc == nil { + panic("Device.GetPciInfoFunc: method is nil but Device.GetPciInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetPciInfo.Lock() + mock.calls.GetPciInfo = append(mock.calls.GetPciInfo, callInfo) + mock.lockGetPciInfo.Unlock() + return mock.GetPciInfoFunc() +} + +// GetPciInfoCalls gets all the calls that were made to GetPciInfo. +// Check the length with: +// +// len(mockedDevice.GetPciInfoCalls()) +func (mock *Device) GetPciInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPciInfo.RLock() + calls = mock.calls.GetPciInfo + mock.lockGetPciInfo.RUnlock() + return calls +} + +// GetPciInfoExt calls GetPciInfoExtFunc. +func (mock *Device) GetPciInfoExt() (nvml.PciInfoExt, nvml.Return) { + if mock.GetPciInfoExtFunc == nil { + panic("Device.GetPciInfoExtFunc: method is nil but Device.GetPciInfoExt was just called") + } + callInfo := struct { + }{} + mock.lockGetPciInfoExt.Lock() + mock.calls.GetPciInfoExt = append(mock.calls.GetPciInfoExt, callInfo) + mock.lockGetPciInfoExt.Unlock() + return mock.GetPciInfoExtFunc() +} + +// GetPciInfoExtCalls gets all the calls that were made to GetPciInfoExt. +// Check the length with: +// +// len(mockedDevice.GetPciInfoExtCalls()) +func (mock *Device) GetPciInfoExtCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPciInfoExt.RLock() + calls = mock.calls.GetPciInfoExt + mock.lockGetPciInfoExt.RUnlock() + return calls +} + +// GetPcieLinkMaxSpeed calls GetPcieLinkMaxSpeedFunc. +func (mock *Device) GetPcieLinkMaxSpeed() (uint32, nvml.Return) { + if mock.GetPcieLinkMaxSpeedFunc == nil { + panic("Device.GetPcieLinkMaxSpeedFunc: method is nil but Device.GetPcieLinkMaxSpeed was just called") + } + callInfo := struct { + }{} + mock.lockGetPcieLinkMaxSpeed.Lock() + mock.calls.GetPcieLinkMaxSpeed = append(mock.calls.GetPcieLinkMaxSpeed, callInfo) + mock.lockGetPcieLinkMaxSpeed.Unlock() + return mock.GetPcieLinkMaxSpeedFunc() +} + +// GetPcieLinkMaxSpeedCalls gets all the calls that were made to GetPcieLinkMaxSpeed. +// Check the length with: +// +// len(mockedDevice.GetPcieLinkMaxSpeedCalls()) +func (mock *Device) GetPcieLinkMaxSpeedCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPcieLinkMaxSpeed.RLock() + calls = mock.calls.GetPcieLinkMaxSpeed + mock.lockGetPcieLinkMaxSpeed.RUnlock() + return calls +} + +// GetPcieReplayCounter calls GetPcieReplayCounterFunc. +func (mock *Device) GetPcieReplayCounter() (int, nvml.Return) { + if mock.GetPcieReplayCounterFunc == nil { + panic("Device.GetPcieReplayCounterFunc: method is nil but Device.GetPcieReplayCounter was just called") + } + callInfo := struct { + }{} + mock.lockGetPcieReplayCounter.Lock() + mock.calls.GetPcieReplayCounter = append(mock.calls.GetPcieReplayCounter, callInfo) + mock.lockGetPcieReplayCounter.Unlock() + return mock.GetPcieReplayCounterFunc() +} + +// GetPcieReplayCounterCalls gets all the calls that were made to GetPcieReplayCounter. +// Check the length with: +// +// len(mockedDevice.GetPcieReplayCounterCalls()) +func (mock *Device) GetPcieReplayCounterCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPcieReplayCounter.RLock() + calls = mock.calls.GetPcieReplayCounter + mock.lockGetPcieReplayCounter.RUnlock() + return calls +} + +// GetPcieSpeed calls GetPcieSpeedFunc. +func (mock *Device) GetPcieSpeed() (int, nvml.Return) { + if mock.GetPcieSpeedFunc == nil { + panic("Device.GetPcieSpeedFunc: method is nil but Device.GetPcieSpeed was just called") + } + callInfo := struct { + }{} + mock.lockGetPcieSpeed.Lock() + mock.calls.GetPcieSpeed = append(mock.calls.GetPcieSpeed, callInfo) + mock.lockGetPcieSpeed.Unlock() + return mock.GetPcieSpeedFunc() +} + +// GetPcieSpeedCalls gets all the calls that were made to GetPcieSpeed. +// Check the length with: +// +// len(mockedDevice.GetPcieSpeedCalls()) +func (mock *Device) GetPcieSpeedCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPcieSpeed.RLock() + calls = mock.calls.GetPcieSpeed + mock.lockGetPcieSpeed.RUnlock() + return calls +} + +// GetPcieThroughput calls GetPcieThroughputFunc. +func (mock *Device) GetPcieThroughput(pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) { + if mock.GetPcieThroughputFunc == nil { + panic("Device.GetPcieThroughputFunc: method is nil but Device.GetPcieThroughput was just called") + } + callInfo := struct { + PcieUtilCounter nvml.PcieUtilCounter + }{ + PcieUtilCounter: pcieUtilCounter, + } + mock.lockGetPcieThroughput.Lock() + mock.calls.GetPcieThroughput = append(mock.calls.GetPcieThroughput, callInfo) + mock.lockGetPcieThroughput.Unlock() + return mock.GetPcieThroughputFunc(pcieUtilCounter) +} + +// GetPcieThroughputCalls gets all the calls that were made to GetPcieThroughput. +// Check the length with: +// +// len(mockedDevice.GetPcieThroughputCalls()) +func (mock *Device) GetPcieThroughputCalls() []struct { + PcieUtilCounter nvml.PcieUtilCounter +} { + var calls []struct { + PcieUtilCounter nvml.PcieUtilCounter + } + mock.lockGetPcieThroughput.RLock() + calls = mock.calls.GetPcieThroughput + mock.lockGetPcieThroughput.RUnlock() + return calls +} + +// GetPdi calls GetPdiFunc. +func (mock *Device) GetPdi() (nvml.Pdi, nvml.Return) { + if mock.GetPdiFunc == nil { + panic("Device.GetPdiFunc: method is nil but Device.GetPdi was just called") + } + callInfo := struct { + }{} + mock.lockGetPdi.Lock() + mock.calls.GetPdi = append(mock.calls.GetPdi, callInfo) + mock.lockGetPdi.Unlock() + return mock.GetPdiFunc() +} + +// GetPdiCalls gets all the calls that were made to GetPdi. +// Check the length with: +// +// len(mockedDevice.GetPdiCalls()) +func (mock *Device) GetPdiCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPdi.RLock() + calls = mock.calls.GetPdi + mock.lockGetPdi.RUnlock() + return calls +} + +// GetPerformanceModes calls GetPerformanceModesFunc. +func (mock *Device) GetPerformanceModes() (nvml.DevicePerfModes, nvml.Return) { + if mock.GetPerformanceModesFunc == nil { + panic("Device.GetPerformanceModesFunc: method is nil but Device.GetPerformanceModes was just called") + } + callInfo := struct { + }{} + mock.lockGetPerformanceModes.Lock() + mock.calls.GetPerformanceModes = append(mock.calls.GetPerformanceModes, callInfo) + mock.lockGetPerformanceModes.Unlock() + return mock.GetPerformanceModesFunc() +} + +// GetPerformanceModesCalls gets all the calls that were made to GetPerformanceModes. +// Check the length with: +// +// len(mockedDevice.GetPerformanceModesCalls()) +func (mock *Device) GetPerformanceModesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPerformanceModes.RLock() + calls = mock.calls.GetPerformanceModes + mock.lockGetPerformanceModes.RUnlock() + return calls +} + +// GetPerformanceState calls GetPerformanceStateFunc. +func (mock *Device) GetPerformanceState() (nvml.Pstates, nvml.Return) { + if mock.GetPerformanceStateFunc == nil { + panic("Device.GetPerformanceStateFunc: method is nil but Device.GetPerformanceState was just called") + } + callInfo := struct { + }{} + mock.lockGetPerformanceState.Lock() + mock.calls.GetPerformanceState = append(mock.calls.GetPerformanceState, callInfo) + mock.lockGetPerformanceState.Unlock() + return mock.GetPerformanceStateFunc() +} + +// GetPerformanceStateCalls gets all the calls that were made to GetPerformanceState. +// Check the length with: +// +// len(mockedDevice.GetPerformanceStateCalls()) +func (mock *Device) GetPerformanceStateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPerformanceState.RLock() + calls = mock.calls.GetPerformanceState + mock.lockGetPerformanceState.RUnlock() + return calls +} + +// GetPersistenceMode calls GetPersistenceModeFunc. +func (mock *Device) GetPersistenceMode() (nvml.EnableState, nvml.Return) { + if mock.GetPersistenceModeFunc == nil { + panic("Device.GetPersistenceModeFunc: method is nil but Device.GetPersistenceMode was just called") + } + callInfo := struct { + }{} + mock.lockGetPersistenceMode.Lock() + mock.calls.GetPersistenceMode = append(mock.calls.GetPersistenceMode, callInfo) + mock.lockGetPersistenceMode.Unlock() + return mock.GetPersistenceModeFunc() +} + +// GetPersistenceModeCalls gets all the calls that were made to GetPersistenceMode. +// Check the length with: +// +// len(mockedDevice.GetPersistenceModeCalls()) +func (mock *Device) GetPersistenceModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPersistenceMode.RLock() + calls = mock.calls.GetPersistenceMode + mock.lockGetPersistenceMode.RUnlock() + return calls +} + +// GetPgpuMetadataString calls GetPgpuMetadataStringFunc. +func (mock *Device) GetPgpuMetadataString() (string, nvml.Return) { + if mock.GetPgpuMetadataStringFunc == nil { + panic("Device.GetPgpuMetadataStringFunc: method is nil but Device.GetPgpuMetadataString was just called") + } + callInfo := struct { + }{} + mock.lockGetPgpuMetadataString.Lock() + mock.calls.GetPgpuMetadataString = append(mock.calls.GetPgpuMetadataString, callInfo) + mock.lockGetPgpuMetadataString.Unlock() + return mock.GetPgpuMetadataStringFunc() +} + +// GetPgpuMetadataStringCalls gets all the calls that were made to GetPgpuMetadataString. +// Check the length with: +// +// len(mockedDevice.GetPgpuMetadataStringCalls()) +func (mock *Device) GetPgpuMetadataStringCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPgpuMetadataString.RLock() + calls = mock.calls.GetPgpuMetadataString + mock.lockGetPgpuMetadataString.RUnlock() + return calls +} + +// GetPlatformInfo calls GetPlatformInfoFunc. +func (mock *Device) GetPlatformInfo() (nvml.PlatformInfo, nvml.Return) { + if mock.GetPlatformInfoFunc == nil { + panic("Device.GetPlatformInfoFunc: method is nil but Device.GetPlatformInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetPlatformInfo.Lock() + mock.calls.GetPlatformInfo = append(mock.calls.GetPlatformInfo, callInfo) + mock.lockGetPlatformInfo.Unlock() + return mock.GetPlatformInfoFunc() +} + +// GetPlatformInfoCalls gets all the calls that were made to GetPlatformInfo. +// Check the length with: +// +// len(mockedDevice.GetPlatformInfoCalls()) +func (mock *Device) GetPlatformInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPlatformInfo.RLock() + calls = mock.calls.GetPlatformInfo + mock.lockGetPlatformInfo.RUnlock() + return calls +} + +// GetPowerManagementDefaultLimit calls GetPowerManagementDefaultLimitFunc. +func (mock *Device) GetPowerManagementDefaultLimit() (uint32, nvml.Return) { + if mock.GetPowerManagementDefaultLimitFunc == nil { + panic("Device.GetPowerManagementDefaultLimitFunc: method is nil but Device.GetPowerManagementDefaultLimit was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerManagementDefaultLimit.Lock() + mock.calls.GetPowerManagementDefaultLimit = append(mock.calls.GetPowerManagementDefaultLimit, callInfo) + mock.lockGetPowerManagementDefaultLimit.Unlock() + return mock.GetPowerManagementDefaultLimitFunc() +} + +// GetPowerManagementDefaultLimitCalls gets all the calls that were made to GetPowerManagementDefaultLimit. +// Check the length with: +// +// len(mockedDevice.GetPowerManagementDefaultLimitCalls()) +func (mock *Device) GetPowerManagementDefaultLimitCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerManagementDefaultLimit.RLock() + calls = mock.calls.GetPowerManagementDefaultLimit + mock.lockGetPowerManagementDefaultLimit.RUnlock() + return calls +} + +// GetPowerManagementLimit calls GetPowerManagementLimitFunc. +func (mock *Device) GetPowerManagementLimit() (uint32, nvml.Return) { + if mock.GetPowerManagementLimitFunc == nil { + panic("Device.GetPowerManagementLimitFunc: method is nil but Device.GetPowerManagementLimit was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerManagementLimit.Lock() + mock.calls.GetPowerManagementLimit = append(mock.calls.GetPowerManagementLimit, callInfo) + mock.lockGetPowerManagementLimit.Unlock() + return mock.GetPowerManagementLimitFunc() +} + +// GetPowerManagementLimitCalls gets all the calls that were made to GetPowerManagementLimit. +// Check the length with: +// +// len(mockedDevice.GetPowerManagementLimitCalls()) +func (mock *Device) GetPowerManagementLimitCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerManagementLimit.RLock() + calls = mock.calls.GetPowerManagementLimit + mock.lockGetPowerManagementLimit.RUnlock() + return calls +} + +// GetPowerManagementLimitConstraints calls GetPowerManagementLimitConstraintsFunc. +func (mock *Device) GetPowerManagementLimitConstraints() (uint32, uint32, nvml.Return) { + if mock.GetPowerManagementLimitConstraintsFunc == nil { + panic("Device.GetPowerManagementLimitConstraintsFunc: method is nil but Device.GetPowerManagementLimitConstraints was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerManagementLimitConstraints.Lock() + mock.calls.GetPowerManagementLimitConstraints = append(mock.calls.GetPowerManagementLimitConstraints, callInfo) + mock.lockGetPowerManagementLimitConstraints.Unlock() + return mock.GetPowerManagementLimitConstraintsFunc() +} + +// GetPowerManagementLimitConstraintsCalls gets all the calls that were made to GetPowerManagementLimitConstraints. +// Check the length with: +// +// len(mockedDevice.GetPowerManagementLimitConstraintsCalls()) +func (mock *Device) GetPowerManagementLimitConstraintsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerManagementLimitConstraints.RLock() + calls = mock.calls.GetPowerManagementLimitConstraints + mock.lockGetPowerManagementLimitConstraints.RUnlock() + return calls +} + +// GetPowerManagementMode calls GetPowerManagementModeFunc. +func (mock *Device) GetPowerManagementMode() (nvml.EnableState, nvml.Return) { + if mock.GetPowerManagementModeFunc == nil { + panic("Device.GetPowerManagementModeFunc: method is nil but Device.GetPowerManagementMode was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerManagementMode.Lock() + mock.calls.GetPowerManagementMode = append(mock.calls.GetPowerManagementMode, callInfo) + mock.lockGetPowerManagementMode.Unlock() + return mock.GetPowerManagementModeFunc() +} + +// GetPowerManagementModeCalls gets all the calls that were made to GetPowerManagementMode. +// Check the length with: +// +// len(mockedDevice.GetPowerManagementModeCalls()) +func (mock *Device) GetPowerManagementModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerManagementMode.RLock() + calls = mock.calls.GetPowerManagementMode + mock.lockGetPowerManagementMode.RUnlock() + return calls +} + +// GetPowerMizerMode_v1 calls GetPowerMizerMode_v1Func. +func (mock *Device) GetPowerMizerMode_v1() (nvml.DevicePowerMizerModes_v1, nvml.Return) { + if mock.GetPowerMizerMode_v1Func == nil { + panic("Device.GetPowerMizerMode_v1Func: method is nil but Device.GetPowerMizerMode_v1 was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerMizerMode_v1.Lock() + mock.calls.GetPowerMizerMode_v1 = append(mock.calls.GetPowerMizerMode_v1, callInfo) + mock.lockGetPowerMizerMode_v1.Unlock() + return mock.GetPowerMizerMode_v1Func() +} + +// GetPowerMizerMode_v1Calls gets all the calls that were made to GetPowerMizerMode_v1. +// Check the length with: +// +// len(mockedDevice.GetPowerMizerMode_v1Calls()) +func (mock *Device) GetPowerMizerMode_v1Calls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerMizerMode_v1.RLock() + calls = mock.calls.GetPowerMizerMode_v1 + mock.lockGetPowerMizerMode_v1.RUnlock() + return calls +} + +// GetPowerSource calls GetPowerSourceFunc. +func (mock *Device) GetPowerSource() (nvml.PowerSource, nvml.Return) { + if mock.GetPowerSourceFunc == nil { + panic("Device.GetPowerSourceFunc: method is nil but Device.GetPowerSource was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerSource.Lock() + mock.calls.GetPowerSource = append(mock.calls.GetPowerSource, callInfo) + mock.lockGetPowerSource.Unlock() + return mock.GetPowerSourceFunc() +} + +// GetPowerSourceCalls gets all the calls that were made to GetPowerSource. +// Check the length with: +// +// len(mockedDevice.GetPowerSourceCalls()) +func (mock *Device) GetPowerSourceCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerSource.RLock() + calls = mock.calls.GetPowerSource + mock.lockGetPowerSource.RUnlock() + return calls +} + +// GetPowerState calls GetPowerStateFunc. +func (mock *Device) GetPowerState() (nvml.Pstates, nvml.Return) { + if mock.GetPowerStateFunc == nil { + panic("Device.GetPowerStateFunc: method is nil but Device.GetPowerState was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerState.Lock() + mock.calls.GetPowerState = append(mock.calls.GetPowerState, callInfo) + mock.lockGetPowerState.Unlock() + return mock.GetPowerStateFunc() +} + +// GetPowerStateCalls gets all the calls that were made to GetPowerState. +// Check the length with: +// +// len(mockedDevice.GetPowerStateCalls()) +func (mock *Device) GetPowerStateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerState.RLock() + calls = mock.calls.GetPowerState + mock.lockGetPowerState.RUnlock() + return calls +} + +// GetPowerUsage calls GetPowerUsageFunc. +func (mock *Device) GetPowerUsage() (uint32, nvml.Return) { + if mock.GetPowerUsageFunc == nil { + panic("Device.GetPowerUsageFunc: method is nil but Device.GetPowerUsage was just called") + } + callInfo := struct { + }{} + mock.lockGetPowerUsage.Lock() + mock.calls.GetPowerUsage = append(mock.calls.GetPowerUsage, callInfo) + mock.lockGetPowerUsage.Unlock() + return mock.GetPowerUsageFunc() +} + +// GetPowerUsageCalls gets all the calls that were made to GetPowerUsage. +// Check the length with: +// +// len(mockedDevice.GetPowerUsageCalls()) +func (mock *Device) GetPowerUsageCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPowerUsage.RLock() + calls = mock.calls.GetPowerUsage + mock.lockGetPowerUsage.RUnlock() + return calls +} + +// GetProcessUtilization calls GetProcessUtilizationFunc. +func (mock *Device) GetProcessUtilization(v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) { + if mock.GetProcessUtilizationFunc == nil { + panic("Device.GetProcessUtilizationFunc: method is nil but Device.GetProcessUtilization was just called") + } + callInfo := struct { + V uint64 + }{ + V: v, + } + mock.lockGetProcessUtilization.Lock() + mock.calls.GetProcessUtilization = append(mock.calls.GetProcessUtilization, callInfo) + mock.lockGetProcessUtilization.Unlock() + return mock.GetProcessUtilizationFunc(v) +} + +// GetProcessUtilizationCalls gets all the calls that were made to GetProcessUtilization. +// Check the length with: +// +// len(mockedDevice.GetProcessUtilizationCalls()) +func (mock *Device) GetProcessUtilizationCalls() []struct { + V uint64 +} { + var calls []struct { + V uint64 + } + mock.lockGetProcessUtilization.RLock() + calls = mock.calls.GetProcessUtilization + mock.lockGetProcessUtilization.RUnlock() + return calls +} + +// GetProcessesUtilizationInfo calls GetProcessesUtilizationInfoFunc. +func (mock *Device) GetProcessesUtilizationInfo() (nvml.ProcessesUtilizationInfo, nvml.Return) { + if mock.GetProcessesUtilizationInfoFunc == nil { + panic("Device.GetProcessesUtilizationInfoFunc: method is nil but Device.GetProcessesUtilizationInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetProcessesUtilizationInfo.Lock() + mock.calls.GetProcessesUtilizationInfo = append(mock.calls.GetProcessesUtilizationInfo, callInfo) + mock.lockGetProcessesUtilizationInfo.Unlock() + return mock.GetProcessesUtilizationInfoFunc() +} + +// GetProcessesUtilizationInfoCalls gets all the calls that were made to GetProcessesUtilizationInfo. +// Check the length with: +// +// len(mockedDevice.GetProcessesUtilizationInfoCalls()) +func (mock *Device) GetProcessesUtilizationInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetProcessesUtilizationInfo.RLock() + calls = mock.calls.GetProcessesUtilizationInfo + mock.lockGetProcessesUtilizationInfo.RUnlock() + return calls +} + +// GetRemappedRows calls GetRemappedRowsFunc. +func (mock *Device) GetRemappedRows() (int, int, bool, bool, nvml.Return) { + if mock.GetRemappedRowsFunc == nil { + panic("Device.GetRemappedRowsFunc: method is nil but Device.GetRemappedRows was just called") + } + callInfo := struct { + }{} + mock.lockGetRemappedRows.Lock() + mock.calls.GetRemappedRows = append(mock.calls.GetRemappedRows, callInfo) + mock.lockGetRemappedRows.Unlock() + return mock.GetRemappedRowsFunc() +} + +// GetRemappedRowsCalls gets all the calls that were made to GetRemappedRows. +// Check the length with: +// +// len(mockedDevice.GetRemappedRowsCalls()) +func (mock *Device) GetRemappedRowsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRemappedRows.RLock() + calls = mock.calls.GetRemappedRows + mock.lockGetRemappedRows.RUnlock() + return calls +} + +// GetRepairStatus calls GetRepairStatusFunc. +func (mock *Device) GetRepairStatus() (nvml.RepairStatus, nvml.Return) { + if mock.GetRepairStatusFunc == nil { + panic("Device.GetRepairStatusFunc: method is nil but Device.GetRepairStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetRepairStatus.Lock() + mock.calls.GetRepairStatus = append(mock.calls.GetRepairStatus, callInfo) + mock.lockGetRepairStatus.Unlock() + return mock.GetRepairStatusFunc() +} + +// GetRepairStatusCalls gets all the calls that were made to GetRepairStatus. +// Check the length with: +// +// len(mockedDevice.GetRepairStatusCalls()) +func (mock *Device) GetRepairStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRepairStatus.RLock() + calls = mock.calls.GetRepairStatus + mock.lockGetRepairStatus.RUnlock() + return calls +} + +// GetRetiredPages calls GetRetiredPagesFunc. +func (mock *Device) GetRetiredPages(pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) { + if mock.GetRetiredPagesFunc == nil { + panic("Device.GetRetiredPagesFunc: method is nil but Device.GetRetiredPages was just called") + } + callInfo := struct { + PageRetirementCause nvml.PageRetirementCause + }{ + PageRetirementCause: pageRetirementCause, + } + mock.lockGetRetiredPages.Lock() + mock.calls.GetRetiredPages = append(mock.calls.GetRetiredPages, callInfo) + mock.lockGetRetiredPages.Unlock() + return mock.GetRetiredPagesFunc(pageRetirementCause) +} + +// GetRetiredPagesCalls gets all the calls that were made to GetRetiredPages. +// Check the length with: +// +// len(mockedDevice.GetRetiredPagesCalls()) +func (mock *Device) GetRetiredPagesCalls() []struct { + PageRetirementCause nvml.PageRetirementCause +} { + var calls []struct { + PageRetirementCause nvml.PageRetirementCause + } + mock.lockGetRetiredPages.RLock() + calls = mock.calls.GetRetiredPages + mock.lockGetRetiredPages.RUnlock() + return calls +} + +// GetRetiredPagesPendingStatus calls GetRetiredPagesPendingStatusFunc. +func (mock *Device) GetRetiredPagesPendingStatus() (nvml.EnableState, nvml.Return) { + if mock.GetRetiredPagesPendingStatusFunc == nil { + panic("Device.GetRetiredPagesPendingStatusFunc: method is nil but Device.GetRetiredPagesPendingStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetRetiredPagesPendingStatus.Lock() + mock.calls.GetRetiredPagesPendingStatus = append(mock.calls.GetRetiredPagesPendingStatus, callInfo) + mock.lockGetRetiredPagesPendingStatus.Unlock() + return mock.GetRetiredPagesPendingStatusFunc() +} + +// GetRetiredPagesPendingStatusCalls gets all the calls that were made to GetRetiredPagesPendingStatus. +// Check the length with: +// +// len(mockedDevice.GetRetiredPagesPendingStatusCalls()) +func (mock *Device) GetRetiredPagesPendingStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRetiredPagesPendingStatus.RLock() + calls = mock.calls.GetRetiredPagesPendingStatus + mock.lockGetRetiredPagesPendingStatus.RUnlock() + return calls +} + +// GetRetiredPages_v2 calls GetRetiredPages_v2Func. +func (mock *Device) GetRetiredPages_v2(pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) { + if mock.GetRetiredPages_v2Func == nil { + panic("Device.GetRetiredPages_v2Func: method is nil but Device.GetRetiredPages_v2 was just called") + } + callInfo := struct { + PageRetirementCause nvml.PageRetirementCause + }{ + PageRetirementCause: pageRetirementCause, + } + mock.lockGetRetiredPages_v2.Lock() + mock.calls.GetRetiredPages_v2 = append(mock.calls.GetRetiredPages_v2, callInfo) + mock.lockGetRetiredPages_v2.Unlock() + return mock.GetRetiredPages_v2Func(pageRetirementCause) +} + +// GetRetiredPages_v2Calls gets all the calls that were made to GetRetiredPages_v2. +// Check the length with: +// +// len(mockedDevice.GetRetiredPages_v2Calls()) +func (mock *Device) GetRetiredPages_v2Calls() []struct { + PageRetirementCause nvml.PageRetirementCause +} { + var calls []struct { + PageRetirementCause nvml.PageRetirementCause + } + mock.lockGetRetiredPages_v2.RLock() + calls = mock.calls.GetRetiredPages_v2 + mock.lockGetRetiredPages_v2.RUnlock() + return calls +} + +// GetRowRemapperHistogram calls GetRowRemapperHistogramFunc. +func (mock *Device) GetRowRemapperHistogram() (nvml.RowRemapperHistogramValues, nvml.Return) { + if mock.GetRowRemapperHistogramFunc == nil { + panic("Device.GetRowRemapperHistogramFunc: method is nil but Device.GetRowRemapperHistogram was just called") + } + callInfo := struct { + }{} + mock.lockGetRowRemapperHistogram.Lock() + mock.calls.GetRowRemapperHistogram = append(mock.calls.GetRowRemapperHistogram, callInfo) + mock.lockGetRowRemapperHistogram.Unlock() + return mock.GetRowRemapperHistogramFunc() +} + +// GetRowRemapperHistogramCalls gets all the calls that were made to GetRowRemapperHistogram. +// Check the length with: +// +// len(mockedDevice.GetRowRemapperHistogramCalls()) +func (mock *Device) GetRowRemapperHistogramCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRowRemapperHistogram.RLock() + calls = mock.calls.GetRowRemapperHistogram + mock.lockGetRowRemapperHistogram.RUnlock() + return calls +} + +// GetRunningProcessDetailList calls GetRunningProcessDetailListFunc. +func (mock *Device) GetRunningProcessDetailList() (nvml.ProcessDetailList, nvml.Return) { + if mock.GetRunningProcessDetailListFunc == nil { + panic("Device.GetRunningProcessDetailListFunc: method is nil but Device.GetRunningProcessDetailList was just called") + } + callInfo := struct { + }{} + mock.lockGetRunningProcessDetailList.Lock() + mock.calls.GetRunningProcessDetailList = append(mock.calls.GetRunningProcessDetailList, callInfo) + mock.lockGetRunningProcessDetailList.Unlock() + return mock.GetRunningProcessDetailListFunc() +} + +// GetRunningProcessDetailListCalls gets all the calls that were made to GetRunningProcessDetailList. +// Check the length with: +// +// len(mockedDevice.GetRunningProcessDetailListCalls()) +func (mock *Device) GetRunningProcessDetailListCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRunningProcessDetailList.RLock() + calls = mock.calls.GetRunningProcessDetailList + mock.lockGetRunningProcessDetailList.RUnlock() + return calls +} + +// GetSamples calls GetSamplesFunc. +func (mock *Device) GetSamples(samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) { + if mock.GetSamplesFunc == nil { + panic("Device.GetSamplesFunc: method is nil but Device.GetSamples was just called") + } + callInfo := struct { + SamplingType nvml.SamplingType + V uint64 + }{ + SamplingType: samplingType, + V: v, + } + mock.lockGetSamples.Lock() + mock.calls.GetSamples = append(mock.calls.GetSamples, callInfo) + mock.lockGetSamples.Unlock() + return mock.GetSamplesFunc(samplingType, v) +} + +// GetSamplesCalls gets all the calls that were made to GetSamples. +// Check the length with: +// +// len(mockedDevice.GetSamplesCalls()) +func (mock *Device) GetSamplesCalls() []struct { + SamplingType nvml.SamplingType + V uint64 +} { + var calls []struct { + SamplingType nvml.SamplingType + V uint64 + } + mock.lockGetSamples.RLock() + calls = mock.calls.GetSamples + mock.lockGetSamples.RUnlock() + return calls +} + +// GetSerial calls GetSerialFunc. +func (mock *Device) GetSerial() (string, nvml.Return) { + if mock.GetSerialFunc == nil { + panic("Device.GetSerialFunc: method is nil but Device.GetSerial was just called") + } + callInfo := struct { + }{} + mock.lockGetSerial.Lock() + mock.calls.GetSerial = append(mock.calls.GetSerial, callInfo) + mock.lockGetSerial.Unlock() + return mock.GetSerialFunc() +} + +// GetSerialCalls gets all the calls that were made to GetSerial. +// Check the length with: +// +// len(mockedDevice.GetSerialCalls()) +func (mock *Device) GetSerialCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSerial.RLock() + calls = mock.calls.GetSerial + mock.lockGetSerial.RUnlock() + return calls +} + +// GetSramEccErrorStatus calls GetSramEccErrorStatusFunc. +func (mock *Device) GetSramEccErrorStatus() (nvml.EccSramErrorStatus, nvml.Return) { + if mock.GetSramEccErrorStatusFunc == nil { + panic("Device.GetSramEccErrorStatusFunc: method is nil but Device.GetSramEccErrorStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetSramEccErrorStatus.Lock() + mock.calls.GetSramEccErrorStatus = append(mock.calls.GetSramEccErrorStatus, callInfo) + mock.lockGetSramEccErrorStatus.Unlock() + return mock.GetSramEccErrorStatusFunc() +} + +// GetSramEccErrorStatusCalls gets all the calls that were made to GetSramEccErrorStatus. +// Check the length with: +// +// len(mockedDevice.GetSramEccErrorStatusCalls()) +func (mock *Device) GetSramEccErrorStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSramEccErrorStatus.RLock() + calls = mock.calls.GetSramEccErrorStatus + mock.lockGetSramEccErrorStatus.RUnlock() + return calls +} + +// GetSramUniqueUncorrectedEccErrorCounts calls GetSramUniqueUncorrectedEccErrorCountsFunc. +func (mock *Device) GetSramUniqueUncorrectedEccErrorCounts(eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return { + if mock.GetSramUniqueUncorrectedEccErrorCountsFunc == nil { + panic("Device.GetSramUniqueUncorrectedEccErrorCountsFunc: method is nil but Device.GetSramUniqueUncorrectedEccErrorCounts was just called") + } + callInfo := struct { + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + }{ + EccSramUniqueUncorrectedErrorCounts: eccSramUniqueUncorrectedErrorCounts, + } + mock.lockGetSramUniqueUncorrectedEccErrorCounts.Lock() + mock.calls.GetSramUniqueUncorrectedEccErrorCounts = append(mock.calls.GetSramUniqueUncorrectedEccErrorCounts, callInfo) + mock.lockGetSramUniqueUncorrectedEccErrorCounts.Unlock() + return mock.GetSramUniqueUncorrectedEccErrorCountsFunc(eccSramUniqueUncorrectedErrorCounts) +} + +// GetSramUniqueUncorrectedEccErrorCountsCalls gets all the calls that were made to GetSramUniqueUncorrectedEccErrorCounts. +// Check the length with: +// +// len(mockedDevice.GetSramUniqueUncorrectedEccErrorCountsCalls()) +func (mock *Device) GetSramUniqueUncorrectedEccErrorCountsCalls() []struct { + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts +} { + var calls []struct { + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + } + mock.lockGetSramUniqueUncorrectedEccErrorCounts.RLock() + calls = mock.calls.GetSramUniqueUncorrectedEccErrorCounts + mock.lockGetSramUniqueUncorrectedEccErrorCounts.RUnlock() + return calls +} + +// GetSupportedClocksEventReasons calls GetSupportedClocksEventReasonsFunc. +func (mock *Device) GetSupportedClocksEventReasons() (uint64, nvml.Return) { + if mock.GetSupportedClocksEventReasonsFunc == nil { + panic("Device.GetSupportedClocksEventReasonsFunc: method is nil but Device.GetSupportedClocksEventReasons was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedClocksEventReasons.Lock() + mock.calls.GetSupportedClocksEventReasons = append(mock.calls.GetSupportedClocksEventReasons, callInfo) + mock.lockGetSupportedClocksEventReasons.Unlock() + return mock.GetSupportedClocksEventReasonsFunc() +} + +// GetSupportedClocksEventReasonsCalls gets all the calls that were made to GetSupportedClocksEventReasons. +// Check the length with: +// +// len(mockedDevice.GetSupportedClocksEventReasonsCalls()) +func (mock *Device) GetSupportedClocksEventReasonsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedClocksEventReasons.RLock() + calls = mock.calls.GetSupportedClocksEventReasons + mock.lockGetSupportedClocksEventReasons.RUnlock() + return calls +} + +// GetSupportedClocksThrottleReasons calls GetSupportedClocksThrottleReasonsFunc. +func (mock *Device) GetSupportedClocksThrottleReasons() (uint64, nvml.Return) { + if mock.GetSupportedClocksThrottleReasonsFunc == nil { + panic("Device.GetSupportedClocksThrottleReasonsFunc: method is nil but Device.GetSupportedClocksThrottleReasons was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedClocksThrottleReasons.Lock() + mock.calls.GetSupportedClocksThrottleReasons = append(mock.calls.GetSupportedClocksThrottleReasons, callInfo) + mock.lockGetSupportedClocksThrottleReasons.Unlock() + return mock.GetSupportedClocksThrottleReasonsFunc() +} + +// GetSupportedClocksThrottleReasonsCalls gets all the calls that were made to GetSupportedClocksThrottleReasons. +// Check the length with: +// +// len(mockedDevice.GetSupportedClocksThrottleReasonsCalls()) +func (mock *Device) GetSupportedClocksThrottleReasonsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedClocksThrottleReasons.RLock() + calls = mock.calls.GetSupportedClocksThrottleReasons + mock.lockGetSupportedClocksThrottleReasons.RUnlock() + return calls +} + +// GetSupportedEventTypes calls GetSupportedEventTypesFunc. +func (mock *Device) GetSupportedEventTypes() (uint64, nvml.Return) { + if mock.GetSupportedEventTypesFunc == nil { + panic("Device.GetSupportedEventTypesFunc: method is nil but Device.GetSupportedEventTypes was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedEventTypes.Lock() + mock.calls.GetSupportedEventTypes = append(mock.calls.GetSupportedEventTypes, callInfo) + mock.lockGetSupportedEventTypes.Unlock() + return mock.GetSupportedEventTypesFunc() +} + +// GetSupportedEventTypesCalls gets all the calls that were made to GetSupportedEventTypes. +// Check the length with: +// +// len(mockedDevice.GetSupportedEventTypesCalls()) +func (mock *Device) GetSupportedEventTypesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedEventTypes.RLock() + calls = mock.calls.GetSupportedEventTypes + mock.lockGetSupportedEventTypes.RUnlock() + return calls +} + +// GetSupportedGraphicsClocks calls GetSupportedGraphicsClocksFunc. +func (mock *Device) GetSupportedGraphicsClocks(n int) (int, uint32, nvml.Return) { + if mock.GetSupportedGraphicsClocksFunc == nil { + panic("Device.GetSupportedGraphicsClocksFunc: method is nil but Device.GetSupportedGraphicsClocks was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetSupportedGraphicsClocks.Lock() + mock.calls.GetSupportedGraphicsClocks = append(mock.calls.GetSupportedGraphicsClocks, callInfo) + mock.lockGetSupportedGraphicsClocks.Unlock() + return mock.GetSupportedGraphicsClocksFunc(n) +} + +// GetSupportedGraphicsClocksCalls gets all the calls that were made to GetSupportedGraphicsClocks. +// Check the length with: +// +// len(mockedDevice.GetSupportedGraphicsClocksCalls()) +func (mock *Device) GetSupportedGraphicsClocksCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetSupportedGraphicsClocks.RLock() + calls = mock.calls.GetSupportedGraphicsClocks + mock.lockGetSupportedGraphicsClocks.RUnlock() + return calls +} + +// GetSupportedMemoryClocks calls GetSupportedMemoryClocksFunc. +func (mock *Device) GetSupportedMemoryClocks() (int, uint32, nvml.Return) { + if mock.GetSupportedMemoryClocksFunc == nil { + panic("Device.GetSupportedMemoryClocksFunc: method is nil but Device.GetSupportedMemoryClocks was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedMemoryClocks.Lock() + mock.calls.GetSupportedMemoryClocks = append(mock.calls.GetSupportedMemoryClocks, callInfo) + mock.lockGetSupportedMemoryClocks.Unlock() + return mock.GetSupportedMemoryClocksFunc() +} + +// GetSupportedMemoryClocksCalls gets all the calls that were made to GetSupportedMemoryClocks. +// Check the length with: +// +// len(mockedDevice.GetSupportedMemoryClocksCalls()) +func (mock *Device) GetSupportedMemoryClocksCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedMemoryClocks.RLock() + calls = mock.calls.GetSupportedMemoryClocks + mock.lockGetSupportedMemoryClocks.RUnlock() + return calls +} + +// GetSupportedPerformanceStates calls GetSupportedPerformanceStatesFunc. +func (mock *Device) GetSupportedPerformanceStates() ([]nvml.Pstates, nvml.Return) { + if mock.GetSupportedPerformanceStatesFunc == nil { + panic("Device.GetSupportedPerformanceStatesFunc: method is nil but Device.GetSupportedPerformanceStates was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedPerformanceStates.Lock() + mock.calls.GetSupportedPerformanceStates = append(mock.calls.GetSupportedPerformanceStates, callInfo) + mock.lockGetSupportedPerformanceStates.Unlock() + return mock.GetSupportedPerformanceStatesFunc() +} + +// GetSupportedPerformanceStatesCalls gets all the calls that were made to GetSupportedPerformanceStates. +// Check the length with: +// +// len(mockedDevice.GetSupportedPerformanceStatesCalls()) +func (mock *Device) GetSupportedPerformanceStatesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedPerformanceStates.RLock() + calls = mock.calls.GetSupportedPerformanceStates + mock.lockGetSupportedPerformanceStates.RUnlock() + return calls +} + +// GetSupportedVgpus calls GetSupportedVgpusFunc. +func (mock *Device) GetSupportedVgpus() ([]nvml.VgpuTypeId, nvml.Return) { + if mock.GetSupportedVgpusFunc == nil { + panic("Device.GetSupportedVgpusFunc: method is nil but Device.GetSupportedVgpus was just called") + } + callInfo := struct { + }{} + mock.lockGetSupportedVgpus.Lock() + mock.calls.GetSupportedVgpus = append(mock.calls.GetSupportedVgpus, callInfo) + mock.lockGetSupportedVgpus.Unlock() + return mock.GetSupportedVgpusFunc() +} + +// GetSupportedVgpusCalls gets all the calls that were made to GetSupportedVgpus. +// Check the length with: +// +// len(mockedDevice.GetSupportedVgpusCalls()) +func (mock *Device) GetSupportedVgpusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetSupportedVgpus.RLock() + calls = mock.calls.GetSupportedVgpus + mock.lockGetSupportedVgpus.RUnlock() + return calls +} + +// GetTargetFanSpeed calls GetTargetFanSpeedFunc. +func (mock *Device) GetTargetFanSpeed(n int) (int, nvml.Return) { + if mock.GetTargetFanSpeedFunc == nil { + panic("Device.GetTargetFanSpeedFunc: method is nil but Device.GetTargetFanSpeed was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetTargetFanSpeed.Lock() + mock.calls.GetTargetFanSpeed = append(mock.calls.GetTargetFanSpeed, callInfo) + mock.lockGetTargetFanSpeed.Unlock() + return mock.GetTargetFanSpeedFunc(n) +} + +// GetTargetFanSpeedCalls gets all the calls that were made to GetTargetFanSpeed. +// Check the length with: +// +// len(mockedDevice.GetTargetFanSpeedCalls()) +func (mock *Device) GetTargetFanSpeedCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetTargetFanSpeed.RLock() + calls = mock.calls.GetTargetFanSpeed + mock.lockGetTargetFanSpeed.RUnlock() + return calls +} + +// GetTemperature calls GetTemperatureFunc. +func (mock *Device) GetTemperature(temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) { + if mock.GetTemperatureFunc == nil { + panic("Device.GetTemperatureFunc: method is nil but Device.GetTemperature was just called") + } + callInfo := struct { + TemperatureSensors nvml.TemperatureSensors + }{ + TemperatureSensors: temperatureSensors, + } + mock.lockGetTemperature.Lock() + mock.calls.GetTemperature = append(mock.calls.GetTemperature, callInfo) + mock.lockGetTemperature.Unlock() + return mock.GetTemperatureFunc(temperatureSensors) +} + +// GetTemperatureCalls gets all the calls that were made to GetTemperature. +// Check the length with: +// +// len(mockedDevice.GetTemperatureCalls()) +func (mock *Device) GetTemperatureCalls() []struct { + TemperatureSensors nvml.TemperatureSensors +} { + var calls []struct { + TemperatureSensors nvml.TemperatureSensors + } + mock.lockGetTemperature.RLock() + calls = mock.calls.GetTemperature + mock.lockGetTemperature.RUnlock() + return calls +} + +// GetTemperatureThreshold calls GetTemperatureThresholdFunc. +func (mock *Device) GetTemperatureThreshold(temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) { + if mock.GetTemperatureThresholdFunc == nil { + panic("Device.GetTemperatureThresholdFunc: method is nil but Device.GetTemperatureThreshold was just called") + } + callInfo := struct { + TemperatureThresholds nvml.TemperatureThresholds + }{ + TemperatureThresholds: temperatureThresholds, + } + mock.lockGetTemperatureThreshold.Lock() + mock.calls.GetTemperatureThreshold = append(mock.calls.GetTemperatureThreshold, callInfo) + mock.lockGetTemperatureThreshold.Unlock() + return mock.GetTemperatureThresholdFunc(temperatureThresholds) +} + +// GetTemperatureThresholdCalls gets all the calls that were made to GetTemperatureThreshold. +// Check the length with: +// +// len(mockedDevice.GetTemperatureThresholdCalls()) +func (mock *Device) GetTemperatureThresholdCalls() []struct { + TemperatureThresholds nvml.TemperatureThresholds +} { + var calls []struct { + TemperatureThresholds nvml.TemperatureThresholds + } + mock.lockGetTemperatureThreshold.RLock() + calls = mock.calls.GetTemperatureThreshold + mock.lockGetTemperatureThreshold.RUnlock() + return calls +} + +// GetTemperatureV calls GetTemperatureVFunc. +func (mock *Device) GetTemperatureV() nvml.TemperatureHandler { + if mock.GetTemperatureVFunc == nil { + panic("Device.GetTemperatureVFunc: method is nil but Device.GetTemperatureV was just called") + } + callInfo := struct { + }{} + mock.lockGetTemperatureV.Lock() + mock.calls.GetTemperatureV = append(mock.calls.GetTemperatureV, callInfo) + mock.lockGetTemperatureV.Unlock() + return mock.GetTemperatureVFunc() +} + +// GetTemperatureVCalls gets all the calls that were made to GetTemperatureV. +// Check the length with: +// +// len(mockedDevice.GetTemperatureVCalls()) +func (mock *Device) GetTemperatureVCalls() []struct { +} { + var calls []struct { + } + mock.lockGetTemperatureV.RLock() + calls = mock.calls.GetTemperatureV + mock.lockGetTemperatureV.RUnlock() + return calls +} + +// GetThermalSettings calls GetThermalSettingsFunc. +func (mock *Device) GetThermalSettings(v uint32) (nvml.GpuThermalSettings, nvml.Return) { + if mock.GetThermalSettingsFunc == nil { + panic("Device.GetThermalSettingsFunc: method is nil but Device.GetThermalSettings was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockGetThermalSettings.Lock() + mock.calls.GetThermalSettings = append(mock.calls.GetThermalSettings, callInfo) + mock.lockGetThermalSettings.Unlock() + return mock.GetThermalSettingsFunc(v) +} + +// GetThermalSettingsCalls gets all the calls that were made to GetThermalSettings. +// Check the length with: +// +// len(mockedDevice.GetThermalSettingsCalls()) +func (mock *Device) GetThermalSettingsCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockGetThermalSettings.RLock() + calls = mock.calls.GetThermalSettings + mock.lockGetThermalSettings.RUnlock() + return calls +} + +// GetTopologyCommonAncestor calls GetTopologyCommonAncestorFunc. +func (mock *Device) GetTopologyCommonAncestor(device nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) { + if mock.GetTopologyCommonAncestorFunc == nil { + panic("Device.GetTopologyCommonAncestorFunc: method is nil but Device.GetTopologyCommonAncestor was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGetTopologyCommonAncestor.Lock() + mock.calls.GetTopologyCommonAncestor = append(mock.calls.GetTopologyCommonAncestor, callInfo) + mock.lockGetTopologyCommonAncestor.Unlock() + return mock.GetTopologyCommonAncestorFunc(device) +} + +// GetTopologyCommonAncestorCalls gets all the calls that were made to GetTopologyCommonAncestor. +// Check the length with: +// +// len(mockedDevice.GetTopologyCommonAncestorCalls()) +func (mock *Device) GetTopologyCommonAncestorCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGetTopologyCommonAncestor.RLock() + calls = mock.calls.GetTopologyCommonAncestor + mock.lockGetTopologyCommonAncestor.RUnlock() + return calls +} + +// GetTopologyNearestGpus calls GetTopologyNearestGpusFunc. +func (mock *Device) GetTopologyNearestGpus(gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) { + if mock.GetTopologyNearestGpusFunc == nil { + panic("Device.GetTopologyNearestGpusFunc: method is nil but Device.GetTopologyNearestGpus was just called") + } + callInfo := struct { + GpuTopologyLevel nvml.GpuTopologyLevel + }{ + GpuTopologyLevel: gpuTopologyLevel, + } + mock.lockGetTopologyNearestGpus.Lock() + mock.calls.GetTopologyNearestGpus = append(mock.calls.GetTopologyNearestGpus, callInfo) + mock.lockGetTopologyNearestGpus.Unlock() + return mock.GetTopologyNearestGpusFunc(gpuTopologyLevel) +} + +// GetTopologyNearestGpusCalls gets all the calls that were made to GetTopologyNearestGpus. +// Check the length with: +// +// len(mockedDevice.GetTopologyNearestGpusCalls()) +func (mock *Device) GetTopologyNearestGpusCalls() []struct { + GpuTopologyLevel nvml.GpuTopologyLevel +} { + var calls []struct { + GpuTopologyLevel nvml.GpuTopologyLevel + } + mock.lockGetTopologyNearestGpus.RLock() + calls = mock.calls.GetTopologyNearestGpus + mock.lockGetTopologyNearestGpus.RUnlock() + return calls +} + +// GetTotalEccErrors calls GetTotalEccErrorsFunc. +func (mock *Device) GetTotalEccErrors(memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) { + if mock.GetTotalEccErrorsFunc == nil { + panic("Device.GetTotalEccErrorsFunc: method is nil but Device.GetTotalEccErrors was just called") + } + callInfo := struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + }{ + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + } + mock.lockGetTotalEccErrors.Lock() + mock.calls.GetTotalEccErrors = append(mock.calls.GetTotalEccErrors, callInfo) + mock.lockGetTotalEccErrors.Unlock() + return mock.GetTotalEccErrorsFunc(memoryErrorType, eccCounterType) +} + +// GetTotalEccErrorsCalls gets all the calls that were made to GetTotalEccErrors. +// Check the length with: +// +// len(mockedDevice.GetTotalEccErrorsCalls()) +func (mock *Device) GetTotalEccErrorsCalls() []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType +} { + var calls []struct { + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + } + mock.lockGetTotalEccErrors.RLock() + calls = mock.calls.GetTotalEccErrors + mock.lockGetTotalEccErrors.RUnlock() + return calls +} + +// GetTotalEnergyConsumption calls GetTotalEnergyConsumptionFunc. +func (mock *Device) GetTotalEnergyConsumption() (uint64, nvml.Return) { + if mock.GetTotalEnergyConsumptionFunc == nil { + panic("Device.GetTotalEnergyConsumptionFunc: method is nil but Device.GetTotalEnergyConsumption was just called") + } + callInfo := struct { + }{} + mock.lockGetTotalEnergyConsumption.Lock() + mock.calls.GetTotalEnergyConsumption = append(mock.calls.GetTotalEnergyConsumption, callInfo) + mock.lockGetTotalEnergyConsumption.Unlock() + return mock.GetTotalEnergyConsumptionFunc() +} + +// GetTotalEnergyConsumptionCalls gets all the calls that were made to GetTotalEnergyConsumption. +// Check the length with: +// +// len(mockedDevice.GetTotalEnergyConsumptionCalls()) +func (mock *Device) GetTotalEnergyConsumptionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetTotalEnergyConsumption.RLock() + calls = mock.calls.GetTotalEnergyConsumption + mock.lockGetTotalEnergyConsumption.RUnlock() + return calls +} + +// GetUUID calls GetUUIDFunc. +func (mock *Device) GetUUID() (string, nvml.Return) { + if mock.GetUUIDFunc == nil { + panic("Device.GetUUIDFunc: method is nil but Device.GetUUID was just called") + } + callInfo := struct { + }{} + mock.lockGetUUID.Lock() + mock.calls.GetUUID = append(mock.calls.GetUUID, callInfo) + mock.lockGetUUID.Unlock() + return mock.GetUUIDFunc() +} + +// GetUUIDCalls gets all the calls that were made to GetUUID. +// Check the length with: +// +// len(mockedDevice.GetUUIDCalls()) +func (mock *Device) GetUUIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetUUID.RLock() + calls = mock.calls.GetUUID + mock.lockGetUUID.RUnlock() + return calls +} + +// GetUtilizationRates calls GetUtilizationRatesFunc. +func (mock *Device) GetUtilizationRates() (nvml.Utilization, nvml.Return) { + if mock.GetUtilizationRatesFunc == nil { + panic("Device.GetUtilizationRatesFunc: method is nil but Device.GetUtilizationRates was just called") + } + callInfo := struct { + }{} + mock.lockGetUtilizationRates.Lock() + mock.calls.GetUtilizationRates = append(mock.calls.GetUtilizationRates, callInfo) + mock.lockGetUtilizationRates.Unlock() + return mock.GetUtilizationRatesFunc() +} + +// GetUtilizationRatesCalls gets all the calls that were made to GetUtilizationRates. +// Check the length with: +// +// len(mockedDevice.GetUtilizationRatesCalls()) +func (mock *Device) GetUtilizationRatesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetUtilizationRates.RLock() + calls = mock.calls.GetUtilizationRates + mock.lockGetUtilizationRates.RUnlock() + return calls +} + +// GetVbiosVersion calls GetVbiosVersionFunc. +func (mock *Device) GetVbiosVersion() (string, nvml.Return) { + if mock.GetVbiosVersionFunc == nil { + panic("Device.GetVbiosVersionFunc: method is nil but Device.GetVbiosVersion was just called") + } + callInfo := struct { + }{} + mock.lockGetVbiosVersion.Lock() + mock.calls.GetVbiosVersion = append(mock.calls.GetVbiosVersion, callInfo) + mock.lockGetVbiosVersion.Unlock() + return mock.GetVbiosVersionFunc() +} + +// GetVbiosVersionCalls gets all the calls that were made to GetVbiosVersion. +// Check the length with: +// +// len(mockedDevice.GetVbiosVersionCalls()) +func (mock *Device) GetVbiosVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVbiosVersion.RLock() + calls = mock.calls.GetVbiosVersion + mock.lockGetVbiosVersion.RUnlock() + return calls +} + +// GetVgpuCapabilities calls GetVgpuCapabilitiesFunc. +func (mock *Device) GetVgpuCapabilities(deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) { + if mock.GetVgpuCapabilitiesFunc == nil { + panic("Device.GetVgpuCapabilitiesFunc: method is nil but Device.GetVgpuCapabilities was just called") + } + callInfo := struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability + }{ + DeviceVgpuCapability: deviceVgpuCapability, + } + mock.lockGetVgpuCapabilities.Lock() + mock.calls.GetVgpuCapabilities = append(mock.calls.GetVgpuCapabilities, callInfo) + mock.lockGetVgpuCapabilities.Unlock() + return mock.GetVgpuCapabilitiesFunc(deviceVgpuCapability) +} + +// GetVgpuCapabilitiesCalls gets all the calls that were made to GetVgpuCapabilities. +// Check the length with: +// +// len(mockedDevice.GetVgpuCapabilitiesCalls()) +func (mock *Device) GetVgpuCapabilitiesCalls() []struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability +} { + var calls []struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability + } + mock.lockGetVgpuCapabilities.RLock() + calls = mock.calls.GetVgpuCapabilities + mock.lockGetVgpuCapabilities.RUnlock() + return calls +} + +// GetVgpuHeterogeneousMode calls GetVgpuHeterogeneousModeFunc. +func (mock *Device) GetVgpuHeterogeneousMode() (nvml.VgpuHeterogeneousMode, nvml.Return) { + if mock.GetVgpuHeterogeneousModeFunc == nil { + panic("Device.GetVgpuHeterogeneousModeFunc: method is nil but Device.GetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuHeterogeneousMode.Lock() + mock.calls.GetVgpuHeterogeneousMode = append(mock.calls.GetVgpuHeterogeneousMode, callInfo) + mock.lockGetVgpuHeterogeneousMode.Unlock() + return mock.GetVgpuHeterogeneousModeFunc() +} + +// GetVgpuHeterogeneousModeCalls gets all the calls that were made to GetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedDevice.GetVgpuHeterogeneousModeCalls()) +func (mock *Device) GetVgpuHeterogeneousModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuHeterogeneousMode.RLock() + calls = mock.calls.GetVgpuHeterogeneousMode + mock.lockGetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// GetVgpuInstancesUtilizationInfo calls GetVgpuInstancesUtilizationInfoFunc. +func (mock *Device) GetVgpuInstancesUtilizationInfo() (nvml.VgpuInstancesUtilizationInfo, nvml.Return) { + if mock.GetVgpuInstancesUtilizationInfoFunc == nil { + panic("Device.GetVgpuInstancesUtilizationInfoFunc: method is nil but Device.GetVgpuInstancesUtilizationInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuInstancesUtilizationInfo.Lock() + mock.calls.GetVgpuInstancesUtilizationInfo = append(mock.calls.GetVgpuInstancesUtilizationInfo, callInfo) + mock.lockGetVgpuInstancesUtilizationInfo.Unlock() + return mock.GetVgpuInstancesUtilizationInfoFunc() +} + +// GetVgpuInstancesUtilizationInfoCalls gets all the calls that were made to GetVgpuInstancesUtilizationInfo. +// Check the length with: +// +// len(mockedDevice.GetVgpuInstancesUtilizationInfoCalls()) +func (mock *Device) GetVgpuInstancesUtilizationInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuInstancesUtilizationInfo.RLock() + calls = mock.calls.GetVgpuInstancesUtilizationInfo + mock.lockGetVgpuInstancesUtilizationInfo.RUnlock() + return calls +} + +// GetVgpuMetadata calls GetVgpuMetadataFunc. +func (mock *Device) GetVgpuMetadata() (nvml.VgpuPgpuMetadata, nvml.Return) { + if mock.GetVgpuMetadataFunc == nil { + panic("Device.GetVgpuMetadataFunc: method is nil but Device.GetVgpuMetadata was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuMetadata.Lock() + mock.calls.GetVgpuMetadata = append(mock.calls.GetVgpuMetadata, callInfo) + mock.lockGetVgpuMetadata.Unlock() + return mock.GetVgpuMetadataFunc() +} + +// GetVgpuMetadataCalls gets all the calls that were made to GetVgpuMetadata. +// Check the length with: +// +// len(mockedDevice.GetVgpuMetadataCalls()) +func (mock *Device) GetVgpuMetadataCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuMetadata.RLock() + calls = mock.calls.GetVgpuMetadata + mock.lockGetVgpuMetadata.RUnlock() + return calls +} + +// GetVgpuProcessUtilization calls GetVgpuProcessUtilizationFunc. +func (mock *Device) GetVgpuProcessUtilization(v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) { + if mock.GetVgpuProcessUtilizationFunc == nil { + panic("Device.GetVgpuProcessUtilizationFunc: method is nil but Device.GetVgpuProcessUtilization was just called") + } + callInfo := struct { + V uint64 + }{ + V: v, + } + mock.lockGetVgpuProcessUtilization.Lock() + mock.calls.GetVgpuProcessUtilization = append(mock.calls.GetVgpuProcessUtilization, callInfo) + mock.lockGetVgpuProcessUtilization.Unlock() + return mock.GetVgpuProcessUtilizationFunc(v) +} + +// GetVgpuProcessUtilizationCalls gets all the calls that were made to GetVgpuProcessUtilization. +// Check the length with: +// +// len(mockedDevice.GetVgpuProcessUtilizationCalls()) +func (mock *Device) GetVgpuProcessUtilizationCalls() []struct { + V uint64 +} { + var calls []struct { + V uint64 + } + mock.lockGetVgpuProcessUtilization.RLock() + calls = mock.calls.GetVgpuProcessUtilization + mock.lockGetVgpuProcessUtilization.RUnlock() + return calls +} + +// GetVgpuProcessesUtilizationInfo calls GetVgpuProcessesUtilizationInfoFunc. +func (mock *Device) GetVgpuProcessesUtilizationInfo() (nvml.VgpuProcessesUtilizationInfo, nvml.Return) { + if mock.GetVgpuProcessesUtilizationInfoFunc == nil { + panic("Device.GetVgpuProcessesUtilizationInfoFunc: method is nil but Device.GetVgpuProcessesUtilizationInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuProcessesUtilizationInfo.Lock() + mock.calls.GetVgpuProcessesUtilizationInfo = append(mock.calls.GetVgpuProcessesUtilizationInfo, callInfo) + mock.lockGetVgpuProcessesUtilizationInfo.Unlock() + return mock.GetVgpuProcessesUtilizationInfoFunc() +} + +// GetVgpuProcessesUtilizationInfoCalls gets all the calls that were made to GetVgpuProcessesUtilizationInfo. +// Check the length with: +// +// len(mockedDevice.GetVgpuProcessesUtilizationInfoCalls()) +func (mock *Device) GetVgpuProcessesUtilizationInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuProcessesUtilizationInfo.RLock() + calls = mock.calls.GetVgpuProcessesUtilizationInfo + mock.lockGetVgpuProcessesUtilizationInfo.RUnlock() + return calls +} + +// GetVgpuSchedulerCapabilities calls GetVgpuSchedulerCapabilitiesFunc. +func (mock *Device) GetVgpuSchedulerCapabilities() (nvml.VgpuSchedulerCapabilities, nvml.Return) { + if mock.GetVgpuSchedulerCapabilitiesFunc == nil { + panic("Device.GetVgpuSchedulerCapabilitiesFunc: method is nil but Device.GetVgpuSchedulerCapabilities was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuSchedulerCapabilities.Lock() + mock.calls.GetVgpuSchedulerCapabilities = append(mock.calls.GetVgpuSchedulerCapabilities, callInfo) + mock.lockGetVgpuSchedulerCapabilities.Unlock() + return mock.GetVgpuSchedulerCapabilitiesFunc() +} + +// GetVgpuSchedulerCapabilitiesCalls gets all the calls that were made to GetVgpuSchedulerCapabilities. +// Check the length with: +// +// len(mockedDevice.GetVgpuSchedulerCapabilitiesCalls()) +func (mock *Device) GetVgpuSchedulerCapabilitiesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuSchedulerCapabilities.RLock() + calls = mock.calls.GetVgpuSchedulerCapabilities + mock.lockGetVgpuSchedulerCapabilities.RUnlock() + return calls +} + +// GetVgpuSchedulerLog calls GetVgpuSchedulerLogFunc. +func (mock *Device) GetVgpuSchedulerLog() (nvml.VgpuSchedulerLog, nvml.Return) { + if mock.GetVgpuSchedulerLogFunc == nil { + panic("Device.GetVgpuSchedulerLogFunc: method is nil but Device.GetVgpuSchedulerLog was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuSchedulerLog.Lock() + mock.calls.GetVgpuSchedulerLog = append(mock.calls.GetVgpuSchedulerLog, callInfo) + mock.lockGetVgpuSchedulerLog.Unlock() + return mock.GetVgpuSchedulerLogFunc() +} + +// GetVgpuSchedulerLogCalls gets all the calls that were made to GetVgpuSchedulerLog. +// Check the length with: +// +// len(mockedDevice.GetVgpuSchedulerLogCalls()) +func (mock *Device) GetVgpuSchedulerLogCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuSchedulerLog.RLock() + calls = mock.calls.GetVgpuSchedulerLog + mock.lockGetVgpuSchedulerLog.RUnlock() + return calls +} + +// GetVgpuSchedulerState calls GetVgpuSchedulerStateFunc. +func (mock *Device) GetVgpuSchedulerState() (nvml.VgpuSchedulerGetState, nvml.Return) { + if mock.GetVgpuSchedulerStateFunc == nil { + panic("Device.GetVgpuSchedulerStateFunc: method is nil but Device.GetVgpuSchedulerState was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuSchedulerState.Lock() + mock.calls.GetVgpuSchedulerState = append(mock.calls.GetVgpuSchedulerState, callInfo) + mock.lockGetVgpuSchedulerState.Unlock() + return mock.GetVgpuSchedulerStateFunc() +} + +// GetVgpuSchedulerStateCalls gets all the calls that were made to GetVgpuSchedulerState. +// Check the length with: +// +// len(mockedDevice.GetVgpuSchedulerStateCalls()) +func (mock *Device) GetVgpuSchedulerStateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuSchedulerState.RLock() + calls = mock.calls.GetVgpuSchedulerState + mock.lockGetVgpuSchedulerState.RUnlock() + return calls +} + +// GetVgpuTypeCreatablePlacements calls GetVgpuTypeCreatablePlacementsFunc. +func (mock *Device) GetVgpuTypeCreatablePlacements(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { + if mock.GetVgpuTypeCreatablePlacementsFunc == nil { + panic("Device.GetVgpuTypeCreatablePlacementsFunc: method is nil but Device.GetVgpuTypeCreatablePlacements was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockGetVgpuTypeCreatablePlacements.Lock() + mock.calls.GetVgpuTypeCreatablePlacements = append(mock.calls.GetVgpuTypeCreatablePlacements, callInfo) + mock.lockGetVgpuTypeCreatablePlacements.Unlock() + return mock.GetVgpuTypeCreatablePlacementsFunc(vgpuTypeId) +} + +// GetVgpuTypeCreatablePlacementsCalls gets all the calls that were made to GetVgpuTypeCreatablePlacements. +// Check the length with: +// +// len(mockedDevice.GetVgpuTypeCreatablePlacementsCalls()) +func (mock *Device) GetVgpuTypeCreatablePlacementsCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockGetVgpuTypeCreatablePlacements.RLock() + calls = mock.calls.GetVgpuTypeCreatablePlacements + mock.lockGetVgpuTypeCreatablePlacements.RUnlock() + return calls +} + +// GetVgpuTypeSupportedPlacements calls GetVgpuTypeSupportedPlacementsFunc. +func (mock *Device) GetVgpuTypeSupportedPlacements(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { + if mock.GetVgpuTypeSupportedPlacementsFunc == nil { + panic("Device.GetVgpuTypeSupportedPlacementsFunc: method is nil but Device.GetVgpuTypeSupportedPlacements was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockGetVgpuTypeSupportedPlacements.Lock() + mock.calls.GetVgpuTypeSupportedPlacements = append(mock.calls.GetVgpuTypeSupportedPlacements, callInfo) + mock.lockGetVgpuTypeSupportedPlacements.Unlock() + return mock.GetVgpuTypeSupportedPlacementsFunc(vgpuTypeId) +} + +// GetVgpuTypeSupportedPlacementsCalls gets all the calls that were made to GetVgpuTypeSupportedPlacements. +// Check the length with: +// +// len(mockedDevice.GetVgpuTypeSupportedPlacementsCalls()) +func (mock *Device) GetVgpuTypeSupportedPlacementsCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockGetVgpuTypeSupportedPlacements.RLock() + calls = mock.calls.GetVgpuTypeSupportedPlacements + mock.lockGetVgpuTypeSupportedPlacements.RUnlock() + return calls +} + +// GetVgpuUtilization calls GetVgpuUtilizationFunc. +func (mock *Device) GetVgpuUtilization(v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) { + if mock.GetVgpuUtilizationFunc == nil { + panic("Device.GetVgpuUtilizationFunc: method is nil but Device.GetVgpuUtilization was just called") + } + callInfo := struct { + V uint64 + }{ + V: v, + } + mock.lockGetVgpuUtilization.Lock() + mock.calls.GetVgpuUtilization = append(mock.calls.GetVgpuUtilization, callInfo) + mock.lockGetVgpuUtilization.Unlock() + return mock.GetVgpuUtilizationFunc(v) +} + +// GetVgpuUtilizationCalls gets all the calls that were made to GetVgpuUtilization. +// Check the length with: +// +// len(mockedDevice.GetVgpuUtilizationCalls()) +func (mock *Device) GetVgpuUtilizationCalls() []struct { + V uint64 +} { + var calls []struct { + V uint64 + } + mock.lockGetVgpuUtilization.RLock() + calls = mock.calls.GetVgpuUtilization + mock.lockGetVgpuUtilization.RUnlock() + return calls +} + +// GetViolationStatus calls GetViolationStatusFunc. +func (mock *Device) GetViolationStatus(perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) { + if mock.GetViolationStatusFunc == nil { + panic("Device.GetViolationStatusFunc: method is nil but Device.GetViolationStatus was just called") + } + callInfo := struct { + PerfPolicyType nvml.PerfPolicyType + }{ + PerfPolicyType: perfPolicyType, + } + mock.lockGetViolationStatus.Lock() + mock.calls.GetViolationStatus = append(mock.calls.GetViolationStatus, callInfo) + mock.lockGetViolationStatus.Unlock() + return mock.GetViolationStatusFunc(perfPolicyType) +} + +// GetViolationStatusCalls gets all the calls that were made to GetViolationStatus. +// Check the length with: +// +// len(mockedDevice.GetViolationStatusCalls()) +func (mock *Device) GetViolationStatusCalls() []struct { + PerfPolicyType nvml.PerfPolicyType +} { + var calls []struct { + PerfPolicyType nvml.PerfPolicyType + } + mock.lockGetViolationStatus.RLock() + calls = mock.calls.GetViolationStatus + mock.lockGetViolationStatus.RUnlock() + return calls +} + +// GetVirtualizationMode calls GetVirtualizationModeFunc. +func (mock *Device) GetVirtualizationMode() (nvml.GpuVirtualizationMode, nvml.Return) { + if mock.GetVirtualizationModeFunc == nil { + panic("Device.GetVirtualizationModeFunc: method is nil but Device.GetVirtualizationMode was just called") + } + callInfo := struct { + }{} + mock.lockGetVirtualizationMode.Lock() + mock.calls.GetVirtualizationMode = append(mock.calls.GetVirtualizationMode, callInfo) + mock.lockGetVirtualizationMode.Unlock() + return mock.GetVirtualizationModeFunc() +} + +// GetVirtualizationModeCalls gets all the calls that were made to GetVirtualizationMode. +// Check the length with: +// +// len(mockedDevice.GetVirtualizationModeCalls()) +func (mock *Device) GetVirtualizationModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVirtualizationMode.RLock() + calls = mock.calls.GetVirtualizationMode + mock.lockGetVirtualizationMode.RUnlock() + return calls +} + +// GpmMigSampleGet calls GpmMigSampleGetFunc. +func (mock *Device) GpmMigSampleGet(n int, gpmSample nvml.GpmSample) nvml.Return { + if mock.GpmMigSampleGetFunc == nil { + panic("Device.GpmMigSampleGetFunc: method is nil but Device.GpmMigSampleGet was just called") + } + callInfo := struct { + N int + GpmSample nvml.GpmSample + }{ + N: n, + GpmSample: gpmSample, + } + mock.lockGpmMigSampleGet.Lock() + mock.calls.GpmMigSampleGet = append(mock.calls.GpmMigSampleGet, callInfo) + mock.lockGpmMigSampleGet.Unlock() + return mock.GpmMigSampleGetFunc(n, gpmSample) +} + +// GpmMigSampleGetCalls gets all the calls that were made to GpmMigSampleGet. +// Check the length with: +// +// len(mockedDevice.GpmMigSampleGetCalls()) +func (mock *Device) GpmMigSampleGetCalls() []struct { + N int + GpmSample nvml.GpmSample +} { + var calls []struct { + N int + GpmSample nvml.GpmSample + } + mock.lockGpmMigSampleGet.RLock() + calls = mock.calls.GpmMigSampleGet + mock.lockGpmMigSampleGet.RUnlock() + return calls +} + +// GpmQueryDeviceSupport calls GpmQueryDeviceSupportFunc. +func (mock *Device) GpmQueryDeviceSupport() (nvml.GpmSupport, nvml.Return) { + if mock.GpmQueryDeviceSupportFunc == nil { + panic("Device.GpmQueryDeviceSupportFunc: method is nil but Device.GpmQueryDeviceSupport was just called") + } + callInfo := struct { + }{} + mock.lockGpmQueryDeviceSupport.Lock() + mock.calls.GpmQueryDeviceSupport = append(mock.calls.GpmQueryDeviceSupport, callInfo) + mock.lockGpmQueryDeviceSupport.Unlock() + return mock.GpmQueryDeviceSupportFunc() +} + +// GpmQueryDeviceSupportCalls gets all the calls that were made to GpmQueryDeviceSupport. +// Check the length with: +// +// len(mockedDevice.GpmQueryDeviceSupportCalls()) +func (mock *Device) GpmQueryDeviceSupportCalls() []struct { +} { + var calls []struct { + } + mock.lockGpmQueryDeviceSupport.RLock() + calls = mock.calls.GpmQueryDeviceSupport + mock.lockGpmQueryDeviceSupport.RUnlock() + return calls +} + +// GpmQueryDeviceSupportV calls GpmQueryDeviceSupportVFunc. +func (mock *Device) GpmQueryDeviceSupportV() nvml.GpmSupportV { + if mock.GpmQueryDeviceSupportVFunc == nil { + panic("Device.GpmQueryDeviceSupportVFunc: method is nil but Device.GpmQueryDeviceSupportV was just called") + } + callInfo := struct { + }{} + mock.lockGpmQueryDeviceSupportV.Lock() + mock.calls.GpmQueryDeviceSupportV = append(mock.calls.GpmQueryDeviceSupportV, callInfo) + mock.lockGpmQueryDeviceSupportV.Unlock() + return mock.GpmQueryDeviceSupportVFunc() +} + +// GpmQueryDeviceSupportVCalls gets all the calls that were made to GpmQueryDeviceSupportV. +// Check the length with: +// +// len(mockedDevice.GpmQueryDeviceSupportVCalls()) +func (mock *Device) GpmQueryDeviceSupportVCalls() []struct { +} { + var calls []struct { + } + mock.lockGpmQueryDeviceSupportV.RLock() + calls = mock.calls.GpmQueryDeviceSupportV + mock.lockGpmQueryDeviceSupportV.RUnlock() + return calls +} + +// GpmQueryIfStreamingEnabled calls GpmQueryIfStreamingEnabledFunc. +func (mock *Device) GpmQueryIfStreamingEnabled() (uint32, nvml.Return) { + if mock.GpmQueryIfStreamingEnabledFunc == nil { + panic("Device.GpmQueryIfStreamingEnabledFunc: method is nil but Device.GpmQueryIfStreamingEnabled was just called") + } + callInfo := struct { + }{} + mock.lockGpmQueryIfStreamingEnabled.Lock() + mock.calls.GpmQueryIfStreamingEnabled = append(mock.calls.GpmQueryIfStreamingEnabled, callInfo) + mock.lockGpmQueryIfStreamingEnabled.Unlock() + return mock.GpmQueryIfStreamingEnabledFunc() +} + +// GpmQueryIfStreamingEnabledCalls gets all the calls that were made to GpmQueryIfStreamingEnabled. +// Check the length with: +// +// len(mockedDevice.GpmQueryIfStreamingEnabledCalls()) +func (mock *Device) GpmQueryIfStreamingEnabledCalls() []struct { +} { + var calls []struct { + } + mock.lockGpmQueryIfStreamingEnabled.RLock() + calls = mock.calls.GpmQueryIfStreamingEnabled + mock.lockGpmQueryIfStreamingEnabled.RUnlock() + return calls +} + +// GpmSampleGet calls GpmSampleGetFunc. +func (mock *Device) GpmSampleGet(gpmSample nvml.GpmSample) nvml.Return { + if mock.GpmSampleGetFunc == nil { + panic("Device.GpmSampleGetFunc: method is nil but Device.GpmSampleGet was just called") + } + callInfo := struct { + GpmSample nvml.GpmSample + }{ + GpmSample: gpmSample, + } + mock.lockGpmSampleGet.Lock() + mock.calls.GpmSampleGet = append(mock.calls.GpmSampleGet, callInfo) + mock.lockGpmSampleGet.Unlock() + return mock.GpmSampleGetFunc(gpmSample) +} + +// GpmSampleGetCalls gets all the calls that were made to GpmSampleGet. +// Check the length with: +// +// len(mockedDevice.GpmSampleGetCalls()) +func (mock *Device) GpmSampleGetCalls() []struct { + GpmSample nvml.GpmSample +} { + var calls []struct { + GpmSample nvml.GpmSample + } + mock.lockGpmSampleGet.RLock() + calls = mock.calls.GpmSampleGet + mock.lockGpmSampleGet.RUnlock() + return calls +} + +// GpmSetStreamingEnabled calls GpmSetStreamingEnabledFunc. +func (mock *Device) GpmSetStreamingEnabled(v uint32) nvml.Return { + if mock.GpmSetStreamingEnabledFunc == nil { + panic("Device.GpmSetStreamingEnabledFunc: method is nil but Device.GpmSetStreamingEnabled was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockGpmSetStreamingEnabled.Lock() + mock.calls.GpmSetStreamingEnabled = append(mock.calls.GpmSetStreamingEnabled, callInfo) + mock.lockGpmSetStreamingEnabled.Unlock() + return mock.GpmSetStreamingEnabledFunc(v) +} + +// GpmSetStreamingEnabledCalls gets all the calls that were made to GpmSetStreamingEnabled. +// Check the length with: +// +// len(mockedDevice.GpmSetStreamingEnabledCalls()) +func (mock *Device) GpmSetStreamingEnabledCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockGpmSetStreamingEnabled.RLock() + calls = mock.calls.GpmSetStreamingEnabled + mock.lockGpmSetStreamingEnabled.RUnlock() + return calls +} + +// IsMigDeviceHandle calls IsMigDeviceHandleFunc. +func (mock *Device) IsMigDeviceHandle() (bool, nvml.Return) { + if mock.IsMigDeviceHandleFunc == nil { + panic("Device.IsMigDeviceHandleFunc: method is nil but Device.IsMigDeviceHandle was just called") + } + callInfo := struct { + }{} + mock.lockIsMigDeviceHandle.Lock() + mock.calls.IsMigDeviceHandle = append(mock.calls.IsMigDeviceHandle, callInfo) + mock.lockIsMigDeviceHandle.Unlock() + return mock.IsMigDeviceHandleFunc() +} + +// IsMigDeviceHandleCalls gets all the calls that were made to IsMigDeviceHandle. +// Check the length with: +// +// len(mockedDevice.IsMigDeviceHandleCalls()) +func (mock *Device) IsMigDeviceHandleCalls() []struct { +} { + var calls []struct { + } + mock.lockIsMigDeviceHandle.RLock() + calls = mock.calls.IsMigDeviceHandle + mock.lockIsMigDeviceHandle.RUnlock() + return calls +} + +// OnSameBoard calls OnSameBoardFunc. +func (mock *Device) OnSameBoard(device nvml.Device) (int, nvml.Return) { + if mock.OnSameBoardFunc == nil { + panic("Device.OnSameBoardFunc: method is nil but Device.OnSameBoard was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockOnSameBoard.Lock() + mock.calls.OnSameBoard = append(mock.calls.OnSameBoard, callInfo) + mock.lockOnSameBoard.Unlock() + return mock.OnSameBoardFunc(device) +} + +// OnSameBoardCalls gets all the calls that were made to OnSameBoard. +// Check the length with: +// +// len(mockedDevice.OnSameBoardCalls()) +func (mock *Device) OnSameBoardCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockOnSameBoard.RLock() + calls = mock.calls.OnSameBoard + mock.lockOnSameBoard.RUnlock() + return calls +} + +// PowerSmoothingActivatePresetProfile calls PowerSmoothingActivatePresetProfileFunc. +func (mock *Device) PowerSmoothingActivatePresetProfile(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { + if mock.PowerSmoothingActivatePresetProfileFunc == nil { + panic("Device.PowerSmoothingActivatePresetProfileFunc: method is nil but Device.PowerSmoothingActivatePresetProfile was just called") + } + callInfo := struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile + }{ + PowerSmoothingProfile: powerSmoothingProfile, + } + mock.lockPowerSmoothingActivatePresetProfile.Lock() + mock.calls.PowerSmoothingActivatePresetProfile = append(mock.calls.PowerSmoothingActivatePresetProfile, callInfo) + mock.lockPowerSmoothingActivatePresetProfile.Unlock() + return mock.PowerSmoothingActivatePresetProfileFunc(powerSmoothingProfile) +} + +// PowerSmoothingActivatePresetProfileCalls gets all the calls that were made to PowerSmoothingActivatePresetProfile. +// Check the length with: +// +// len(mockedDevice.PowerSmoothingActivatePresetProfileCalls()) +func (mock *Device) PowerSmoothingActivatePresetProfileCalls() []struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile +} { + var calls []struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + mock.lockPowerSmoothingActivatePresetProfile.RLock() + calls = mock.calls.PowerSmoothingActivatePresetProfile + mock.lockPowerSmoothingActivatePresetProfile.RUnlock() + return calls +} + +// PowerSmoothingSetState calls PowerSmoothingSetStateFunc. +func (mock *Device) PowerSmoothingSetState(powerSmoothingState *nvml.PowerSmoothingState) nvml.Return { + if mock.PowerSmoothingSetStateFunc == nil { + panic("Device.PowerSmoothingSetStateFunc: method is nil but Device.PowerSmoothingSetState was just called") + } + callInfo := struct { + PowerSmoothingState *nvml.PowerSmoothingState + }{ + PowerSmoothingState: powerSmoothingState, + } + mock.lockPowerSmoothingSetState.Lock() + mock.calls.PowerSmoothingSetState = append(mock.calls.PowerSmoothingSetState, callInfo) + mock.lockPowerSmoothingSetState.Unlock() + return mock.PowerSmoothingSetStateFunc(powerSmoothingState) +} + +// PowerSmoothingSetStateCalls gets all the calls that were made to PowerSmoothingSetState. +// Check the length with: +// +// len(mockedDevice.PowerSmoothingSetStateCalls()) +func (mock *Device) PowerSmoothingSetStateCalls() []struct { + PowerSmoothingState *nvml.PowerSmoothingState +} { + var calls []struct { + PowerSmoothingState *nvml.PowerSmoothingState + } + mock.lockPowerSmoothingSetState.RLock() + calls = mock.calls.PowerSmoothingSetState + mock.lockPowerSmoothingSetState.RUnlock() + return calls +} + +// PowerSmoothingUpdatePresetProfileParam calls PowerSmoothingUpdatePresetProfileParamFunc. +func (mock *Device) PowerSmoothingUpdatePresetProfileParam(powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { + if mock.PowerSmoothingUpdatePresetProfileParamFunc == nil { + panic("Device.PowerSmoothingUpdatePresetProfileParamFunc: method is nil but Device.PowerSmoothingUpdatePresetProfileParam was just called") + } + callInfo := struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile + }{ + PowerSmoothingProfile: powerSmoothingProfile, + } + mock.lockPowerSmoothingUpdatePresetProfileParam.Lock() + mock.calls.PowerSmoothingUpdatePresetProfileParam = append(mock.calls.PowerSmoothingUpdatePresetProfileParam, callInfo) + mock.lockPowerSmoothingUpdatePresetProfileParam.Unlock() + return mock.PowerSmoothingUpdatePresetProfileParamFunc(powerSmoothingProfile) +} + +// PowerSmoothingUpdatePresetProfileParamCalls gets all the calls that were made to PowerSmoothingUpdatePresetProfileParam. +// Check the length with: +// +// len(mockedDevice.PowerSmoothingUpdatePresetProfileParamCalls()) +func (mock *Device) PowerSmoothingUpdatePresetProfileParamCalls() []struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile +} { + var calls []struct { + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + mock.lockPowerSmoothingUpdatePresetProfileParam.RLock() + calls = mock.calls.PowerSmoothingUpdatePresetProfileParam + mock.lockPowerSmoothingUpdatePresetProfileParam.RUnlock() + return calls +} + +// ReadWritePRM_v1 calls ReadWritePRM_v1Func. +func (mock *Device) ReadWritePRM_v1(pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return { + if mock.ReadWritePRM_v1Func == nil { + panic("Device.ReadWritePRM_v1Func: method is nil but Device.ReadWritePRM_v1 was just called") + } + callInfo := struct { + PRMTLV_v1 *nvml.PRMTLV_v1 + }{ + PRMTLV_v1: pRMTLV_v1, + } + mock.lockReadWritePRM_v1.Lock() + mock.calls.ReadWritePRM_v1 = append(mock.calls.ReadWritePRM_v1, callInfo) + mock.lockReadWritePRM_v1.Unlock() + return mock.ReadWritePRM_v1Func(pRMTLV_v1) +} + +// ReadWritePRM_v1Calls gets all the calls that were made to ReadWritePRM_v1. +// Check the length with: +// +// len(mockedDevice.ReadWritePRM_v1Calls()) +func (mock *Device) ReadWritePRM_v1Calls() []struct { + PRMTLV_v1 *nvml.PRMTLV_v1 +} { + var calls []struct { + PRMTLV_v1 *nvml.PRMTLV_v1 + } + mock.lockReadWritePRM_v1.RLock() + calls = mock.calls.ReadWritePRM_v1 + mock.lockReadWritePRM_v1.RUnlock() + return calls +} + +// RegisterEvents calls RegisterEventsFunc. +func (mock *Device) RegisterEvents(v uint64, eventSet nvml.EventSet) nvml.Return { + if mock.RegisterEventsFunc == nil { + panic("Device.RegisterEventsFunc: method is nil but Device.RegisterEvents was just called") + } + callInfo := struct { + V uint64 + EventSet nvml.EventSet + }{ + V: v, + EventSet: eventSet, + } + mock.lockRegisterEvents.Lock() + mock.calls.RegisterEvents = append(mock.calls.RegisterEvents, callInfo) + mock.lockRegisterEvents.Unlock() + return mock.RegisterEventsFunc(v, eventSet) +} + +// RegisterEventsCalls gets all the calls that were made to RegisterEvents. +// Check the length with: +// +// len(mockedDevice.RegisterEventsCalls()) +func (mock *Device) RegisterEventsCalls() []struct { + V uint64 + EventSet nvml.EventSet +} { + var calls []struct { + V uint64 + EventSet nvml.EventSet + } + mock.lockRegisterEvents.RLock() + calls = mock.calls.RegisterEvents + mock.lockRegisterEvents.RUnlock() + return calls +} + +// ResetApplicationsClocks calls ResetApplicationsClocksFunc. +func (mock *Device) ResetApplicationsClocks() nvml.Return { + if mock.ResetApplicationsClocksFunc == nil { + panic("Device.ResetApplicationsClocksFunc: method is nil but Device.ResetApplicationsClocks was just called") + } + callInfo := struct { + }{} + mock.lockResetApplicationsClocks.Lock() + mock.calls.ResetApplicationsClocks = append(mock.calls.ResetApplicationsClocks, callInfo) + mock.lockResetApplicationsClocks.Unlock() + return mock.ResetApplicationsClocksFunc() +} + +// ResetApplicationsClocksCalls gets all the calls that were made to ResetApplicationsClocks. +// Check the length with: +// +// len(mockedDevice.ResetApplicationsClocksCalls()) +func (mock *Device) ResetApplicationsClocksCalls() []struct { +} { + var calls []struct { + } + mock.lockResetApplicationsClocks.RLock() + calls = mock.calls.ResetApplicationsClocks + mock.lockResetApplicationsClocks.RUnlock() + return calls +} + +// ResetGpuLockedClocks calls ResetGpuLockedClocksFunc. +func (mock *Device) ResetGpuLockedClocks() nvml.Return { + if mock.ResetGpuLockedClocksFunc == nil { + panic("Device.ResetGpuLockedClocksFunc: method is nil but Device.ResetGpuLockedClocks was just called") + } + callInfo := struct { + }{} + mock.lockResetGpuLockedClocks.Lock() + mock.calls.ResetGpuLockedClocks = append(mock.calls.ResetGpuLockedClocks, callInfo) + mock.lockResetGpuLockedClocks.Unlock() + return mock.ResetGpuLockedClocksFunc() +} + +// ResetGpuLockedClocksCalls gets all the calls that were made to ResetGpuLockedClocks. +// Check the length with: +// +// len(mockedDevice.ResetGpuLockedClocksCalls()) +func (mock *Device) ResetGpuLockedClocksCalls() []struct { +} { + var calls []struct { + } + mock.lockResetGpuLockedClocks.RLock() + calls = mock.calls.ResetGpuLockedClocks + mock.lockResetGpuLockedClocks.RUnlock() + return calls +} + +// ResetMemoryLockedClocks calls ResetMemoryLockedClocksFunc. +func (mock *Device) ResetMemoryLockedClocks() nvml.Return { + if mock.ResetMemoryLockedClocksFunc == nil { + panic("Device.ResetMemoryLockedClocksFunc: method is nil but Device.ResetMemoryLockedClocks was just called") + } + callInfo := struct { + }{} + mock.lockResetMemoryLockedClocks.Lock() + mock.calls.ResetMemoryLockedClocks = append(mock.calls.ResetMemoryLockedClocks, callInfo) + mock.lockResetMemoryLockedClocks.Unlock() + return mock.ResetMemoryLockedClocksFunc() +} + +// ResetMemoryLockedClocksCalls gets all the calls that were made to ResetMemoryLockedClocks. +// Check the length with: +// +// len(mockedDevice.ResetMemoryLockedClocksCalls()) +func (mock *Device) ResetMemoryLockedClocksCalls() []struct { +} { + var calls []struct { + } + mock.lockResetMemoryLockedClocks.RLock() + calls = mock.calls.ResetMemoryLockedClocks + mock.lockResetMemoryLockedClocks.RUnlock() + return calls +} + +// ResetNvLinkErrorCounters calls ResetNvLinkErrorCountersFunc. +func (mock *Device) ResetNvLinkErrorCounters(n int) nvml.Return { + if mock.ResetNvLinkErrorCountersFunc == nil { + panic("Device.ResetNvLinkErrorCountersFunc: method is nil but Device.ResetNvLinkErrorCounters was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockResetNvLinkErrorCounters.Lock() + mock.calls.ResetNvLinkErrorCounters = append(mock.calls.ResetNvLinkErrorCounters, callInfo) + mock.lockResetNvLinkErrorCounters.Unlock() + return mock.ResetNvLinkErrorCountersFunc(n) +} + +// ResetNvLinkErrorCountersCalls gets all the calls that were made to ResetNvLinkErrorCounters. +// Check the length with: +// +// len(mockedDevice.ResetNvLinkErrorCountersCalls()) +func (mock *Device) ResetNvLinkErrorCountersCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockResetNvLinkErrorCounters.RLock() + calls = mock.calls.ResetNvLinkErrorCounters + mock.lockResetNvLinkErrorCounters.RUnlock() + return calls +} + +// ResetNvLinkUtilizationCounter calls ResetNvLinkUtilizationCounterFunc. +func (mock *Device) ResetNvLinkUtilizationCounter(n1 int, n2 int) nvml.Return { + if mock.ResetNvLinkUtilizationCounterFunc == nil { + panic("Device.ResetNvLinkUtilizationCounterFunc: method is nil but Device.ResetNvLinkUtilizationCounter was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockResetNvLinkUtilizationCounter.Lock() + mock.calls.ResetNvLinkUtilizationCounter = append(mock.calls.ResetNvLinkUtilizationCounter, callInfo) + mock.lockResetNvLinkUtilizationCounter.Unlock() + return mock.ResetNvLinkUtilizationCounterFunc(n1, n2) +} + +// ResetNvLinkUtilizationCounterCalls gets all the calls that were made to ResetNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedDevice.ResetNvLinkUtilizationCounterCalls()) +func (mock *Device) ResetNvLinkUtilizationCounterCalls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockResetNvLinkUtilizationCounter.RLock() + calls = mock.calls.ResetNvLinkUtilizationCounter + mock.lockResetNvLinkUtilizationCounter.RUnlock() + return calls +} + +// SetAPIRestriction calls SetAPIRestrictionFunc. +func (mock *Device) SetAPIRestriction(restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return { + if mock.SetAPIRestrictionFunc == nil { + panic("Device.SetAPIRestrictionFunc: method is nil but Device.SetAPIRestriction was just called") + } + callInfo := struct { + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState + }{ + RestrictedAPI: restrictedAPI, + EnableState: enableState, + } + mock.lockSetAPIRestriction.Lock() + mock.calls.SetAPIRestriction = append(mock.calls.SetAPIRestriction, callInfo) + mock.lockSetAPIRestriction.Unlock() + return mock.SetAPIRestrictionFunc(restrictedAPI, enableState) +} + +// SetAPIRestrictionCalls gets all the calls that were made to SetAPIRestriction. +// Check the length with: +// +// len(mockedDevice.SetAPIRestrictionCalls()) +func (mock *Device) SetAPIRestrictionCalls() []struct { + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState +} { + var calls []struct { + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState + } + mock.lockSetAPIRestriction.RLock() + calls = mock.calls.SetAPIRestriction + mock.lockSetAPIRestriction.RUnlock() + return calls +} + +// SetAccountingMode calls SetAccountingModeFunc. +func (mock *Device) SetAccountingMode(enableState nvml.EnableState) nvml.Return { + if mock.SetAccountingModeFunc == nil { + panic("Device.SetAccountingModeFunc: method is nil but Device.SetAccountingMode was just called") + } + callInfo := struct { + EnableState nvml.EnableState + }{ + EnableState: enableState, + } + mock.lockSetAccountingMode.Lock() + mock.calls.SetAccountingMode = append(mock.calls.SetAccountingMode, callInfo) + mock.lockSetAccountingMode.Unlock() + return mock.SetAccountingModeFunc(enableState) +} + +// SetAccountingModeCalls gets all the calls that were made to SetAccountingMode. +// Check the length with: +// +// len(mockedDevice.SetAccountingModeCalls()) +func (mock *Device) SetAccountingModeCalls() []struct { + EnableState nvml.EnableState +} { + var calls []struct { + EnableState nvml.EnableState + } + mock.lockSetAccountingMode.RLock() + calls = mock.calls.SetAccountingMode + mock.lockSetAccountingMode.RUnlock() + return calls +} + +// SetApplicationsClocks calls SetApplicationsClocksFunc. +func (mock *Device) SetApplicationsClocks(v1 uint32, v2 uint32) nvml.Return { + if mock.SetApplicationsClocksFunc == nil { + panic("Device.SetApplicationsClocksFunc: method is nil but Device.SetApplicationsClocks was just called") + } + callInfo := struct { + V1 uint32 + V2 uint32 + }{ + V1: v1, + V2: v2, + } + mock.lockSetApplicationsClocks.Lock() + mock.calls.SetApplicationsClocks = append(mock.calls.SetApplicationsClocks, callInfo) + mock.lockSetApplicationsClocks.Unlock() + return mock.SetApplicationsClocksFunc(v1, v2) +} + +// SetApplicationsClocksCalls gets all the calls that were made to SetApplicationsClocks. +// Check the length with: +// +// len(mockedDevice.SetApplicationsClocksCalls()) +func (mock *Device) SetApplicationsClocksCalls() []struct { + V1 uint32 + V2 uint32 +} { + var calls []struct { + V1 uint32 + V2 uint32 + } + mock.lockSetApplicationsClocks.RLock() + calls = mock.calls.SetApplicationsClocks + mock.lockSetApplicationsClocks.RUnlock() + return calls +} + +// SetAutoBoostedClocksEnabled calls SetAutoBoostedClocksEnabledFunc. +func (mock *Device) SetAutoBoostedClocksEnabled(enableState nvml.EnableState) nvml.Return { + if mock.SetAutoBoostedClocksEnabledFunc == nil { + panic("Device.SetAutoBoostedClocksEnabledFunc: method is nil but Device.SetAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + EnableState nvml.EnableState + }{ + EnableState: enableState, + } + mock.lockSetAutoBoostedClocksEnabled.Lock() + mock.calls.SetAutoBoostedClocksEnabled = append(mock.calls.SetAutoBoostedClocksEnabled, callInfo) + mock.lockSetAutoBoostedClocksEnabled.Unlock() + return mock.SetAutoBoostedClocksEnabledFunc(enableState) +} + +// SetAutoBoostedClocksEnabledCalls gets all the calls that were made to SetAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedDevice.SetAutoBoostedClocksEnabledCalls()) +func (mock *Device) SetAutoBoostedClocksEnabledCalls() []struct { + EnableState nvml.EnableState +} { + var calls []struct { + EnableState nvml.EnableState + } + mock.lockSetAutoBoostedClocksEnabled.RLock() + calls = mock.calls.SetAutoBoostedClocksEnabled + mock.lockSetAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// SetClockOffsets calls SetClockOffsetsFunc. +func (mock *Device) SetClockOffsets(clockOffset nvml.ClockOffset) nvml.Return { + if mock.SetClockOffsetsFunc == nil { + panic("Device.SetClockOffsetsFunc: method is nil but Device.SetClockOffsets was just called") + } + callInfo := struct { + ClockOffset nvml.ClockOffset + }{ + ClockOffset: clockOffset, + } + mock.lockSetClockOffsets.Lock() + mock.calls.SetClockOffsets = append(mock.calls.SetClockOffsets, callInfo) + mock.lockSetClockOffsets.Unlock() + return mock.SetClockOffsetsFunc(clockOffset) +} + +// SetClockOffsetsCalls gets all the calls that were made to SetClockOffsets. +// Check the length with: +// +// len(mockedDevice.SetClockOffsetsCalls()) +func (mock *Device) SetClockOffsetsCalls() []struct { + ClockOffset nvml.ClockOffset +} { + var calls []struct { + ClockOffset nvml.ClockOffset + } + mock.lockSetClockOffsets.RLock() + calls = mock.calls.SetClockOffsets + mock.lockSetClockOffsets.RUnlock() + return calls +} + +// SetComputeMode calls SetComputeModeFunc. +func (mock *Device) SetComputeMode(computeMode nvml.ComputeMode) nvml.Return { + if mock.SetComputeModeFunc == nil { + panic("Device.SetComputeModeFunc: method is nil but Device.SetComputeMode was just called") + } + callInfo := struct { + ComputeMode nvml.ComputeMode + }{ + ComputeMode: computeMode, + } + mock.lockSetComputeMode.Lock() + mock.calls.SetComputeMode = append(mock.calls.SetComputeMode, callInfo) + mock.lockSetComputeMode.Unlock() + return mock.SetComputeModeFunc(computeMode) +} + +// SetComputeModeCalls gets all the calls that were made to SetComputeMode. +// Check the length with: +// +// len(mockedDevice.SetComputeModeCalls()) +func (mock *Device) SetComputeModeCalls() []struct { + ComputeMode nvml.ComputeMode +} { + var calls []struct { + ComputeMode nvml.ComputeMode + } + mock.lockSetComputeMode.RLock() + calls = mock.calls.SetComputeMode + mock.lockSetComputeMode.RUnlock() + return calls +} + +// SetConfComputeUnprotectedMemSize calls SetConfComputeUnprotectedMemSizeFunc. +func (mock *Device) SetConfComputeUnprotectedMemSize(v uint64) nvml.Return { + if mock.SetConfComputeUnprotectedMemSizeFunc == nil { + panic("Device.SetConfComputeUnprotectedMemSizeFunc: method is nil but Device.SetConfComputeUnprotectedMemSize was just called") + } + callInfo := struct { + V uint64 + }{ + V: v, + } + mock.lockSetConfComputeUnprotectedMemSize.Lock() + mock.calls.SetConfComputeUnprotectedMemSize = append(mock.calls.SetConfComputeUnprotectedMemSize, callInfo) + mock.lockSetConfComputeUnprotectedMemSize.Unlock() + return mock.SetConfComputeUnprotectedMemSizeFunc(v) +} + +// SetConfComputeUnprotectedMemSizeCalls gets all the calls that were made to SetConfComputeUnprotectedMemSize. +// Check the length with: +// +// len(mockedDevice.SetConfComputeUnprotectedMemSizeCalls()) +func (mock *Device) SetConfComputeUnprotectedMemSizeCalls() []struct { + V uint64 +} { + var calls []struct { + V uint64 + } + mock.lockSetConfComputeUnprotectedMemSize.RLock() + calls = mock.calls.SetConfComputeUnprotectedMemSize + mock.lockSetConfComputeUnprotectedMemSize.RUnlock() + return calls +} + +// SetCpuAffinity calls SetCpuAffinityFunc. +func (mock *Device) SetCpuAffinity() nvml.Return { + if mock.SetCpuAffinityFunc == nil { + panic("Device.SetCpuAffinityFunc: method is nil but Device.SetCpuAffinity was just called") + } + callInfo := struct { + }{} + mock.lockSetCpuAffinity.Lock() + mock.calls.SetCpuAffinity = append(mock.calls.SetCpuAffinity, callInfo) + mock.lockSetCpuAffinity.Unlock() + return mock.SetCpuAffinityFunc() +} + +// SetCpuAffinityCalls gets all the calls that were made to SetCpuAffinity. +// Check the length with: +// +// len(mockedDevice.SetCpuAffinityCalls()) +func (mock *Device) SetCpuAffinityCalls() []struct { +} { + var calls []struct { + } + mock.lockSetCpuAffinity.RLock() + calls = mock.calls.SetCpuAffinity + mock.lockSetCpuAffinity.RUnlock() + return calls +} + +// SetDefaultAutoBoostedClocksEnabled calls SetDefaultAutoBoostedClocksEnabledFunc. +func (mock *Device) SetDefaultAutoBoostedClocksEnabled(enableState nvml.EnableState, v uint32) nvml.Return { + if mock.SetDefaultAutoBoostedClocksEnabledFunc == nil { + panic("Device.SetDefaultAutoBoostedClocksEnabledFunc: method is nil but Device.SetDefaultAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + EnableState nvml.EnableState + V uint32 + }{ + EnableState: enableState, + V: v, + } + mock.lockSetDefaultAutoBoostedClocksEnabled.Lock() + mock.calls.SetDefaultAutoBoostedClocksEnabled = append(mock.calls.SetDefaultAutoBoostedClocksEnabled, callInfo) + mock.lockSetDefaultAutoBoostedClocksEnabled.Unlock() + return mock.SetDefaultAutoBoostedClocksEnabledFunc(enableState, v) +} + +// SetDefaultAutoBoostedClocksEnabledCalls gets all the calls that were made to SetDefaultAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedDevice.SetDefaultAutoBoostedClocksEnabledCalls()) +func (mock *Device) SetDefaultAutoBoostedClocksEnabledCalls() []struct { + EnableState nvml.EnableState + V uint32 +} { + var calls []struct { + EnableState nvml.EnableState + V uint32 + } + mock.lockSetDefaultAutoBoostedClocksEnabled.RLock() + calls = mock.calls.SetDefaultAutoBoostedClocksEnabled + mock.lockSetDefaultAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// SetDefaultFanSpeed_v2 calls SetDefaultFanSpeed_v2Func. +func (mock *Device) SetDefaultFanSpeed_v2(n int) nvml.Return { + if mock.SetDefaultFanSpeed_v2Func == nil { + panic("Device.SetDefaultFanSpeed_v2Func: method is nil but Device.SetDefaultFanSpeed_v2 was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSetDefaultFanSpeed_v2.Lock() + mock.calls.SetDefaultFanSpeed_v2 = append(mock.calls.SetDefaultFanSpeed_v2, callInfo) + mock.lockSetDefaultFanSpeed_v2.Unlock() + return mock.SetDefaultFanSpeed_v2Func(n) +} + +// SetDefaultFanSpeed_v2Calls gets all the calls that were made to SetDefaultFanSpeed_v2. +// Check the length with: +// +// len(mockedDevice.SetDefaultFanSpeed_v2Calls()) +func (mock *Device) SetDefaultFanSpeed_v2Calls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSetDefaultFanSpeed_v2.RLock() + calls = mock.calls.SetDefaultFanSpeed_v2 + mock.lockSetDefaultFanSpeed_v2.RUnlock() + return calls +} + +// SetDramEncryptionMode calls SetDramEncryptionModeFunc. +func (mock *Device) SetDramEncryptionMode(dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return { + if mock.SetDramEncryptionModeFunc == nil { + panic("Device.SetDramEncryptionModeFunc: method is nil but Device.SetDramEncryptionMode was just called") + } + callInfo := struct { + DramEncryptionInfo *nvml.DramEncryptionInfo + }{ + DramEncryptionInfo: dramEncryptionInfo, + } + mock.lockSetDramEncryptionMode.Lock() + mock.calls.SetDramEncryptionMode = append(mock.calls.SetDramEncryptionMode, callInfo) + mock.lockSetDramEncryptionMode.Unlock() + return mock.SetDramEncryptionModeFunc(dramEncryptionInfo) +} + +// SetDramEncryptionModeCalls gets all the calls that were made to SetDramEncryptionMode. +// Check the length with: +// +// len(mockedDevice.SetDramEncryptionModeCalls()) +func (mock *Device) SetDramEncryptionModeCalls() []struct { + DramEncryptionInfo *nvml.DramEncryptionInfo +} { + var calls []struct { + DramEncryptionInfo *nvml.DramEncryptionInfo + } + mock.lockSetDramEncryptionMode.RLock() + calls = mock.calls.SetDramEncryptionMode + mock.lockSetDramEncryptionMode.RUnlock() + return calls +} + +// SetDriverModel calls SetDriverModelFunc. +func (mock *Device) SetDriverModel(driverModel nvml.DriverModel, v uint32) nvml.Return { + if mock.SetDriverModelFunc == nil { + panic("Device.SetDriverModelFunc: method is nil but Device.SetDriverModel was just called") + } + callInfo := struct { + DriverModel nvml.DriverModel + V uint32 + }{ + DriverModel: driverModel, + V: v, + } + mock.lockSetDriverModel.Lock() + mock.calls.SetDriverModel = append(mock.calls.SetDriverModel, callInfo) + mock.lockSetDriverModel.Unlock() + return mock.SetDriverModelFunc(driverModel, v) +} + +// SetDriverModelCalls gets all the calls that were made to SetDriverModel. +// Check the length with: +// +// len(mockedDevice.SetDriverModelCalls()) +func (mock *Device) SetDriverModelCalls() []struct { + DriverModel nvml.DriverModel + V uint32 +} { + var calls []struct { + DriverModel nvml.DriverModel + V uint32 + } + mock.lockSetDriverModel.RLock() + calls = mock.calls.SetDriverModel + mock.lockSetDriverModel.RUnlock() + return calls +} + +// SetEccMode calls SetEccModeFunc. +func (mock *Device) SetEccMode(enableState nvml.EnableState) nvml.Return { + if mock.SetEccModeFunc == nil { + panic("Device.SetEccModeFunc: method is nil but Device.SetEccMode was just called") + } + callInfo := struct { + EnableState nvml.EnableState + }{ + EnableState: enableState, + } + mock.lockSetEccMode.Lock() + mock.calls.SetEccMode = append(mock.calls.SetEccMode, callInfo) + mock.lockSetEccMode.Unlock() + return mock.SetEccModeFunc(enableState) +} + +// SetEccModeCalls gets all the calls that were made to SetEccMode. +// Check the length with: +// +// len(mockedDevice.SetEccModeCalls()) +func (mock *Device) SetEccModeCalls() []struct { + EnableState nvml.EnableState +} { + var calls []struct { + EnableState nvml.EnableState + } + mock.lockSetEccMode.RLock() + calls = mock.calls.SetEccMode + mock.lockSetEccMode.RUnlock() + return calls +} + +// SetFanControlPolicy calls SetFanControlPolicyFunc. +func (mock *Device) SetFanControlPolicy(n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return { + if mock.SetFanControlPolicyFunc == nil { + panic("Device.SetFanControlPolicyFunc: method is nil but Device.SetFanControlPolicy was just called") + } + callInfo := struct { + N int + FanControlPolicy nvml.FanControlPolicy + }{ + N: n, + FanControlPolicy: fanControlPolicy, + } + mock.lockSetFanControlPolicy.Lock() + mock.calls.SetFanControlPolicy = append(mock.calls.SetFanControlPolicy, callInfo) + mock.lockSetFanControlPolicy.Unlock() + return mock.SetFanControlPolicyFunc(n, fanControlPolicy) +} + +// SetFanControlPolicyCalls gets all the calls that were made to SetFanControlPolicy. +// Check the length with: +// +// len(mockedDevice.SetFanControlPolicyCalls()) +func (mock *Device) SetFanControlPolicyCalls() []struct { + N int + FanControlPolicy nvml.FanControlPolicy +} { + var calls []struct { + N int + FanControlPolicy nvml.FanControlPolicy + } + mock.lockSetFanControlPolicy.RLock() + calls = mock.calls.SetFanControlPolicy + mock.lockSetFanControlPolicy.RUnlock() + return calls +} + +// SetFanSpeed_v2 calls SetFanSpeed_v2Func. +func (mock *Device) SetFanSpeed_v2(n1 int, n2 int) nvml.Return { + if mock.SetFanSpeed_v2Func == nil { + panic("Device.SetFanSpeed_v2Func: method is nil but Device.SetFanSpeed_v2 was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockSetFanSpeed_v2.Lock() + mock.calls.SetFanSpeed_v2 = append(mock.calls.SetFanSpeed_v2, callInfo) + mock.lockSetFanSpeed_v2.Unlock() + return mock.SetFanSpeed_v2Func(n1, n2) +} + +// SetFanSpeed_v2Calls gets all the calls that were made to SetFanSpeed_v2. +// Check the length with: +// +// len(mockedDevice.SetFanSpeed_v2Calls()) +func (mock *Device) SetFanSpeed_v2Calls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockSetFanSpeed_v2.RLock() + calls = mock.calls.SetFanSpeed_v2 + mock.lockSetFanSpeed_v2.RUnlock() + return calls +} + +// SetGpcClkVfOffset calls SetGpcClkVfOffsetFunc. +func (mock *Device) SetGpcClkVfOffset(n int) nvml.Return { + if mock.SetGpcClkVfOffsetFunc == nil { + panic("Device.SetGpcClkVfOffsetFunc: method is nil but Device.SetGpcClkVfOffset was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSetGpcClkVfOffset.Lock() + mock.calls.SetGpcClkVfOffset = append(mock.calls.SetGpcClkVfOffset, callInfo) + mock.lockSetGpcClkVfOffset.Unlock() + return mock.SetGpcClkVfOffsetFunc(n) +} + +// SetGpcClkVfOffsetCalls gets all the calls that were made to SetGpcClkVfOffset. +// Check the length with: +// +// len(mockedDevice.SetGpcClkVfOffsetCalls()) +func (mock *Device) SetGpcClkVfOffsetCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSetGpcClkVfOffset.RLock() + calls = mock.calls.SetGpcClkVfOffset + mock.lockSetGpcClkVfOffset.RUnlock() + return calls +} + +// SetGpuLockedClocks calls SetGpuLockedClocksFunc. +func (mock *Device) SetGpuLockedClocks(v1 uint32, v2 uint32) nvml.Return { + if mock.SetGpuLockedClocksFunc == nil { + panic("Device.SetGpuLockedClocksFunc: method is nil but Device.SetGpuLockedClocks was just called") + } + callInfo := struct { + V1 uint32 + V2 uint32 + }{ + V1: v1, + V2: v2, + } + mock.lockSetGpuLockedClocks.Lock() + mock.calls.SetGpuLockedClocks = append(mock.calls.SetGpuLockedClocks, callInfo) + mock.lockSetGpuLockedClocks.Unlock() + return mock.SetGpuLockedClocksFunc(v1, v2) +} + +// SetGpuLockedClocksCalls gets all the calls that were made to SetGpuLockedClocks. +// Check the length with: +// +// len(mockedDevice.SetGpuLockedClocksCalls()) +func (mock *Device) SetGpuLockedClocksCalls() []struct { + V1 uint32 + V2 uint32 +} { + var calls []struct { + V1 uint32 + V2 uint32 + } + mock.lockSetGpuLockedClocks.RLock() + calls = mock.calls.SetGpuLockedClocks + mock.lockSetGpuLockedClocks.RUnlock() + return calls +} + +// SetGpuOperationMode calls SetGpuOperationModeFunc. +func (mock *Device) SetGpuOperationMode(gpuOperationMode nvml.GpuOperationMode) nvml.Return { + if mock.SetGpuOperationModeFunc == nil { + panic("Device.SetGpuOperationModeFunc: method is nil but Device.SetGpuOperationMode was just called") + } + callInfo := struct { + GpuOperationMode nvml.GpuOperationMode + }{ + GpuOperationMode: gpuOperationMode, + } + mock.lockSetGpuOperationMode.Lock() + mock.calls.SetGpuOperationMode = append(mock.calls.SetGpuOperationMode, callInfo) + mock.lockSetGpuOperationMode.Unlock() + return mock.SetGpuOperationModeFunc(gpuOperationMode) +} + +// SetGpuOperationModeCalls gets all the calls that were made to SetGpuOperationMode. +// Check the length with: +// +// len(mockedDevice.SetGpuOperationModeCalls()) +func (mock *Device) SetGpuOperationModeCalls() []struct { + GpuOperationMode nvml.GpuOperationMode +} { + var calls []struct { + GpuOperationMode nvml.GpuOperationMode + } + mock.lockSetGpuOperationMode.RLock() + calls = mock.calls.SetGpuOperationMode + mock.lockSetGpuOperationMode.RUnlock() + return calls +} + +// SetMemClkVfOffset calls SetMemClkVfOffsetFunc. +func (mock *Device) SetMemClkVfOffset(n int) nvml.Return { + if mock.SetMemClkVfOffsetFunc == nil { + panic("Device.SetMemClkVfOffsetFunc: method is nil but Device.SetMemClkVfOffset was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSetMemClkVfOffset.Lock() + mock.calls.SetMemClkVfOffset = append(mock.calls.SetMemClkVfOffset, callInfo) + mock.lockSetMemClkVfOffset.Unlock() + return mock.SetMemClkVfOffsetFunc(n) +} + +// SetMemClkVfOffsetCalls gets all the calls that were made to SetMemClkVfOffset. +// Check the length with: +// +// len(mockedDevice.SetMemClkVfOffsetCalls()) +func (mock *Device) SetMemClkVfOffsetCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSetMemClkVfOffset.RLock() + calls = mock.calls.SetMemClkVfOffset + mock.lockSetMemClkVfOffset.RUnlock() + return calls +} + +// SetMemoryLockedClocks calls SetMemoryLockedClocksFunc. +func (mock *Device) SetMemoryLockedClocks(v1 uint32, v2 uint32) nvml.Return { + if mock.SetMemoryLockedClocksFunc == nil { + panic("Device.SetMemoryLockedClocksFunc: method is nil but Device.SetMemoryLockedClocks was just called") + } + callInfo := struct { + V1 uint32 + V2 uint32 + }{ + V1: v1, + V2: v2, + } + mock.lockSetMemoryLockedClocks.Lock() + mock.calls.SetMemoryLockedClocks = append(mock.calls.SetMemoryLockedClocks, callInfo) + mock.lockSetMemoryLockedClocks.Unlock() + return mock.SetMemoryLockedClocksFunc(v1, v2) +} + +// SetMemoryLockedClocksCalls gets all the calls that were made to SetMemoryLockedClocks. +// Check the length with: +// +// len(mockedDevice.SetMemoryLockedClocksCalls()) +func (mock *Device) SetMemoryLockedClocksCalls() []struct { + V1 uint32 + V2 uint32 +} { + var calls []struct { + V1 uint32 + V2 uint32 + } + mock.lockSetMemoryLockedClocks.RLock() + calls = mock.calls.SetMemoryLockedClocks + mock.lockSetMemoryLockedClocks.RUnlock() + return calls +} + +// SetMigMode calls SetMigModeFunc. +func (mock *Device) SetMigMode(n int) (nvml.Return, nvml.Return) { + if mock.SetMigModeFunc == nil { + panic("Device.SetMigModeFunc: method is nil but Device.SetMigMode was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSetMigMode.Lock() + mock.calls.SetMigMode = append(mock.calls.SetMigMode, callInfo) + mock.lockSetMigMode.Unlock() + return mock.SetMigModeFunc(n) +} + +// SetMigModeCalls gets all the calls that were made to SetMigMode. +// Check the length with: +// +// len(mockedDevice.SetMigModeCalls()) +func (mock *Device) SetMigModeCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSetMigMode.RLock() + calls = mock.calls.SetMigMode + mock.lockSetMigMode.RUnlock() + return calls +} + +// SetNvLinkDeviceLowPowerThreshold calls SetNvLinkDeviceLowPowerThresholdFunc. +func (mock *Device) SetNvLinkDeviceLowPowerThreshold(nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return { + if mock.SetNvLinkDeviceLowPowerThresholdFunc == nil { + panic("Device.SetNvLinkDeviceLowPowerThresholdFunc: method is nil but Device.SetNvLinkDeviceLowPowerThreshold was just called") + } + callInfo := struct { + NvLinkPowerThres *nvml.NvLinkPowerThres + }{ + NvLinkPowerThres: nvLinkPowerThres, + } + mock.lockSetNvLinkDeviceLowPowerThreshold.Lock() + mock.calls.SetNvLinkDeviceLowPowerThreshold = append(mock.calls.SetNvLinkDeviceLowPowerThreshold, callInfo) + mock.lockSetNvLinkDeviceLowPowerThreshold.Unlock() + return mock.SetNvLinkDeviceLowPowerThresholdFunc(nvLinkPowerThres) +} + +// SetNvLinkDeviceLowPowerThresholdCalls gets all the calls that were made to SetNvLinkDeviceLowPowerThreshold. +// Check the length with: +// +// len(mockedDevice.SetNvLinkDeviceLowPowerThresholdCalls()) +func (mock *Device) SetNvLinkDeviceLowPowerThresholdCalls() []struct { + NvLinkPowerThres *nvml.NvLinkPowerThres +} { + var calls []struct { + NvLinkPowerThres *nvml.NvLinkPowerThres + } + mock.lockSetNvLinkDeviceLowPowerThreshold.RLock() + calls = mock.calls.SetNvLinkDeviceLowPowerThreshold + mock.lockSetNvLinkDeviceLowPowerThreshold.RUnlock() + return calls +} + +// SetNvLinkUtilizationControl calls SetNvLinkUtilizationControlFunc. +func (mock *Device) SetNvLinkUtilizationControl(n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return { + if mock.SetNvLinkUtilizationControlFunc == nil { + panic("Device.SetNvLinkUtilizationControlFunc: method is nil but Device.SetNvLinkUtilizationControl was just called") + } + callInfo := struct { + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool + }{ + N1: n1, + N2: n2, + NvLinkUtilizationControl: nvLinkUtilizationControl, + B: b, + } + mock.lockSetNvLinkUtilizationControl.Lock() + mock.calls.SetNvLinkUtilizationControl = append(mock.calls.SetNvLinkUtilizationControl, callInfo) + mock.lockSetNvLinkUtilizationControl.Unlock() + return mock.SetNvLinkUtilizationControlFunc(n1, n2, nvLinkUtilizationControl, b) +} + +// SetNvLinkUtilizationControlCalls gets all the calls that were made to SetNvLinkUtilizationControl. +// Check the length with: +// +// len(mockedDevice.SetNvLinkUtilizationControlCalls()) +func (mock *Device) SetNvLinkUtilizationControlCalls() []struct { + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool +} { + var calls []struct { + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool + } + mock.lockSetNvLinkUtilizationControl.RLock() + calls = mock.calls.SetNvLinkUtilizationControl + mock.lockSetNvLinkUtilizationControl.RUnlock() + return calls +} + +// SetNvlinkBwMode calls SetNvlinkBwModeFunc. +func (mock *Device) SetNvlinkBwMode(nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return { + if mock.SetNvlinkBwModeFunc == nil { + panic("Device.SetNvlinkBwModeFunc: method is nil but Device.SetNvlinkBwMode was just called") + } + callInfo := struct { + NvlinkSetBwMode *nvml.NvlinkSetBwMode + }{ + NvlinkSetBwMode: nvlinkSetBwMode, + } + mock.lockSetNvlinkBwMode.Lock() + mock.calls.SetNvlinkBwMode = append(mock.calls.SetNvlinkBwMode, callInfo) + mock.lockSetNvlinkBwMode.Unlock() + return mock.SetNvlinkBwModeFunc(nvlinkSetBwMode) +} + +// SetNvlinkBwModeCalls gets all the calls that were made to SetNvlinkBwMode. +// Check the length with: +// +// len(mockedDevice.SetNvlinkBwModeCalls()) +func (mock *Device) SetNvlinkBwModeCalls() []struct { + NvlinkSetBwMode *nvml.NvlinkSetBwMode +} { + var calls []struct { + NvlinkSetBwMode *nvml.NvlinkSetBwMode + } + mock.lockSetNvlinkBwMode.RLock() + calls = mock.calls.SetNvlinkBwMode + mock.lockSetNvlinkBwMode.RUnlock() + return calls +} + +// SetPersistenceMode calls SetPersistenceModeFunc. +func (mock *Device) SetPersistenceMode(enableState nvml.EnableState) nvml.Return { + if mock.SetPersistenceModeFunc == nil { + panic("Device.SetPersistenceModeFunc: method is nil but Device.SetPersistenceMode was just called") + } + callInfo := struct { + EnableState nvml.EnableState + }{ + EnableState: enableState, + } + mock.lockSetPersistenceMode.Lock() + mock.calls.SetPersistenceMode = append(mock.calls.SetPersistenceMode, callInfo) + mock.lockSetPersistenceMode.Unlock() + return mock.SetPersistenceModeFunc(enableState) +} + +// SetPersistenceModeCalls gets all the calls that were made to SetPersistenceMode. +// Check the length with: +// +// len(mockedDevice.SetPersistenceModeCalls()) +func (mock *Device) SetPersistenceModeCalls() []struct { + EnableState nvml.EnableState +} { + var calls []struct { + EnableState nvml.EnableState + } + mock.lockSetPersistenceMode.RLock() + calls = mock.calls.SetPersistenceMode + mock.lockSetPersistenceMode.RUnlock() + return calls +} + +// SetPowerManagementLimit calls SetPowerManagementLimitFunc. +func (mock *Device) SetPowerManagementLimit(v uint32) nvml.Return { + if mock.SetPowerManagementLimitFunc == nil { + panic("Device.SetPowerManagementLimitFunc: method is nil but Device.SetPowerManagementLimit was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockSetPowerManagementLimit.Lock() + mock.calls.SetPowerManagementLimit = append(mock.calls.SetPowerManagementLimit, callInfo) + mock.lockSetPowerManagementLimit.Unlock() + return mock.SetPowerManagementLimitFunc(v) +} + +// SetPowerManagementLimitCalls gets all the calls that were made to SetPowerManagementLimit. +// Check the length with: +// +// len(mockedDevice.SetPowerManagementLimitCalls()) +func (mock *Device) SetPowerManagementLimitCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockSetPowerManagementLimit.RLock() + calls = mock.calls.SetPowerManagementLimit + mock.lockSetPowerManagementLimit.RUnlock() + return calls +} + +// SetPowerManagementLimit_v2 calls SetPowerManagementLimit_v2Func. +func (mock *Device) SetPowerManagementLimit_v2(powerValue_v2 *nvml.PowerValue_v2) nvml.Return { + if mock.SetPowerManagementLimit_v2Func == nil { + panic("Device.SetPowerManagementLimit_v2Func: method is nil but Device.SetPowerManagementLimit_v2 was just called") + } + callInfo := struct { + PowerValue_v2 *nvml.PowerValue_v2 + }{ + PowerValue_v2: powerValue_v2, + } + mock.lockSetPowerManagementLimit_v2.Lock() + mock.calls.SetPowerManagementLimit_v2 = append(mock.calls.SetPowerManagementLimit_v2, callInfo) + mock.lockSetPowerManagementLimit_v2.Unlock() + return mock.SetPowerManagementLimit_v2Func(powerValue_v2) +} + +// SetPowerManagementLimit_v2Calls gets all the calls that were made to SetPowerManagementLimit_v2. +// Check the length with: +// +// len(mockedDevice.SetPowerManagementLimit_v2Calls()) +func (mock *Device) SetPowerManagementLimit_v2Calls() []struct { + PowerValue_v2 *nvml.PowerValue_v2 +} { + var calls []struct { + PowerValue_v2 *nvml.PowerValue_v2 + } + mock.lockSetPowerManagementLimit_v2.RLock() + calls = mock.calls.SetPowerManagementLimit_v2 + mock.lockSetPowerManagementLimit_v2.RUnlock() + return calls +} + +// SetTemperatureThreshold calls SetTemperatureThresholdFunc. +func (mock *Device) SetTemperatureThreshold(temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return { + if mock.SetTemperatureThresholdFunc == nil { + panic("Device.SetTemperatureThresholdFunc: method is nil but Device.SetTemperatureThreshold was just called") + } + callInfo := struct { + TemperatureThresholds nvml.TemperatureThresholds + N int + }{ + TemperatureThresholds: temperatureThresholds, + N: n, + } + mock.lockSetTemperatureThreshold.Lock() + mock.calls.SetTemperatureThreshold = append(mock.calls.SetTemperatureThreshold, callInfo) + mock.lockSetTemperatureThreshold.Unlock() + return mock.SetTemperatureThresholdFunc(temperatureThresholds, n) +} + +// SetTemperatureThresholdCalls gets all the calls that were made to SetTemperatureThreshold. +// Check the length with: +// +// len(mockedDevice.SetTemperatureThresholdCalls()) +func (mock *Device) SetTemperatureThresholdCalls() []struct { + TemperatureThresholds nvml.TemperatureThresholds + N int +} { + var calls []struct { + TemperatureThresholds nvml.TemperatureThresholds + N int + } + mock.lockSetTemperatureThreshold.RLock() + calls = mock.calls.SetTemperatureThreshold + mock.lockSetTemperatureThreshold.RUnlock() + return calls +} + +// SetVgpuCapabilities calls SetVgpuCapabilitiesFunc. +func (mock *Device) SetVgpuCapabilities(deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return { + if mock.SetVgpuCapabilitiesFunc == nil { + panic("Device.SetVgpuCapabilitiesFunc: method is nil but Device.SetVgpuCapabilities was just called") + } + callInfo := struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState + }{ + DeviceVgpuCapability: deviceVgpuCapability, + EnableState: enableState, + } + mock.lockSetVgpuCapabilities.Lock() + mock.calls.SetVgpuCapabilities = append(mock.calls.SetVgpuCapabilities, callInfo) + mock.lockSetVgpuCapabilities.Unlock() + return mock.SetVgpuCapabilitiesFunc(deviceVgpuCapability, enableState) +} + +// SetVgpuCapabilitiesCalls gets all the calls that were made to SetVgpuCapabilities. +// Check the length with: +// +// len(mockedDevice.SetVgpuCapabilitiesCalls()) +func (mock *Device) SetVgpuCapabilitiesCalls() []struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState +} { + var calls []struct { + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState + } + mock.lockSetVgpuCapabilities.RLock() + calls = mock.calls.SetVgpuCapabilities + mock.lockSetVgpuCapabilities.RUnlock() + return calls +} + +// SetVgpuHeterogeneousMode calls SetVgpuHeterogeneousModeFunc. +func (mock *Device) SetVgpuHeterogeneousMode(vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return { + if mock.SetVgpuHeterogeneousModeFunc == nil { + panic("Device.SetVgpuHeterogeneousModeFunc: method is nil but Device.SetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + }{ + VgpuHeterogeneousMode: vgpuHeterogeneousMode, + } + mock.lockSetVgpuHeterogeneousMode.Lock() + mock.calls.SetVgpuHeterogeneousMode = append(mock.calls.SetVgpuHeterogeneousMode, callInfo) + mock.lockSetVgpuHeterogeneousMode.Unlock() + return mock.SetVgpuHeterogeneousModeFunc(vgpuHeterogeneousMode) +} + +// SetVgpuHeterogeneousModeCalls gets all the calls that were made to SetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedDevice.SetVgpuHeterogeneousModeCalls()) +func (mock *Device) SetVgpuHeterogeneousModeCalls() []struct { + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode +} { + var calls []struct { + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + } + mock.lockSetVgpuHeterogeneousMode.RLock() + calls = mock.calls.SetVgpuHeterogeneousMode + mock.lockSetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// SetVgpuSchedulerState calls SetVgpuSchedulerStateFunc. +func (mock *Device) SetVgpuSchedulerState(vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return { + if mock.SetVgpuSchedulerStateFunc == nil { + panic("Device.SetVgpuSchedulerStateFunc: method is nil but Device.SetVgpuSchedulerState was just called") + } + callInfo := struct { + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + }{ + VgpuSchedulerSetState: vgpuSchedulerSetState, + } + mock.lockSetVgpuSchedulerState.Lock() + mock.calls.SetVgpuSchedulerState = append(mock.calls.SetVgpuSchedulerState, callInfo) + mock.lockSetVgpuSchedulerState.Unlock() + return mock.SetVgpuSchedulerStateFunc(vgpuSchedulerSetState) +} + +// SetVgpuSchedulerStateCalls gets all the calls that were made to SetVgpuSchedulerState. +// Check the length with: +// +// len(mockedDevice.SetVgpuSchedulerStateCalls()) +func (mock *Device) SetVgpuSchedulerStateCalls() []struct { + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState +} { + var calls []struct { + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + } + mock.lockSetVgpuSchedulerState.RLock() + calls = mock.calls.SetVgpuSchedulerState + mock.lockSetVgpuSchedulerState.RUnlock() + return calls +} + +// SetVirtualizationMode calls SetVirtualizationModeFunc. +func (mock *Device) SetVirtualizationMode(gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return { + if mock.SetVirtualizationModeFunc == nil { + panic("Device.SetVirtualizationModeFunc: method is nil but Device.SetVirtualizationMode was just called") + } + callInfo := struct { + GpuVirtualizationMode nvml.GpuVirtualizationMode + }{ + GpuVirtualizationMode: gpuVirtualizationMode, + } + mock.lockSetVirtualizationMode.Lock() + mock.calls.SetVirtualizationMode = append(mock.calls.SetVirtualizationMode, callInfo) + mock.lockSetVirtualizationMode.Unlock() + return mock.SetVirtualizationModeFunc(gpuVirtualizationMode) +} + +// SetVirtualizationModeCalls gets all the calls that were made to SetVirtualizationMode. +// Check the length with: +// +// len(mockedDevice.SetVirtualizationModeCalls()) +func (mock *Device) SetVirtualizationModeCalls() []struct { + GpuVirtualizationMode nvml.GpuVirtualizationMode +} { + var calls []struct { + GpuVirtualizationMode nvml.GpuVirtualizationMode + } + mock.lockSetVirtualizationMode.RLock() + calls = mock.calls.SetVirtualizationMode + mock.lockSetVirtualizationMode.RUnlock() + return calls +} + +// ValidateInforom calls ValidateInforomFunc. +func (mock *Device) ValidateInforom() nvml.Return { + if mock.ValidateInforomFunc == nil { + panic("Device.ValidateInforomFunc: method is nil but Device.ValidateInforom was just called") + } + callInfo := struct { + }{} + mock.lockValidateInforom.Lock() + mock.calls.ValidateInforom = append(mock.calls.ValidateInforom, callInfo) + mock.lockValidateInforom.Unlock() + return mock.ValidateInforomFunc() +} + +// ValidateInforomCalls gets all the calls that were made to ValidateInforom. +// Check the length with: +// +// len(mockedDevice.ValidateInforomCalls()) +func (mock *Device) ValidateInforomCalls() []struct { +} { + var calls []struct { + } + mock.lockValidateInforom.RLock() + calls = mock.calls.ValidateInforom + mock.lockValidateInforom.RUnlock() + return calls +} + +// VgpuTypeGetMaxInstances calls VgpuTypeGetMaxInstancesFunc. +func (mock *Device) VgpuTypeGetMaxInstances(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { + if mock.VgpuTypeGetMaxInstancesFunc == nil { + panic("Device.VgpuTypeGetMaxInstancesFunc: method is nil but Device.VgpuTypeGetMaxInstances was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetMaxInstances.Lock() + mock.calls.VgpuTypeGetMaxInstances = append(mock.calls.VgpuTypeGetMaxInstances, callInfo) + mock.lockVgpuTypeGetMaxInstances.Unlock() + return mock.VgpuTypeGetMaxInstancesFunc(vgpuTypeId) +} + +// VgpuTypeGetMaxInstancesCalls gets all the calls that were made to VgpuTypeGetMaxInstances. +// Check the length with: +// +// len(mockedDevice.VgpuTypeGetMaxInstancesCalls()) +func (mock *Device) VgpuTypeGetMaxInstancesCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetMaxInstances.RLock() + calls = mock.calls.VgpuTypeGetMaxInstances + mock.lockVgpuTypeGetMaxInstances.RUnlock() + return calls +} + +// WorkloadPowerProfileClearRequestedProfiles calls WorkloadPowerProfileClearRequestedProfilesFunc. +func (mock *Device) WorkloadPowerProfileClearRequestedProfiles(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { + if mock.WorkloadPowerProfileClearRequestedProfilesFunc == nil { + panic("Device.WorkloadPowerProfileClearRequestedProfilesFunc: method is nil but Device.WorkloadPowerProfileClearRequestedProfiles was just called") + } + callInfo := struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + }{ + WorkloadPowerProfileRequestedProfiles: workloadPowerProfileRequestedProfiles, + } + mock.lockWorkloadPowerProfileClearRequestedProfiles.Lock() + mock.calls.WorkloadPowerProfileClearRequestedProfiles = append(mock.calls.WorkloadPowerProfileClearRequestedProfiles, callInfo) + mock.lockWorkloadPowerProfileClearRequestedProfiles.Unlock() + return mock.WorkloadPowerProfileClearRequestedProfilesFunc(workloadPowerProfileRequestedProfiles) +} + +// WorkloadPowerProfileClearRequestedProfilesCalls gets all the calls that were made to WorkloadPowerProfileClearRequestedProfiles. +// Check the length with: +// +// len(mockedDevice.WorkloadPowerProfileClearRequestedProfilesCalls()) +func (mock *Device) WorkloadPowerProfileClearRequestedProfilesCalls() []struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles +} { + var calls []struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + mock.lockWorkloadPowerProfileClearRequestedProfiles.RLock() + calls = mock.calls.WorkloadPowerProfileClearRequestedProfiles + mock.lockWorkloadPowerProfileClearRequestedProfiles.RUnlock() + return calls +} + +// WorkloadPowerProfileGetCurrentProfiles calls WorkloadPowerProfileGetCurrentProfilesFunc. +func (mock *Device) WorkloadPowerProfileGetCurrentProfiles() (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) { + if mock.WorkloadPowerProfileGetCurrentProfilesFunc == nil { + panic("Device.WorkloadPowerProfileGetCurrentProfilesFunc: method is nil but Device.WorkloadPowerProfileGetCurrentProfiles was just called") + } + callInfo := struct { + }{} + mock.lockWorkloadPowerProfileGetCurrentProfiles.Lock() + mock.calls.WorkloadPowerProfileGetCurrentProfiles = append(mock.calls.WorkloadPowerProfileGetCurrentProfiles, callInfo) + mock.lockWorkloadPowerProfileGetCurrentProfiles.Unlock() + return mock.WorkloadPowerProfileGetCurrentProfilesFunc() +} + +// WorkloadPowerProfileGetCurrentProfilesCalls gets all the calls that were made to WorkloadPowerProfileGetCurrentProfiles. +// Check the length with: +// +// len(mockedDevice.WorkloadPowerProfileGetCurrentProfilesCalls()) +func (mock *Device) WorkloadPowerProfileGetCurrentProfilesCalls() []struct { +} { + var calls []struct { + } + mock.lockWorkloadPowerProfileGetCurrentProfiles.RLock() + calls = mock.calls.WorkloadPowerProfileGetCurrentProfiles + mock.lockWorkloadPowerProfileGetCurrentProfiles.RUnlock() + return calls +} + +// WorkloadPowerProfileGetProfilesInfo calls WorkloadPowerProfileGetProfilesInfoFunc. +func (mock *Device) WorkloadPowerProfileGetProfilesInfo() (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) { + if mock.WorkloadPowerProfileGetProfilesInfoFunc == nil { + panic("Device.WorkloadPowerProfileGetProfilesInfoFunc: method is nil but Device.WorkloadPowerProfileGetProfilesInfo was just called") + } + callInfo := struct { + }{} + mock.lockWorkloadPowerProfileGetProfilesInfo.Lock() + mock.calls.WorkloadPowerProfileGetProfilesInfo = append(mock.calls.WorkloadPowerProfileGetProfilesInfo, callInfo) + mock.lockWorkloadPowerProfileGetProfilesInfo.Unlock() + return mock.WorkloadPowerProfileGetProfilesInfoFunc() +} + +// WorkloadPowerProfileGetProfilesInfoCalls gets all the calls that were made to WorkloadPowerProfileGetProfilesInfo. +// Check the length with: +// +// len(mockedDevice.WorkloadPowerProfileGetProfilesInfoCalls()) +func (mock *Device) WorkloadPowerProfileGetProfilesInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockWorkloadPowerProfileGetProfilesInfo.RLock() + calls = mock.calls.WorkloadPowerProfileGetProfilesInfo + mock.lockWorkloadPowerProfileGetProfilesInfo.RUnlock() + return calls +} + +// WorkloadPowerProfileSetRequestedProfiles calls WorkloadPowerProfileSetRequestedProfilesFunc. +func (mock *Device) WorkloadPowerProfileSetRequestedProfiles(workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { + if mock.WorkloadPowerProfileSetRequestedProfilesFunc == nil { + panic("Device.WorkloadPowerProfileSetRequestedProfilesFunc: method is nil but Device.WorkloadPowerProfileSetRequestedProfiles was just called") + } + callInfo := struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + }{ + WorkloadPowerProfileRequestedProfiles: workloadPowerProfileRequestedProfiles, + } + mock.lockWorkloadPowerProfileSetRequestedProfiles.Lock() + mock.calls.WorkloadPowerProfileSetRequestedProfiles = append(mock.calls.WorkloadPowerProfileSetRequestedProfiles, callInfo) + mock.lockWorkloadPowerProfileSetRequestedProfiles.Unlock() + return mock.WorkloadPowerProfileSetRequestedProfilesFunc(workloadPowerProfileRequestedProfiles) +} + +// WorkloadPowerProfileSetRequestedProfilesCalls gets all the calls that were made to WorkloadPowerProfileSetRequestedProfiles. +// Check the length with: +// +// len(mockedDevice.WorkloadPowerProfileSetRequestedProfilesCalls()) +func (mock *Device) WorkloadPowerProfileSetRequestedProfilesCalls() []struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles +} { + var calls []struct { + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + mock.lockWorkloadPowerProfileSetRequestedProfiles.RLock() + calls = mock.calls.WorkloadPowerProfileSetRequestedProfiles + mock.lockWorkloadPowerProfileSetRequestedProfiles.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/dgxa100.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/dgxa100.go new file mode 100644 index 00000000..af650370 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/dgxa100.go @@ -0,0 +1,381 @@ +/* + * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dgxa100 + +import ( + "fmt" + "sync" + + "github.com/google/uuid" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + "github.com/NVIDIA/go-nvml/pkg/nvml/mock" +) + +type Server struct { + mock.Interface + mock.ExtendedInterface + Devices [8]nvml.Device + DriverVersion string + NvmlVersion string + CudaDriverVersion int +} +type Device struct { + mock.Device + sync.RWMutex + UUID string + Name string + Brand nvml.BrandType + Architecture nvml.DeviceArchitecture + PciBusID string + Minor int + Index int + CudaComputeCapability CudaComputeCapability + MigMode int + GpuInstances map[*GpuInstance]struct{} + GpuInstanceCounter uint32 + MemoryInfo nvml.Memory +} + +type GpuInstance struct { + mock.GpuInstance + sync.RWMutex + Info nvml.GpuInstanceInfo + ComputeInstances map[*ComputeInstance]struct{} + ComputeInstanceCounter uint32 +} + +type ComputeInstance struct { + mock.ComputeInstance + Info nvml.ComputeInstanceInfo +} + +type CudaComputeCapability struct { + Major int + Minor int +} + +var _ nvml.Interface = (*Server)(nil) +var _ nvml.Device = (*Device)(nil) +var _ nvml.GpuInstance = (*GpuInstance)(nil) +var _ nvml.ComputeInstance = (*ComputeInstance)(nil) + +func New() *Server { + server := &Server{ + Devices: [8]nvml.Device{ + NewDevice(0), + NewDevice(1), + NewDevice(2), + NewDevice(3), + NewDevice(4), + NewDevice(5), + NewDevice(6), + NewDevice(7), + }, + DriverVersion: "550.54.15", + NvmlVersion: "12.550.54.15", + CudaDriverVersion: 12040, + } + server.setMockFuncs() + return server +} + +func NewDevice(index int) *Device { + device := &Device{ + UUID: "GPU-" + uuid.New().String(), + Name: "Mock NVIDIA A100-SXM4-40GB", + Brand: nvml.BRAND_NVIDIA, + Architecture: nvml.DEVICE_ARCH_AMPERE, + PciBusID: fmt.Sprintf("0000:%02x:00.0", index), + Minor: index, + Index: index, + CudaComputeCapability: CudaComputeCapability{ + Major: 8, + Minor: 0, + }, + GpuInstances: make(map[*GpuInstance]struct{}), + GpuInstanceCounter: 0, + MemoryInfo: nvml.Memory{Total: 42949672960, Free: 0, Used: 0}, + } + device.setMockFuncs() + return device +} + +func NewGpuInstance(info nvml.GpuInstanceInfo) *GpuInstance { + gi := &GpuInstance{ + Info: info, + ComputeInstances: make(map[*ComputeInstance]struct{}), + ComputeInstanceCounter: 0, + } + gi.setMockFuncs() + return gi +} + +func NewComputeInstance(info nvml.ComputeInstanceInfo) *ComputeInstance { + ci := &ComputeInstance{ + Info: info, + } + ci.setMockFuncs() + return ci +} + +func (s *Server) setMockFuncs() { + s.ExtensionsFunc = func() nvml.ExtendedInterface { + return s + } + + s.LookupSymbolFunc = func(symbol string) error { + return nil + } + + s.InitFunc = func() nvml.Return { + return nvml.SUCCESS + } + + s.ShutdownFunc = func() nvml.Return { + return nvml.SUCCESS + } + + s.SystemGetDriverVersionFunc = func() (string, nvml.Return) { + return s.DriverVersion, nvml.SUCCESS + } + + s.SystemGetNVMLVersionFunc = func() (string, nvml.Return) { + return s.NvmlVersion, nvml.SUCCESS + } + + s.SystemGetCudaDriverVersionFunc = func() (int, nvml.Return) { + return s.CudaDriverVersion, nvml.SUCCESS + } + + s.DeviceGetCountFunc = func() (int, nvml.Return) { + return len(s.Devices), nvml.SUCCESS + } + + s.DeviceGetHandleByIndexFunc = func(index int) (nvml.Device, nvml.Return) { + if index < 0 || index >= len(s.Devices) { + return nil, nvml.ERROR_INVALID_ARGUMENT + } + return s.Devices[index], nvml.SUCCESS + } + + s.DeviceGetHandleByUUIDFunc = func(uuid string) (nvml.Device, nvml.Return) { + for _, d := range s.Devices { + if uuid == d.(*Device).UUID { + return d, nvml.SUCCESS + } + } + return nil, nvml.ERROR_INVALID_ARGUMENT + } + + s.DeviceGetHandleByPciBusIdFunc = func(busID string) (nvml.Device, nvml.Return) { + for _, d := range s.Devices { + if busID == d.(*Device).PciBusID { + return d, nvml.SUCCESS + } + } + return nil, nvml.ERROR_INVALID_ARGUMENT + } +} + +func (d *Device) setMockFuncs() { + d.GetMinorNumberFunc = func() (int, nvml.Return) { + return d.Minor, nvml.SUCCESS + } + + d.GetIndexFunc = func() (int, nvml.Return) { + return d.Index, nvml.SUCCESS + } + + d.GetCudaComputeCapabilityFunc = func() (int, int, nvml.Return) { + return d.CudaComputeCapability.Major, d.CudaComputeCapability.Minor, nvml.SUCCESS + } + + d.GetUUIDFunc = func() (string, nvml.Return) { + return d.UUID, nvml.SUCCESS + } + + d.GetNameFunc = func() (string, nvml.Return) { + return d.Name, nvml.SUCCESS + } + + d.GetBrandFunc = func() (nvml.BrandType, nvml.Return) { + return d.Brand, nvml.SUCCESS + } + + d.GetArchitectureFunc = func() (nvml.DeviceArchitecture, nvml.Return) { + return d.Architecture, nvml.SUCCESS + } + + d.GetMemoryInfoFunc = func() (nvml.Memory, nvml.Return) { + return d.MemoryInfo, nvml.SUCCESS + } + + d.GetPciInfoFunc = func() (nvml.PciInfo, nvml.Return) { + p := nvml.PciInfo{ + PciDeviceId: 0x20B010DE, + } + return p, nvml.SUCCESS + } + + d.SetMigModeFunc = func(mode int) (nvml.Return, nvml.Return) { + d.MigMode = mode + return nvml.SUCCESS, nvml.SUCCESS + } + + d.GetMigModeFunc = func() (int, int, nvml.Return) { + return d.MigMode, d.MigMode, nvml.SUCCESS + } + + d.GetGpuInstanceProfileInfoFunc = func(giProfileId int) (nvml.GpuInstanceProfileInfo, nvml.Return) { + if giProfileId < 0 || giProfileId >= nvml.GPU_INSTANCE_PROFILE_COUNT { + return nvml.GpuInstanceProfileInfo{}, nvml.ERROR_INVALID_ARGUMENT + } + + if _, exists := MIGProfiles.GpuInstanceProfiles[giProfileId]; !exists { + return nvml.GpuInstanceProfileInfo{}, nvml.ERROR_NOT_SUPPORTED + } + + return MIGProfiles.GpuInstanceProfiles[giProfileId], nvml.SUCCESS + } + + d.GetGpuInstancePossiblePlacementsFunc = func(info *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) { + return MIGPlacements.GpuInstancePossiblePlacements[int(info.Id)], nvml.SUCCESS + } + + d.CreateGpuInstanceFunc = func(info *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) { + d.Lock() + defer d.Unlock() + giInfo := nvml.GpuInstanceInfo{ + Device: d, + Id: d.GpuInstanceCounter, + ProfileId: info.Id, + } + d.GpuInstanceCounter++ + gi := NewGpuInstance(giInfo) + d.GpuInstances[gi] = struct{}{} + return gi, nvml.SUCCESS + } + + d.CreateGpuInstanceWithPlacementFunc = func(info *nvml.GpuInstanceProfileInfo, placement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) { + d.Lock() + defer d.Unlock() + giInfo := nvml.GpuInstanceInfo{ + Device: d, + Id: d.GpuInstanceCounter, + ProfileId: info.Id, + Placement: *placement, + } + d.GpuInstanceCounter++ + gi := NewGpuInstance(giInfo) + d.GpuInstances[gi] = struct{}{} + return gi, nvml.SUCCESS + } + + d.GetGpuInstancesFunc = func(info *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { + d.RLock() + defer d.RUnlock() + var gis []nvml.GpuInstance + for gi := range d.GpuInstances { + if gi.Info.ProfileId == info.Id { + gis = append(gis, gi) + } + } + return gis, nvml.SUCCESS + } +} + +func (gi *GpuInstance) setMockFuncs() { + gi.GetInfoFunc = func() (nvml.GpuInstanceInfo, nvml.Return) { + return gi.Info, nvml.SUCCESS + } + + gi.GetComputeInstanceProfileInfoFunc = func(ciProfileId int, ciEngProfileId int) (nvml.ComputeInstanceProfileInfo, nvml.Return) { + if ciProfileId < 0 || ciProfileId >= nvml.COMPUTE_INSTANCE_PROFILE_COUNT { + return nvml.ComputeInstanceProfileInfo{}, nvml.ERROR_INVALID_ARGUMENT + } + + if ciEngProfileId != nvml.COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED { + return nvml.ComputeInstanceProfileInfo{}, nvml.ERROR_NOT_SUPPORTED + } + + giProfileId := int(gi.Info.ProfileId) + + if _, exists := MIGProfiles.ComputeInstanceProfiles[giProfileId]; !exists { + return nvml.ComputeInstanceProfileInfo{}, nvml.ERROR_NOT_SUPPORTED + } + + if _, exists := MIGProfiles.ComputeInstanceProfiles[giProfileId][ciProfileId]; !exists { + return nvml.ComputeInstanceProfileInfo{}, nvml.ERROR_NOT_SUPPORTED + } + + return MIGProfiles.ComputeInstanceProfiles[giProfileId][ciProfileId], nvml.SUCCESS + } + + gi.GetComputeInstancePossiblePlacementsFunc = func(info *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) { + return MIGPlacements.ComputeInstancePossiblePlacements[int(gi.Info.Id)][int(info.Id)], nvml.SUCCESS + } + + gi.CreateComputeInstanceFunc = func(info *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) { + gi.Lock() + defer gi.Unlock() + ciInfo := nvml.ComputeInstanceInfo{ + Device: gi.Info.Device, + GpuInstance: gi, + Id: gi.ComputeInstanceCounter, + ProfileId: info.Id, + } + gi.ComputeInstanceCounter++ + ci := NewComputeInstance(ciInfo) + gi.ComputeInstances[ci] = struct{}{} + return ci, nvml.SUCCESS + } + + gi.GetComputeInstancesFunc = func(info *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) { + gi.RLock() + defer gi.RUnlock() + var cis []nvml.ComputeInstance + for ci := range gi.ComputeInstances { + if ci.Info.ProfileId == info.Id { + cis = append(cis, ci) + } + } + return cis, nvml.SUCCESS + } + + gi.DestroyFunc = func() nvml.Return { + d := gi.Info.Device.(*Device) + d.Lock() + defer d.Unlock() + delete(d.GpuInstances, gi) + return nvml.SUCCESS + } +} + +func (ci *ComputeInstance) setMockFuncs() { + ci.GetInfoFunc = func() (nvml.ComputeInstanceInfo, nvml.Return) { + return ci.Info, nvml.SUCCESS + } + + ci.DestroyFunc = func() nvml.Return { + gi := ci.Info.GpuInstance.(*GpuInstance) + gi.Lock() + defer gi.Unlock() + delete(gi.ComputeInstances, ci) + return nvml.SUCCESS + } +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/mig-profile.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/mig-profile.go new file mode 100644 index 00000000..c4df4c83 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100/mig-profile.go @@ -0,0 +1,471 @@ +/* + * Copyright (c) 2024, NVIDIA CORPORATION. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dgxa100 + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// MIGProfiles holds the profile information for GIs and CIs in this mock server. +// We should consider auto-generating this object in the future. +var MIGProfiles = struct { + GpuInstanceProfiles map[int]nvml.GpuInstanceProfileInfo + ComputeInstanceProfiles map[int]map[int]nvml.ComputeInstanceProfileInfo +}{ + GpuInstanceProfiles: map[int]nvml.GpuInstanceProfileInfo{ + nvml.GPU_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.GPU_INSTANCE_PROFILE_1_SLICE, + IsP2pSupported: 0, + SliceCount: 1, + InstanceCount: 7, + MultiprocessorCount: 14, + CopyEngineCount: 1, + DecoderCount: 0, + EncoderCount: 0, + JpegCount: 0, + OfaCount: 0, + MemorySizeMB: 4864, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1: { + Id: nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1, + IsP2pSupported: 0, + SliceCount: 1, + InstanceCount: 1, + MultiprocessorCount: 14, + CopyEngineCount: 1, + DecoderCount: 1, + EncoderCount: 0, + JpegCount: 1, + OfaCount: 1, + MemorySizeMB: 4864, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2: { + Id: nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2, + IsP2pSupported: 0, + SliceCount: 1, + InstanceCount: 4, + MultiprocessorCount: 14, + CopyEngineCount: 1, + DecoderCount: 1, + EncoderCount: 0, + JpegCount: 0, + OfaCount: 0, + MemorySizeMB: 9856, + }, + nvml.GPU_INSTANCE_PROFILE_2_SLICE: { + Id: nvml.GPU_INSTANCE_PROFILE_2_SLICE, + IsP2pSupported: 0, + SliceCount: 2, + InstanceCount: 3, + MultiprocessorCount: 28, + CopyEngineCount: 2, + DecoderCount: 1, + EncoderCount: 0, + JpegCount: 0, + OfaCount: 0, + MemorySizeMB: 9856, + }, + nvml.GPU_INSTANCE_PROFILE_3_SLICE: { + Id: nvml.GPU_INSTANCE_PROFILE_3_SLICE, + IsP2pSupported: 0, + SliceCount: 3, + InstanceCount: 2, + MultiprocessorCount: 42, + CopyEngineCount: 3, + DecoderCount: 2, + EncoderCount: 0, + JpegCount: 0, + OfaCount: 0, + MemorySizeMB: 19968, + }, + nvml.GPU_INSTANCE_PROFILE_4_SLICE: { + Id: nvml.GPU_INSTANCE_PROFILE_4_SLICE, + IsP2pSupported: 0, + SliceCount: 4, + InstanceCount: 1, + MultiprocessorCount: 56, + CopyEngineCount: 4, + DecoderCount: 2, + EncoderCount: 0, + JpegCount: 0, + OfaCount: 0, + MemorySizeMB: 19968, + }, + nvml.GPU_INSTANCE_PROFILE_7_SLICE: { + Id: nvml.GPU_INSTANCE_PROFILE_7_SLICE, + IsP2pSupported: 0, + SliceCount: 7, + InstanceCount: 1, + MultiprocessorCount: 98, + CopyEngineCount: 7, + DecoderCount: 5, + EncoderCount: 0, + JpegCount: 1, + OfaCount: 1, + MemorySizeMB: 40192, + }, + }, + ComputeInstanceProfiles: map[int]map[int]nvml.ComputeInstanceProfileInfo{ + nvml.GPU_INSTANCE_PROFILE_1_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 1, + MultiprocessorCount: 14, + SharedCopyEngineCount: 1, + SharedDecoderCount: 0, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 1, + MultiprocessorCount: 14, + SharedCopyEngineCount: 1, + SharedDecoderCount: 1, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 1, + MultiprocessorCount: 14, + SharedCopyEngineCount: 1, + SharedDecoderCount: 1, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + }, + nvml.GPU_INSTANCE_PROFILE_2_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 2, + MultiprocessorCount: 14, + SharedCopyEngineCount: 2, + SharedDecoderCount: 1, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE, + SliceCount: 2, + InstanceCount: 1, + MultiprocessorCount: 28, + SharedCopyEngineCount: 2, + SharedDecoderCount: 1, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + }, + nvml.GPU_INSTANCE_PROFILE_3_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 3, + MultiprocessorCount: 14, + SharedCopyEngineCount: 3, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE, + SliceCount: 2, + InstanceCount: 1, + MultiprocessorCount: 28, + SharedCopyEngineCount: 3, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE, + SliceCount: 3, + InstanceCount: 1, + MultiprocessorCount: 42, + SharedCopyEngineCount: 3, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + }, + nvml.GPU_INSTANCE_PROFILE_4_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 4, + MultiprocessorCount: 14, + SharedCopyEngineCount: 4, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE, + SliceCount: 2, + InstanceCount: 2, + MultiprocessorCount: 28, + SharedCopyEngineCount: 4, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE, + SliceCount: 4, + InstanceCount: 1, + MultiprocessorCount: 56, + SharedCopyEngineCount: 4, + SharedDecoderCount: 2, + SharedEncoderCount: 0, + SharedJpegCount: 0, + SharedOfaCount: 0, + }, + }, + nvml.GPU_INSTANCE_PROFILE_7_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE, + SliceCount: 1, + InstanceCount: 7, + MultiprocessorCount: 14, + SharedCopyEngineCount: 7, + SharedDecoderCount: 5, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE, + SliceCount: 2, + InstanceCount: 3, + MultiprocessorCount: 28, + SharedCopyEngineCount: 7, + SharedDecoderCount: 5, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE, + SliceCount: 3, + InstanceCount: 2, + MultiprocessorCount: 42, + SharedCopyEngineCount: 7, + SharedDecoderCount: 5, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE, + SliceCount: 4, + InstanceCount: 1, + MultiprocessorCount: 56, + SharedCopyEngineCount: 7, + SharedDecoderCount: 5, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + nvml.COMPUTE_INSTANCE_PROFILE_7_SLICE: { + Id: nvml.COMPUTE_INSTANCE_PROFILE_7_SLICE, + SliceCount: 7, + InstanceCount: 1, + MultiprocessorCount: 98, + SharedCopyEngineCount: 7, + SharedDecoderCount: 5, + SharedEncoderCount: 0, + SharedJpegCount: 1, + SharedOfaCount: 1, + }, + }, + }, +} + +// MIGPlacements holds the placement information for GIs and CIs in this mock server. +// We should consider auto-generating this object in the future. +var MIGPlacements = struct { + GpuInstancePossiblePlacements map[int][]nvml.GpuInstancePlacement + ComputeInstancePossiblePlacements map[int]map[int][]nvml.ComputeInstancePlacement +}{ + GpuInstancePossiblePlacements: map[int][]nvml.GpuInstancePlacement{ + nvml.GPU_INSTANCE_PROFILE_1_SLICE: { + { + Start: 0, + Size: 1, + }, + { + Start: 1, + Size: 1, + }, + { + Start: 2, + Size: 1, + }, + { + Start: 3, + Size: 1, + }, + { + Start: 4, + Size: 1, + }, + { + Start: 5, + Size: 1, + }, + { + Start: 6, + Size: 1, + }, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1: { + { + Start: 0, + Size: 1, + }, + { + Start: 1, + Size: 1, + }, + { + Start: 2, + Size: 1, + }, + { + Start: 3, + Size: 1, + }, + { + Start: 4, + Size: 1, + }, + { + Start: 5, + Size: 1, + }, + { + Start: 6, + Size: 1, + }, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2: { + { + Start: 0, + Size: 2, + }, + { + Start: 2, + Size: 2, + }, + { + Start: 4, + Size: 2, + }, + { + Start: 6, + Size: 2, + }, + }, + nvml.GPU_INSTANCE_PROFILE_2_SLICE: { + { + Start: 0, + Size: 2, + }, + { + Start: 2, + Size: 2, + }, + { + Start: 4, + Size: 2, + }, + }, + nvml.GPU_INSTANCE_PROFILE_3_SLICE: { + { + Start: 0, + Size: 4, + }, + { + Start: 4, + Size: 4, + }, + }, + nvml.GPU_INSTANCE_PROFILE_4_SLICE: { + { + Start: 0, + Size: 4, + }, + }, + nvml.GPU_INSTANCE_PROFILE_7_SLICE: { + { + Start: 0, + Size: 8, + }, + }, + }, + // TODO: Fill out ComputeInstancePossiblePlacements + ComputeInstancePossiblePlacements: map[int]map[int][]nvml.ComputeInstancePlacement{ + nvml.GPU_INSTANCE_PROFILE_1_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV1: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_1_SLICE_REV2: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_2_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_3_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_4_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE: {}, + }, + nvml.GPU_INSTANCE_PROFILE_7_SLICE: { + nvml.COMPUTE_INSTANCE_PROFILE_1_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_2_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_3_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_4_SLICE: {}, + nvml.COMPUTE_INSTANCE_PROFILE_7_SLICE: {}, + }, + }, +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/eventset.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/eventset.go new file mode 100644 index 00000000..d452c4d4 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/eventset.go @@ -0,0 +1,112 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that EventSet does implement nvml.EventSet. +// If this is not the case, regenerate this file with moq. +var _ nvml.EventSet = &EventSet{} + +// EventSet is a mock implementation of nvml.EventSet. +// +// func TestSomethingThatUsesEventSet(t *testing.T) { +// +// // make and configure a mocked nvml.EventSet +// mockedEventSet := &EventSet{ +// FreeFunc: func() nvml.Return { +// panic("mock out the Free method") +// }, +// WaitFunc: func(v uint32) (nvml.EventData, nvml.Return) { +// panic("mock out the Wait method") +// }, +// } +// +// // use mockedEventSet in code that requires nvml.EventSet +// // and then make assertions. +// +// } +type EventSet struct { + // FreeFunc mocks the Free method. + FreeFunc func() nvml.Return + + // WaitFunc mocks the Wait method. + WaitFunc func(v uint32) (nvml.EventData, nvml.Return) + + // calls tracks calls to the methods. + calls struct { + // Free holds details about calls to the Free method. + Free []struct { + } + // Wait holds details about calls to the Wait method. + Wait []struct { + // V is the v argument value. + V uint32 + } + } + lockFree sync.RWMutex + lockWait sync.RWMutex +} + +// Free calls FreeFunc. +func (mock *EventSet) Free() nvml.Return { + if mock.FreeFunc == nil { + panic("EventSet.FreeFunc: method is nil but EventSet.Free was just called") + } + callInfo := struct { + }{} + mock.lockFree.Lock() + mock.calls.Free = append(mock.calls.Free, callInfo) + mock.lockFree.Unlock() + return mock.FreeFunc() +} + +// FreeCalls gets all the calls that were made to Free. +// Check the length with: +// +// len(mockedEventSet.FreeCalls()) +func (mock *EventSet) FreeCalls() []struct { +} { + var calls []struct { + } + mock.lockFree.RLock() + calls = mock.calls.Free + mock.lockFree.RUnlock() + return calls +} + +// Wait calls WaitFunc. +func (mock *EventSet) Wait(v uint32) (nvml.EventData, nvml.Return) { + if mock.WaitFunc == nil { + panic("EventSet.WaitFunc: method is nil but EventSet.Wait was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockWait.Lock() + mock.calls.Wait = append(mock.calls.Wait, callInfo) + mock.lockWait.Unlock() + return mock.WaitFunc(v) +} + +// WaitCalls gets all the calls that were made to Wait. +// Check the length with: +// +// len(mockedEventSet.WaitCalls()) +func (mock *EventSet) WaitCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockWait.RLock() + calls = mock.calls.Wait + mock.lockWait.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/extendedinterface.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/extendedinterface.go new file mode 100644 index 00000000..71634bfd --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/extendedinterface.go @@ -0,0 +1,75 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that ExtendedInterface does implement nvml.ExtendedInterface. +// If this is not the case, regenerate this file with moq. +var _ nvml.ExtendedInterface = &ExtendedInterface{} + +// ExtendedInterface is a mock implementation of nvml.ExtendedInterface. +// +// func TestSomethingThatUsesExtendedInterface(t *testing.T) { +// +// // make and configure a mocked nvml.ExtendedInterface +// mockedExtendedInterface := &ExtendedInterface{ +// LookupSymbolFunc: func(s string) error { +// panic("mock out the LookupSymbol method") +// }, +// } +// +// // use mockedExtendedInterface in code that requires nvml.ExtendedInterface +// // and then make assertions. +// +// } +type ExtendedInterface struct { + // LookupSymbolFunc mocks the LookupSymbol method. + LookupSymbolFunc func(s string) error + + // calls tracks calls to the methods. + calls struct { + // LookupSymbol holds details about calls to the LookupSymbol method. + LookupSymbol []struct { + // S is the s argument value. + S string + } + } + lockLookupSymbol sync.RWMutex +} + +// LookupSymbol calls LookupSymbolFunc. +func (mock *ExtendedInterface) LookupSymbol(s string) error { + if mock.LookupSymbolFunc == nil { + panic("ExtendedInterface.LookupSymbolFunc: method is nil but ExtendedInterface.LookupSymbol was just called") + } + callInfo := struct { + S string + }{ + S: s, + } + mock.lockLookupSymbol.Lock() + mock.calls.LookupSymbol = append(mock.calls.LookupSymbol, callInfo) + mock.lockLookupSymbol.Unlock() + return mock.LookupSymbolFunc(s) +} + +// LookupSymbolCalls gets all the calls that were made to LookupSymbol. +// Check the length with: +// +// len(mockedExtendedInterface.LookupSymbolCalls()) +func (mock *ExtendedInterface) LookupSymbolCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockLookupSymbol.RLock() + calls = mock.calls.LookupSymbol + mock.lockLookupSymbol.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpmsample.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpmsample.go new file mode 100644 index 00000000..1023c344 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpmsample.go @@ -0,0 +1,162 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that GpmSample does implement nvml.GpmSample. +// If this is not the case, regenerate this file with moq. +var _ nvml.GpmSample = &GpmSample{} + +// GpmSample is a mock implementation of nvml.GpmSample. +// +// func TestSomethingThatUsesGpmSample(t *testing.T) { +// +// // make and configure a mocked nvml.GpmSample +// mockedGpmSample := &GpmSample{ +// FreeFunc: func() nvml.Return { +// panic("mock out the Free method") +// }, +// GetFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the Get method") +// }, +// MigGetFunc: func(device nvml.Device, n int) nvml.Return { +// panic("mock out the MigGet method") +// }, +// } +// +// // use mockedGpmSample in code that requires nvml.GpmSample +// // and then make assertions. +// +// } +type GpmSample struct { + // FreeFunc mocks the Free method. + FreeFunc func() nvml.Return + + // GetFunc mocks the Get method. + GetFunc func(device nvml.Device) nvml.Return + + // MigGetFunc mocks the MigGet method. + MigGetFunc func(device nvml.Device, n int) nvml.Return + + // calls tracks calls to the methods. + calls struct { + // Free holds details about calls to the Free method. + Free []struct { + } + // Get holds details about calls to the Get method. + Get []struct { + // Device is the device argument value. + Device nvml.Device + } + // MigGet holds details about calls to the MigGet method. + MigGet []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + } + lockFree sync.RWMutex + lockGet sync.RWMutex + lockMigGet sync.RWMutex +} + +// Free calls FreeFunc. +func (mock *GpmSample) Free() nvml.Return { + if mock.FreeFunc == nil { + panic("GpmSample.FreeFunc: method is nil but GpmSample.Free was just called") + } + callInfo := struct { + }{} + mock.lockFree.Lock() + mock.calls.Free = append(mock.calls.Free, callInfo) + mock.lockFree.Unlock() + return mock.FreeFunc() +} + +// FreeCalls gets all the calls that were made to Free. +// Check the length with: +// +// len(mockedGpmSample.FreeCalls()) +func (mock *GpmSample) FreeCalls() []struct { +} { + var calls []struct { + } + mock.lockFree.RLock() + calls = mock.calls.Free + mock.lockFree.RUnlock() + return calls +} + +// Get calls GetFunc. +func (mock *GpmSample) Get(device nvml.Device) nvml.Return { + if mock.GetFunc == nil { + panic("GpmSample.GetFunc: method is nil but GpmSample.Get was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGet.Lock() + mock.calls.Get = append(mock.calls.Get, callInfo) + mock.lockGet.Unlock() + return mock.GetFunc(device) +} + +// GetCalls gets all the calls that were made to Get. +// Check the length with: +// +// len(mockedGpmSample.GetCalls()) +func (mock *GpmSample) GetCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGet.RLock() + calls = mock.calls.Get + mock.lockGet.RUnlock() + return calls +} + +// MigGet calls MigGetFunc. +func (mock *GpmSample) MigGet(device nvml.Device, n int) nvml.Return { + if mock.MigGetFunc == nil { + panic("GpmSample.MigGetFunc: method is nil but GpmSample.MigGet was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockMigGet.Lock() + mock.calls.MigGet = append(mock.calls.MigGet, callInfo) + mock.lockMigGet.Unlock() + return mock.MigGetFunc(device, n) +} + +// MigGetCalls gets all the calls that were made to MigGet. +// Check the length with: +// +// len(mockedGpmSample.MigGetCalls()) +func (mock *GpmSample) MigGetCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockMigGet.RLock() + calls = mock.calls.MigGet + mock.lockMigGet.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpuinstance.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpuinstance.go new file mode 100644 index 00000000..d05bc348 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/gpuinstance.go @@ -0,0 +1,785 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that GpuInstance does implement nvml.GpuInstance. +// If this is not the case, regenerate this file with moq. +var _ nvml.GpuInstance = &GpuInstance{} + +// GpuInstance is a mock implementation of nvml.GpuInstance. +// +// func TestSomethingThatUsesGpuInstance(t *testing.T) { +// +// // make and configure a mocked nvml.GpuInstance +// mockedGpuInstance := &GpuInstance{ +// CreateComputeInstanceFunc: func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the CreateComputeInstance method") +// }, +// CreateComputeInstanceWithPlacementFunc: func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the CreateComputeInstanceWithPlacement method") +// }, +// DestroyFunc: func() nvml.Return { +// panic("mock out the Destroy method") +// }, +// GetActiveVgpusFunc: func() (nvml.ActiveVgpuInstanceInfo, nvml.Return) { +// panic("mock out the GetActiveVgpus method") +// }, +// GetComputeInstanceByIdFunc: func(n int) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GetComputeInstanceById method") +// }, +// GetComputeInstancePossiblePlacementsFunc: func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) { +// panic("mock out the GetComputeInstancePossiblePlacements method") +// }, +// GetComputeInstanceProfileInfoFunc: func(n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) { +// panic("mock out the GetComputeInstanceProfileInfo method") +// }, +// GetComputeInstanceProfileInfoVFunc: func(n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler { +// panic("mock out the GetComputeInstanceProfileInfoV method") +// }, +// GetComputeInstanceRemainingCapacityFunc: func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) { +// panic("mock out the GetComputeInstanceRemainingCapacity method") +// }, +// GetComputeInstancesFunc: func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GetComputeInstances method") +// }, +// GetCreatableVgpusFunc: func() (nvml.VgpuTypeIdInfo, nvml.Return) { +// panic("mock out the GetCreatableVgpus method") +// }, +// GetInfoFunc: func() (nvml.GpuInstanceInfo, nvml.Return) { +// panic("mock out the GetInfo method") +// }, +// GetVgpuHeterogeneousModeFunc: func() (nvml.VgpuHeterogeneousMode, nvml.Return) { +// panic("mock out the GetVgpuHeterogeneousMode method") +// }, +// GetVgpuSchedulerLogFunc: func() (nvml.VgpuSchedulerLogInfo, nvml.Return) { +// panic("mock out the GetVgpuSchedulerLog method") +// }, +// GetVgpuSchedulerStateFunc: func() (nvml.VgpuSchedulerStateInfo, nvml.Return) { +// panic("mock out the GetVgpuSchedulerState method") +// }, +// GetVgpuTypeCreatablePlacementsFunc: func() (nvml.VgpuCreatablePlacementInfo, nvml.Return) { +// panic("mock out the GetVgpuTypeCreatablePlacements method") +// }, +// SetVgpuHeterogeneousModeFunc: func(vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return { +// panic("mock out the SetVgpuHeterogeneousMode method") +// }, +// SetVgpuSchedulerStateFunc: func(vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return { +// panic("mock out the SetVgpuSchedulerState method") +// }, +// } +// +// // use mockedGpuInstance in code that requires nvml.GpuInstance +// // and then make assertions. +// +// } +type GpuInstance struct { + // CreateComputeInstanceFunc mocks the CreateComputeInstance method. + CreateComputeInstanceFunc func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) + + // CreateComputeInstanceWithPlacementFunc mocks the CreateComputeInstanceWithPlacement method. + CreateComputeInstanceWithPlacementFunc func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) + + // DestroyFunc mocks the Destroy method. + DestroyFunc func() nvml.Return + + // GetActiveVgpusFunc mocks the GetActiveVgpus method. + GetActiveVgpusFunc func() (nvml.ActiveVgpuInstanceInfo, nvml.Return) + + // GetComputeInstanceByIdFunc mocks the GetComputeInstanceById method. + GetComputeInstanceByIdFunc func(n int) (nvml.ComputeInstance, nvml.Return) + + // GetComputeInstancePossiblePlacementsFunc mocks the GetComputeInstancePossiblePlacements method. + GetComputeInstancePossiblePlacementsFunc func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) + + // GetComputeInstanceProfileInfoFunc mocks the GetComputeInstanceProfileInfo method. + GetComputeInstanceProfileInfoFunc func(n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) + + // GetComputeInstanceProfileInfoVFunc mocks the GetComputeInstanceProfileInfoV method. + GetComputeInstanceProfileInfoVFunc func(n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler + + // GetComputeInstanceRemainingCapacityFunc mocks the GetComputeInstanceRemainingCapacity method. + GetComputeInstanceRemainingCapacityFunc func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) + + // GetComputeInstancesFunc mocks the GetComputeInstances method. + GetComputeInstancesFunc func(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) + + // GetCreatableVgpusFunc mocks the GetCreatableVgpus method. + GetCreatableVgpusFunc func() (nvml.VgpuTypeIdInfo, nvml.Return) + + // GetInfoFunc mocks the GetInfo method. + GetInfoFunc func() (nvml.GpuInstanceInfo, nvml.Return) + + // GetVgpuHeterogeneousModeFunc mocks the GetVgpuHeterogeneousMode method. + GetVgpuHeterogeneousModeFunc func() (nvml.VgpuHeterogeneousMode, nvml.Return) + + // GetVgpuSchedulerLogFunc mocks the GetVgpuSchedulerLog method. + GetVgpuSchedulerLogFunc func() (nvml.VgpuSchedulerLogInfo, nvml.Return) + + // GetVgpuSchedulerStateFunc mocks the GetVgpuSchedulerState method. + GetVgpuSchedulerStateFunc func() (nvml.VgpuSchedulerStateInfo, nvml.Return) + + // GetVgpuTypeCreatablePlacementsFunc mocks the GetVgpuTypeCreatablePlacements method. + GetVgpuTypeCreatablePlacementsFunc func() (nvml.VgpuCreatablePlacementInfo, nvml.Return) + + // SetVgpuHeterogeneousModeFunc mocks the SetVgpuHeterogeneousMode method. + SetVgpuHeterogeneousModeFunc func(vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return + + // SetVgpuSchedulerStateFunc mocks the SetVgpuSchedulerState method. + SetVgpuSchedulerStateFunc func(vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return + + // calls tracks calls to the methods. + calls struct { + // CreateComputeInstance holds details about calls to the CreateComputeInstance method. + CreateComputeInstance []struct { + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // CreateComputeInstanceWithPlacement holds details about calls to the CreateComputeInstanceWithPlacement method. + CreateComputeInstanceWithPlacement []struct { + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + // ComputeInstancePlacement is the computeInstancePlacement argument value. + ComputeInstancePlacement *nvml.ComputeInstancePlacement + } + // Destroy holds details about calls to the Destroy method. + Destroy []struct { + } + // GetActiveVgpus holds details about calls to the GetActiveVgpus method. + GetActiveVgpus []struct { + } + // GetComputeInstanceById holds details about calls to the GetComputeInstanceById method. + GetComputeInstanceById []struct { + // N is the n argument value. + N int + } + // GetComputeInstancePossiblePlacements holds details about calls to the GetComputeInstancePossiblePlacements method. + GetComputeInstancePossiblePlacements []struct { + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GetComputeInstanceProfileInfo holds details about calls to the GetComputeInstanceProfileInfo method. + GetComputeInstanceProfileInfo []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GetComputeInstanceProfileInfoV holds details about calls to the GetComputeInstanceProfileInfoV method. + GetComputeInstanceProfileInfoV []struct { + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GetComputeInstanceRemainingCapacity holds details about calls to the GetComputeInstanceRemainingCapacity method. + GetComputeInstanceRemainingCapacity []struct { + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GetComputeInstances holds details about calls to the GetComputeInstances method. + GetComputeInstances []struct { + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GetCreatableVgpus holds details about calls to the GetCreatableVgpus method. + GetCreatableVgpus []struct { + } + // GetInfo holds details about calls to the GetInfo method. + GetInfo []struct { + } + // GetVgpuHeterogeneousMode holds details about calls to the GetVgpuHeterogeneousMode method. + GetVgpuHeterogeneousMode []struct { + } + // GetVgpuSchedulerLog holds details about calls to the GetVgpuSchedulerLog method. + GetVgpuSchedulerLog []struct { + } + // GetVgpuSchedulerState holds details about calls to the GetVgpuSchedulerState method. + GetVgpuSchedulerState []struct { + } + // GetVgpuTypeCreatablePlacements holds details about calls to the GetVgpuTypeCreatablePlacements method. + GetVgpuTypeCreatablePlacements []struct { + } + // SetVgpuHeterogeneousMode holds details about calls to the SetVgpuHeterogeneousMode method. + SetVgpuHeterogeneousMode []struct { + // VgpuHeterogeneousMode is the vgpuHeterogeneousMode argument value. + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + } + // SetVgpuSchedulerState holds details about calls to the SetVgpuSchedulerState method. + SetVgpuSchedulerState []struct { + // VgpuSchedulerState is the vgpuSchedulerState argument value. + VgpuSchedulerState *nvml.VgpuSchedulerState + } + } + lockCreateComputeInstance sync.RWMutex + lockCreateComputeInstanceWithPlacement sync.RWMutex + lockDestroy sync.RWMutex + lockGetActiveVgpus sync.RWMutex + lockGetComputeInstanceById sync.RWMutex + lockGetComputeInstancePossiblePlacements sync.RWMutex + lockGetComputeInstanceProfileInfo sync.RWMutex + lockGetComputeInstanceProfileInfoV sync.RWMutex + lockGetComputeInstanceRemainingCapacity sync.RWMutex + lockGetComputeInstances sync.RWMutex + lockGetCreatableVgpus sync.RWMutex + lockGetInfo sync.RWMutex + lockGetVgpuHeterogeneousMode sync.RWMutex + lockGetVgpuSchedulerLog sync.RWMutex + lockGetVgpuSchedulerState sync.RWMutex + lockGetVgpuTypeCreatablePlacements sync.RWMutex + lockSetVgpuHeterogeneousMode sync.RWMutex + lockSetVgpuSchedulerState sync.RWMutex +} + +// CreateComputeInstance calls CreateComputeInstanceFunc. +func (mock *GpuInstance) CreateComputeInstance(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) { + if mock.CreateComputeInstanceFunc == nil { + panic("GpuInstance.CreateComputeInstanceFunc: method is nil but GpuInstance.CreateComputeInstance was just called") + } + callInfo := struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockCreateComputeInstance.Lock() + mock.calls.CreateComputeInstance = append(mock.calls.CreateComputeInstance, callInfo) + mock.lockCreateComputeInstance.Unlock() + return mock.CreateComputeInstanceFunc(computeInstanceProfileInfo) +} + +// CreateComputeInstanceCalls gets all the calls that were made to CreateComputeInstance. +// Check the length with: +// +// len(mockedGpuInstance.CreateComputeInstanceCalls()) +func (mock *GpuInstance) CreateComputeInstanceCalls() []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockCreateComputeInstance.RLock() + calls = mock.calls.CreateComputeInstance + mock.lockCreateComputeInstance.RUnlock() + return calls +} + +// CreateComputeInstanceWithPlacement calls CreateComputeInstanceWithPlacementFunc. +func (mock *GpuInstance) CreateComputeInstanceWithPlacement(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) { + if mock.CreateComputeInstanceWithPlacementFunc == nil { + panic("GpuInstance.CreateComputeInstanceWithPlacementFunc: method is nil but GpuInstance.CreateComputeInstanceWithPlacement was just called") + } + callInfo := struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement + }{ + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + ComputeInstancePlacement: computeInstancePlacement, + } + mock.lockCreateComputeInstanceWithPlacement.Lock() + mock.calls.CreateComputeInstanceWithPlacement = append(mock.calls.CreateComputeInstanceWithPlacement, callInfo) + mock.lockCreateComputeInstanceWithPlacement.Unlock() + return mock.CreateComputeInstanceWithPlacementFunc(computeInstanceProfileInfo, computeInstancePlacement) +} + +// CreateComputeInstanceWithPlacementCalls gets all the calls that were made to CreateComputeInstanceWithPlacement. +// Check the length with: +// +// len(mockedGpuInstance.CreateComputeInstanceWithPlacementCalls()) +func (mock *GpuInstance) CreateComputeInstanceWithPlacementCalls() []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement +} { + var calls []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement + } + mock.lockCreateComputeInstanceWithPlacement.RLock() + calls = mock.calls.CreateComputeInstanceWithPlacement + mock.lockCreateComputeInstanceWithPlacement.RUnlock() + return calls +} + +// Destroy calls DestroyFunc. +func (mock *GpuInstance) Destroy() nvml.Return { + if mock.DestroyFunc == nil { + panic("GpuInstance.DestroyFunc: method is nil but GpuInstance.Destroy was just called") + } + callInfo := struct { + }{} + mock.lockDestroy.Lock() + mock.calls.Destroy = append(mock.calls.Destroy, callInfo) + mock.lockDestroy.Unlock() + return mock.DestroyFunc() +} + +// DestroyCalls gets all the calls that were made to Destroy. +// Check the length with: +// +// len(mockedGpuInstance.DestroyCalls()) +func (mock *GpuInstance) DestroyCalls() []struct { +} { + var calls []struct { + } + mock.lockDestroy.RLock() + calls = mock.calls.Destroy + mock.lockDestroy.RUnlock() + return calls +} + +// GetActiveVgpus calls GetActiveVgpusFunc. +func (mock *GpuInstance) GetActiveVgpus() (nvml.ActiveVgpuInstanceInfo, nvml.Return) { + if mock.GetActiveVgpusFunc == nil { + panic("GpuInstance.GetActiveVgpusFunc: method is nil but GpuInstance.GetActiveVgpus was just called") + } + callInfo := struct { + }{} + mock.lockGetActiveVgpus.Lock() + mock.calls.GetActiveVgpus = append(mock.calls.GetActiveVgpus, callInfo) + mock.lockGetActiveVgpus.Unlock() + return mock.GetActiveVgpusFunc() +} + +// GetActiveVgpusCalls gets all the calls that were made to GetActiveVgpus. +// Check the length with: +// +// len(mockedGpuInstance.GetActiveVgpusCalls()) +func (mock *GpuInstance) GetActiveVgpusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetActiveVgpus.RLock() + calls = mock.calls.GetActiveVgpus + mock.lockGetActiveVgpus.RUnlock() + return calls +} + +// GetComputeInstanceById calls GetComputeInstanceByIdFunc. +func (mock *GpuInstance) GetComputeInstanceById(n int) (nvml.ComputeInstance, nvml.Return) { + if mock.GetComputeInstanceByIdFunc == nil { + panic("GpuInstance.GetComputeInstanceByIdFunc: method is nil but GpuInstance.GetComputeInstanceById was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetComputeInstanceById.Lock() + mock.calls.GetComputeInstanceById = append(mock.calls.GetComputeInstanceById, callInfo) + mock.lockGetComputeInstanceById.Unlock() + return mock.GetComputeInstanceByIdFunc(n) +} + +// GetComputeInstanceByIdCalls gets all the calls that were made to GetComputeInstanceById. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstanceByIdCalls()) +func (mock *GpuInstance) GetComputeInstanceByIdCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetComputeInstanceById.RLock() + calls = mock.calls.GetComputeInstanceById + mock.lockGetComputeInstanceById.RUnlock() + return calls +} + +// GetComputeInstancePossiblePlacements calls GetComputeInstancePossiblePlacementsFunc. +func (mock *GpuInstance) GetComputeInstancePossiblePlacements(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) { + if mock.GetComputeInstancePossiblePlacementsFunc == nil { + panic("GpuInstance.GetComputeInstancePossiblePlacementsFunc: method is nil but GpuInstance.GetComputeInstancePossiblePlacements was just called") + } + callInfo := struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGetComputeInstancePossiblePlacements.Lock() + mock.calls.GetComputeInstancePossiblePlacements = append(mock.calls.GetComputeInstancePossiblePlacements, callInfo) + mock.lockGetComputeInstancePossiblePlacements.Unlock() + return mock.GetComputeInstancePossiblePlacementsFunc(computeInstanceProfileInfo) +} + +// GetComputeInstancePossiblePlacementsCalls gets all the calls that were made to GetComputeInstancePossiblePlacements. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstancePossiblePlacementsCalls()) +func (mock *GpuInstance) GetComputeInstancePossiblePlacementsCalls() []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGetComputeInstancePossiblePlacements.RLock() + calls = mock.calls.GetComputeInstancePossiblePlacements + mock.lockGetComputeInstancePossiblePlacements.RUnlock() + return calls +} + +// GetComputeInstanceProfileInfo calls GetComputeInstanceProfileInfoFunc. +func (mock *GpuInstance) GetComputeInstanceProfileInfo(n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) { + if mock.GetComputeInstanceProfileInfoFunc == nil { + panic("GpuInstance.GetComputeInstanceProfileInfoFunc: method is nil but GpuInstance.GetComputeInstanceProfileInfo was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockGetComputeInstanceProfileInfo.Lock() + mock.calls.GetComputeInstanceProfileInfo = append(mock.calls.GetComputeInstanceProfileInfo, callInfo) + mock.lockGetComputeInstanceProfileInfo.Unlock() + return mock.GetComputeInstanceProfileInfoFunc(n1, n2) +} + +// GetComputeInstanceProfileInfoCalls gets all the calls that were made to GetComputeInstanceProfileInfo. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstanceProfileInfoCalls()) +func (mock *GpuInstance) GetComputeInstanceProfileInfoCalls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockGetComputeInstanceProfileInfo.RLock() + calls = mock.calls.GetComputeInstanceProfileInfo + mock.lockGetComputeInstanceProfileInfo.RUnlock() + return calls +} + +// GetComputeInstanceProfileInfoV calls GetComputeInstanceProfileInfoVFunc. +func (mock *GpuInstance) GetComputeInstanceProfileInfoV(n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler { + if mock.GetComputeInstanceProfileInfoVFunc == nil { + panic("GpuInstance.GetComputeInstanceProfileInfoVFunc: method is nil but GpuInstance.GetComputeInstanceProfileInfoV was just called") + } + callInfo := struct { + N1 int + N2 int + }{ + N1: n1, + N2: n2, + } + mock.lockGetComputeInstanceProfileInfoV.Lock() + mock.calls.GetComputeInstanceProfileInfoV = append(mock.calls.GetComputeInstanceProfileInfoV, callInfo) + mock.lockGetComputeInstanceProfileInfoV.Unlock() + return mock.GetComputeInstanceProfileInfoVFunc(n1, n2) +} + +// GetComputeInstanceProfileInfoVCalls gets all the calls that were made to GetComputeInstanceProfileInfoV. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstanceProfileInfoVCalls()) +func (mock *GpuInstance) GetComputeInstanceProfileInfoVCalls() []struct { + N1 int + N2 int +} { + var calls []struct { + N1 int + N2 int + } + mock.lockGetComputeInstanceProfileInfoV.RLock() + calls = mock.calls.GetComputeInstanceProfileInfoV + mock.lockGetComputeInstanceProfileInfoV.RUnlock() + return calls +} + +// GetComputeInstanceRemainingCapacity calls GetComputeInstanceRemainingCapacityFunc. +func (mock *GpuInstance) GetComputeInstanceRemainingCapacity(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) { + if mock.GetComputeInstanceRemainingCapacityFunc == nil { + panic("GpuInstance.GetComputeInstanceRemainingCapacityFunc: method is nil but GpuInstance.GetComputeInstanceRemainingCapacity was just called") + } + callInfo := struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGetComputeInstanceRemainingCapacity.Lock() + mock.calls.GetComputeInstanceRemainingCapacity = append(mock.calls.GetComputeInstanceRemainingCapacity, callInfo) + mock.lockGetComputeInstanceRemainingCapacity.Unlock() + return mock.GetComputeInstanceRemainingCapacityFunc(computeInstanceProfileInfo) +} + +// GetComputeInstanceRemainingCapacityCalls gets all the calls that were made to GetComputeInstanceRemainingCapacity. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstanceRemainingCapacityCalls()) +func (mock *GpuInstance) GetComputeInstanceRemainingCapacityCalls() []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGetComputeInstanceRemainingCapacity.RLock() + calls = mock.calls.GetComputeInstanceRemainingCapacity + mock.lockGetComputeInstanceRemainingCapacity.RUnlock() + return calls +} + +// GetComputeInstances calls GetComputeInstancesFunc. +func (mock *GpuInstance) GetComputeInstances(computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) { + if mock.GetComputeInstancesFunc == nil { + panic("GpuInstance.GetComputeInstancesFunc: method is nil but GpuInstance.GetComputeInstances was just called") + } + callInfo := struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGetComputeInstances.Lock() + mock.calls.GetComputeInstances = append(mock.calls.GetComputeInstances, callInfo) + mock.lockGetComputeInstances.Unlock() + return mock.GetComputeInstancesFunc(computeInstanceProfileInfo) +} + +// GetComputeInstancesCalls gets all the calls that were made to GetComputeInstances. +// Check the length with: +// +// len(mockedGpuInstance.GetComputeInstancesCalls()) +func (mock *GpuInstance) GetComputeInstancesCalls() []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGetComputeInstances.RLock() + calls = mock.calls.GetComputeInstances + mock.lockGetComputeInstances.RUnlock() + return calls +} + +// GetCreatableVgpus calls GetCreatableVgpusFunc. +func (mock *GpuInstance) GetCreatableVgpus() (nvml.VgpuTypeIdInfo, nvml.Return) { + if mock.GetCreatableVgpusFunc == nil { + panic("GpuInstance.GetCreatableVgpusFunc: method is nil but GpuInstance.GetCreatableVgpus was just called") + } + callInfo := struct { + }{} + mock.lockGetCreatableVgpus.Lock() + mock.calls.GetCreatableVgpus = append(mock.calls.GetCreatableVgpus, callInfo) + mock.lockGetCreatableVgpus.Unlock() + return mock.GetCreatableVgpusFunc() +} + +// GetCreatableVgpusCalls gets all the calls that were made to GetCreatableVgpus. +// Check the length with: +// +// len(mockedGpuInstance.GetCreatableVgpusCalls()) +func (mock *GpuInstance) GetCreatableVgpusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetCreatableVgpus.RLock() + calls = mock.calls.GetCreatableVgpus + mock.lockGetCreatableVgpus.RUnlock() + return calls +} + +// GetInfo calls GetInfoFunc. +func (mock *GpuInstance) GetInfo() (nvml.GpuInstanceInfo, nvml.Return) { + if mock.GetInfoFunc == nil { + panic("GpuInstance.GetInfoFunc: method is nil but GpuInstance.GetInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetInfo.Lock() + mock.calls.GetInfo = append(mock.calls.GetInfo, callInfo) + mock.lockGetInfo.Unlock() + return mock.GetInfoFunc() +} + +// GetInfoCalls gets all the calls that were made to GetInfo. +// Check the length with: +// +// len(mockedGpuInstance.GetInfoCalls()) +func (mock *GpuInstance) GetInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetInfo.RLock() + calls = mock.calls.GetInfo + mock.lockGetInfo.RUnlock() + return calls +} + +// GetVgpuHeterogeneousMode calls GetVgpuHeterogeneousModeFunc. +func (mock *GpuInstance) GetVgpuHeterogeneousMode() (nvml.VgpuHeterogeneousMode, nvml.Return) { + if mock.GetVgpuHeterogeneousModeFunc == nil { + panic("GpuInstance.GetVgpuHeterogeneousModeFunc: method is nil but GpuInstance.GetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuHeterogeneousMode.Lock() + mock.calls.GetVgpuHeterogeneousMode = append(mock.calls.GetVgpuHeterogeneousMode, callInfo) + mock.lockGetVgpuHeterogeneousMode.Unlock() + return mock.GetVgpuHeterogeneousModeFunc() +} + +// GetVgpuHeterogeneousModeCalls gets all the calls that were made to GetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedGpuInstance.GetVgpuHeterogeneousModeCalls()) +func (mock *GpuInstance) GetVgpuHeterogeneousModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuHeterogeneousMode.RLock() + calls = mock.calls.GetVgpuHeterogeneousMode + mock.lockGetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// GetVgpuSchedulerLog calls GetVgpuSchedulerLogFunc. +func (mock *GpuInstance) GetVgpuSchedulerLog() (nvml.VgpuSchedulerLogInfo, nvml.Return) { + if mock.GetVgpuSchedulerLogFunc == nil { + panic("GpuInstance.GetVgpuSchedulerLogFunc: method is nil but GpuInstance.GetVgpuSchedulerLog was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuSchedulerLog.Lock() + mock.calls.GetVgpuSchedulerLog = append(mock.calls.GetVgpuSchedulerLog, callInfo) + mock.lockGetVgpuSchedulerLog.Unlock() + return mock.GetVgpuSchedulerLogFunc() +} + +// GetVgpuSchedulerLogCalls gets all the calls that were made to GetVgpuSchedulerLog. +// Check the length with: +// +// len(mockedGpuInstance.GetVgpuSchedulerLogCalls()) +func (mock *GpuInstance) GetVgpuSchedulerLogCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuSchedulerLog.RLock() + calls = mock.calls.GetVgpuSchedulerLog + mock.lockGetVgpuSchedulerLog.RUnlock() + return calls +} + +// GetVgpuSchedulerState calls GetVgpuSchedulerStateFunc. +func (mock *GpuInstance) GetVgpuSchedulerState() (nvml.VgpuSchedulerStateInfo, nvml.Return) { + if mock.GetVgpuSchedulerStateFunc == nil { + panic("GpuInstance.GetVgpuSchedulerStateFunc: method is nil but GpuInstance.GetVgpuSchedulerState was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuSchedulerState.Lock() + mock.calls.GetVgpuSchedulerState = append(mock.calls.GetVgpuSchedulerState, callInfo) + mock.lockGetVgpuSchedulerState.Unlock() + return mock.GetVgpuSchedulerStateFunc() +} + +// GetVgpuSchedulerStateCalls gets all the calls that were made to GetVgpuSchedulerState. +// Check the length with: +// +// len(mockedGpuInstance.GetVgpuSchedulerStateCalls()) +func (mock *GpuInstance) GetVgpuSchedulerStateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuSchedulerState.RLock() + calls = mock.calls.GetVgpuSchedulerState + mock.lockGetVgpuSchedulerState.RUnlock() + return calls +} + +// GetVgpuTypeCreatablePlacements calls GetVgpuTypeCreatablePlacementsFunc. +func (mock *GpuInstance) GetVgpuTypeCreatablePlacements() (nvml.VgpuCreatablePlacementInfo, nvml.Return) { + if mock.GetVgpuTypeCreatablePlacementsFunc == nil { + panic("GpuInstance.GetVgpuTypeCreatablePlacementsFunc: method is nil but GpuInstance.GetVgpuTypeCreatablePlacements was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuTypeCreatablePlacements.Lock() + mock.calls.GetVgpuTypeCreatablePlacements = append(mock.calls.GetVgpuTypeCreatablePlacements, callInfo) + mock.lockGetVgpuTypeCreatablePlacements.Unlock() + return mock.GetVgpuTypeCreatablePlacementsFunc() +} + +// GetVgpuTypeCreatablePlacementsCalls gets all the calls that were made to GetVgpuTypeCreatablePlacements. +// Check the length with: +// +// len(mockedGpuInstance.GetVgpuTypeCreatablePlacementsCalls()) +func (mock *GpuInstance) GetVgpuTypeCreatablePlacementsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuTypeCreatablePlacements.RLock() + calls = mock.calls.GetVgpuTypeCreatablePlacements + mock.lockGetVgpuTypeCreatablePlacements.RUnlock() + return calls +} + +// SetVgpuHeterogeneousMode calls SetVgpuHeterogeneousModeFunc. +func (mock *GpuInstance) SetVgpuHeterogeneousMode(vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return { + if mock.SetVgpuHeterogeneousModeFunc == nil { + panic("GpuInstance.SetVgpuHeterogeneousModeFunc: method is nil but GpuInstance.SetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + }{ + VgpuHeterogeneousMode: vgpuHeterogeneousMode, + } + mock.lockSetVgpuHeterogeneousMode.Lock() + mock.calls.SetVgpuHeterogeneousMode = append(mock.calls.SetVgpuHeterogeneousMode, callInfo) + mock.lockSetVgpuHeterogeneousMode.Unlock() + return mock.SetVgpuHeterogeneousModeFunc(vgpuHeterogeneousMode) +} + +// SetVgpuHeterogeneousModeCalls gets all the calls that were made to SetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedGpuInstance.SetVgpuHeterogeneousModeCalls()) +func (mock *GpuInstance) SetVgpuHeterogeneousModeCalls() []struct { + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode +} { + var calls []struct { + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + } + mock.lockSetVgpuHeterogeneousMode.RLock() + calls = mock.calls.SetVgpuHeterogeneousMode + mock.lockSetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// SetVgpuSchedulerState calls SetVgpuSchedulerStateFunc. +func (mock *GpuInstance) SetVgpuSchedulerState(vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return { + if mock.SetVgpuSchedulerStateFunc == nil { + panic("GpuInstance.SetVgpuSchedulerStateFunc: method is nil but GpuInstance.SetVgpuSchedulerState was just called") + } + callInfo := struct { + VgpuSchedulerState *nvml.VgpuSchedulerState + }{ + VgpuSchedulerState: vgpuSchedulerState, + } + mock.lockSetVgpuSchedulerState.Lock() + mock.calls.SetVgpuSchedulerState = append(mock.calls.SetVgpuSchedulerState, callInfo) + mock.lockSetVgpuSchedulerState.Unlock() + return mock.SetVgpuSchedulerStateFunc(vgpuSchedulerState) +} + +// SetVgpuSchedulerStateCalls gets all the calls that were made to SetVgpuSchedulerState. +// Check the length with: +// +// len(mockedGpuInstance.SetVgpuSchedulerStateCalls()) +func (mock *GpuInstance) SetVgpuSchedulerStateCalls() []struct { + VgpuSchedulerState *nvml.VgpuSchedulerState +} { + var calls []struct { + VgpuSchedulerState *nvml.VgpuSchedulerState + } + mock.lockSetVgpuSchedulerState.RLock() + calls = mock.calls.SetVgpuSchedulerState + mock.lockSetVgpuSchedulerState.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/interface.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/interface.go new file mode 100644 index 00000000..dc25ce21 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/interface.go @@ -0,0 +1,17317 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that Interface does implement nvml.Interface. +// If this is not the case, regenerate this file with moq. +var _ nvml.Interface = &Interface{} + +// Interface is a mock implementation of nvml.Interface. +// +// func TestSomethingThatUsesInterface(t *testing.T) { +// +// // make and configure a mocked nvml.Interface +// mockedInterface := &Interface{ +// ComputeInstanceDestroyFunc: func(computeInstance nvml.ComputeInstance) nvml.Return { +// panic("mock out the ComputeInstanceDestroy method") +// }, +// ComputeInstanceGetInfoFunc: func(computeInstance nvml.ComputeInstance) (nvml.ComputeInstanceInfo, nvml.Return) { +// panic("mock out the ComputeInstanceGetInfo method") +// }, +// DeviceClearAccountingPidsFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceClearAccountingPids method") +// }, +// DeviceClearCpuAffinityFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceClearCpuAffinity method") +// }, +// DeviceClearEccErrorCountsFunc: func(device nvml.Device, eccCounterType nvml.EccCounterType) nvml.Return { +// panic("mock out the DeviceClearEccErrorCounts method") +// }, +// DeviceClearFieldValuesFunc: func(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return { +// panic("mock out the DeviceClearFieldValues method") +// }, +// DeviceCreateGpuInstanceFunc: func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the DeviceCreateGpuInstance method") +// }, +// DeviceCreateGpuInstanceWithPlacementFunc: func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the DeviceCreateGpuInstanceWithPlacement method") +// }, +// DeviceDiscoverGpusFunc: func() (nvml.PciInfo, nvml.Return) { +// panic("mock out the DeviceDiscoverGpus method") +// }, +// DeviceFreezeNvLinkUtilizationCounterFunc: func(device nvml.Device, n1 int, n2 int, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceFreezeNvLinkUtilizationCounter method") +// }, +// DeviceGetAPIRestrictionFunc: func(device nvml.Device, restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetAPIRestriction method") +// }, +// DeviceGetAccountingBufferSizeFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetAccountingBufferSize method") +// }, +// DeviceGetAccountingModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetAccountingMode method") +// }, +// DeviceGetAccountingPidsFunc: func(device nvml.Device) ([]int, nvml.Return) { +// panic("mock out the DeviceGetAccountingPids method") +// }, +// DeviceGetAccountingStatsFunc: func(device nvml.Device, v uint32) (nvml.AccountingStats, nvml.Return) { +// panic("mock out the DeviceGetAccountingStats method") +// }, +// DeviceGetActiveVgpusFunc: func(device nvml.Device) ([]nvml.VgpuInstance, nvml.Return) { +// panic("mock out the DeviceGetActiveVgpus method") +// }, +// DeviceGetAdaptiveClockInfoStatusFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetAdaptiveClockInfoStatus method") +// }, +// DeviceGetAddressingModeFunc: func(device nvml.Device) (nvml.DeviceAddressingMode, nvml.Return) { +// panic("mock out the DeviceGetAddressingMode method") +// }, +// DeviceGetApplicationsClockFunc: func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the DeviceGetApplicationsClock method") +// }, +// DeviceGetArchitectureFunc: func(device nvml.Device) (nvml.DeviceArchitecture, nvml.Return) { +// panic("mock out the DeviceGetArchitecture method") +// }, +// DeviceGetAttributesFunc: func(device nvml.Device) (nvml.DeviceAttributes, nvml.Return) { +// panic("mock out the DeviceGetAttributes method") +// }, +// DeviceGetAutoBoostedClocksEnabledFunc: func(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetAutoBoostedClocksEnabled method") +// }, +// DeviceGetBAR1MemoryInfoFunc: func(device nvml.Device) (nvml.BAR1Memory, nvml.Return) { +// panic("mock out the DeviceGetBAR1MemoryInfo method") +// }, +// DeviceGetBoardIdFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetBoardId method") +// }, +// DeviceGetBoardPartNumberFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetBoardPartNumber method") +// }, +// DeviceGetBrandFunc: func(device nvml.Device) (nvml.BrandType, nvml.Return) { +// panic("mock out the DeviceGetBrand method") +// }, +// DeviceGetBridgeChipInfoFunc: func(device nvml.Device) (nvml.BridgeChipHierarchy, nvml.Return) { +// panic("mock out the DeviceGetBridgeChipInfo method") +// }, +// DeviceGetBusTypeFunc: func(device nvml.Device) (nvml.BusType, nvml.Return) { +// panic("mock out the DeviceGetBusType method") +// }, +// DeviceGetC2cModeInfoVFunc: func(device nvml.Device) nvml.C2cModeInfoHandler { +// panic("mock out the DeviceGetC2cModeInfoV method") +// }, +// DeviceGetCapabilitiesFunc: func(device nvml.Device) (nvml.DeviceCapabilities, nvml.Return) { +// panic("mock out the DeviceGetCapabilities method") +// }, +// DeviceGetClkMonStatusFunc: func(device nvml.Device) (nvml.ClkMonStatus, nvml.Return) { +// panic("mock out the DeviceGetClkMonStatus method") +// }, +// DeviceGetClockFunc: func(device nvml.Device, clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) { +// panic("mock out the DeviceGetClock method") +// }, +// DeviceGetClockInfoFunc: func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the DeviceGetClockInfo method") +// }, +// DeviceGetClockOffsetsFunc: func(device nvml.Device) (nvml.ClockOffset, nvml.Return) { +// panic("mock out the DeviceGetClockOffsets method") +// }, +// DeviceGetComputeInstanceIdFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetComputeInstanceId method") +// }, +// DeviceGetComputeModeFunc: func(device nvml.Device) (nvml.ComputeMode, nvml.Return) { +// panic("mock out the DeviceGetComputeMode method") +// }, +// DeviceGetComputeRunningProcessesFunc: func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the DeviceGetComputeRunningProcesses method") +// }, +// DeviceGetConfComputeGpuAttestationReportFunc: func(device nvml.Device, confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return { +// panic("mock out the DeviceGetConfComputeGpuAttestationReport method") +// }, +// DeviceGetConfComputeGpuCertificateFunc: func(device nvml.Device) (nvml.ConfComputeGpuCertificate, nvml.Return) { +// panic("mock out the DeviceGetConfComputeGpuCertificate method") +// }, +// DeviceGetConfComputeMemSizeInfoFunc: func(device nvml.Device) (nvml.ConfComputeMemSizeInfo, nvml.Return) { +// panic("mock out the DeviceGetConfComputeMemSizeInfo method") +// }, +// DeviceGetConfComputeProtectedMemoryUsageFunc: func(device nvml.Device) (nvml.Memory, nvml.Return) { +// panic("mock out the DeviceGetConfComputeProtectedMemoryUsage method") +// }, +// DeviceGetCoolerInfoFunc: func(device nvml.Device) (nvml.CoolerInfo, nvml.Return) { +// panic("mock out the DeviceGetCoolerInfo method") +// }, +// DeviceGetCountFunc: func() (int, nvml.Return) { +// panic("mock out the DeviceGetCount method") +// }, +// DeviceGetCpuAffinityFunc: func(device nvml.Device, n int) ([]uint, nvml.Return) { +// panic("mock out the DeviceGetCpuAffinity method") +// }, +// DeviceGetCpuAffinityWithinScopeFunc: func(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { +// panic("mock out the DeviceGetCpuAffinityWithinScope method") +// }, +// DeviceGetCreatableVgpusFunc: func(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the DeviceGetCreatableVgpus method") +// }, +// DeviceGetCudaComputeCapabilityFunc: func(device nvml.Device) (int, int, nvml.Return) { +// panic("mock out the DeviceGetCudaComputeCapability method") +// }, +// DeviceGetCurrPcieLinkGenerationFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetCurrPcieLinkGeneration method") +// }, +// DeviceGetCurrPcieLinkWidthFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetCurrPcieLinkWidth method") +// }, +// DeviceGetCurrentClockFreqsFunc: func(device nvml.Device) (nvml.DeviceCurrentClockFreqs, nvml.Return) { +// panic("mock out the DeviceGetCurrentClockFreqs method") +// }, +// DeviceGetCurrentClocksEventReasonsFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetCurrentClocksEventReasons method") +// }, +// DeviceGetCurrentClocksThrottleReasonsFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetCurrentClocksThrottleReasons method") +// }, +// DeviceGetDecoderUtilizationFunc: func(device nvml.Device) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetDecoderUtilization method") +// }, +// DeviceGetDefaultApplicationsClockFunc: func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the DeviceGetDefaultApplicationsClock method") +// }, +// DeviceGetDefaultEccModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetDefaultEccMode method") +// }, +// DeviceGetDetailedEccErrorsFunc: func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) { +// panic("mock out the DeviceGetDetailedEccErrors method") +// }, +// DeviceGetDeviceHandleFromMigDeviceHandleFunc: func(device nvml.Device) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetDeviceHandleFromMigDeviceHandle method") +// }, +// DeviceGetDisplayActiveFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetDisplayActive method") +// }, +// DeviceGetDisplayModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetDisplayMode method") +// }, +// DeviceGetDramEncryptionModeFunc: func(device nvml.Device) (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) { +// panic("mock out the DeviceGetDramEncryptionMode method") +// }, +// DeviceGetDriverModelFunc: func(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) { +// panic("mock out the DeviceGetDriverModel method") +// }, +// DeviceGetDriverModel_v2Func: func(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) { +// panic("mock out the DeviceGetDriverModel_v2 method") +// }, +// DeviceGetDynamicPstatesInfoFunc: func(device nvml.Device) (nvml.GpuDynamicPstatesInfo, nvml.Return) { +// panic("mock out the DeviceGetDynamicPstatesInfo method") +// }, +// DeviceGetEccModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetEccMode method") +// }, +// DeviceGetEncoderCapacityFunc: func(device nvml.Device, encoderType nvml.EncoderType) (int, nvml.Return) { +// panic("mock out the DeviceGetEncoderCapacity method") +// }, +// DeviceGetEncoderSessionsFunc: func(device nvml.Device) ([]nvml.EncoderSessionInfo, nvml.Return) { +// panic("mock out the DeviceGetEncoderSessions method") +// }, +// DeviceGetEncoderStatsFunc: func(device nvml.Device) (int, uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetEncoderStats method") +// }, +// DeviceGetEncoderUtilizationFunc: func(device nvml.Device) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetEncoderUtilization method") +// }, +// DeviceGetEnforcedPowerLimitFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetEnforcedPowerLimit method") +// }, +// DeviceGetFBCSessionsFunc: func(device nvml.Device) ([]nvml.FBCSessionInfo, nvml.Return) { +// panic("mock out the DeviceGetFBCSessions method") +// }, +// DeviceGetFBCStatsFunc: func(device nvml.Device) (nvml.FBCStats, nvml.Return) { +// panic("mock out the DeviceGetFBCStats method") +// }, +// DeviceGetFanControlPolicy_v2Func: func(device nvml.Device, n int) (nvml.FanControlPolicy, nvml.Return) { +// panic("mock out the DeviceGetFanControlPolicy_v2 method") +// }, +// DeviceGetFanSpeedFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetFanSpeed method") +// }, +// DeviceGetFanSpeedRPMFunc: func(device nvml.Device) (nvml.FanSpeedInfo, nvml.Return) { +// panic("mock out the DeviceGetFanSpeedRPM method") +// }, +// DeviceGetFanSpeed_v2Func: func(device nvml.Device, n int) (uint32, nvml.Return) { +// panic("mock out the DeviceGetFanSpeed_v2 method") +// }, +// DeviceGetFieldValuesFunc: func(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return { +// panic("mock out the DeviceGetFieldValues method") +// }, +// DeviceGetGpcClkMinMaxVfOffsetFunc: func(device nvml.Device) (int, int, nvml.Return) { +// panic("mock out the DeviceGetGpcClkMinMaxVfOffset method") +// }, +// DeviceGetGpcClkVfOffsetFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetGpcClkVfOffset method") +// }, +// DeviceGetGpuFabricInfoFunc: func(device nvml.Device) (nvml.GpuFabricInfo, nvml.Return) { +// panic("mock out the DeviceGetGpuFabricInfo method") +// }, +// DeviceGetGpuFabricInfoVFunc: func(device nvml.Device) nvml.GpuFabricInfoHandler { +// panic("mock out the DeviceGetGpuFabricInfoV method") +// }, +// DeviceGetGpuInstanceByIdFunc: func(device nvml.Device, n int) (nvml.GpuInstance, nvml.Return) { +// panic("mock out the DeviceGetGpuInstanceById method") +// }, +// DeviceGetGpuInstanceIdFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetGpuInstanceId method") +// }, +// DeviceGetGpuInstancePossiblePlacementsFunc: func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) { +// panic("mock out the DeviceGetGpuInstancePossiblePlacements method") +// }, +// DeviceGetGpuInstanceProfileInfoFunc: func(device nvml.Device, n int) (nvml.GpuInstanceProfileInfo, nvml.Return) { +// panic("mock out the DeviceGetGpuInstanceProfileInfo method") +// }, +// DeviceGetGpuInstanceProfileInfoByIdVFunc: func(device nvml.Device, n int) nvml.GpuInstanceProfileInfoByIdHandler { +// panic("mock out the DeviceGetGpuInstanceProfileInfoByIdV method") +// }, +// DeviceGetGpuInstanceProfileInfoVFunc: func(device nvml.Device, n int) nvml.GpuInstanceProfileInfoHandler { +// panic("mock out the DeviceGetGpuInstanceProfileInfoV method") +// }, +// DeviceGetGpuInstanceRemainingCapacityFunc: func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) { +// panic("mock out the DeviceGetGpuInstanceRemainingCapacity method") +// }, +// DeviceGetGpuInstancesFunc: func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { +// panic("mock out the DeviceGetGpuInstances method") +// }, +// DeviceGetGpuMaxPcieLinkGenerationFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetGpuMaxPcieLinkGeneration method") +// }, +// DeviceGetGpuOperationModeFunc: func(device nvml.Device) (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) { +// panic("mock out the DeviceGetGpuOperationMode method") +// }, +// DeviceGetGraphicsRunningProcessesFunc: func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the DeviceGetGraphicsRunningProcesses method") +// }, +// DeviceGetGridLicensableFeaturesFunc: func(device nvml.Device) (nvml.GridLicensableFeatures, nvml.Return) { +// panic("mock out the DeviceGetGridLicensableFeatures method") +// }, +// DeviceGetGspFirmwareModeFunc: func(device nvml.Device) (bool, bool, nvml.Return) { +// panic("mock out the DeviceGetGspFirmwareMode method") +// }, +// DeviceGetGspFirmwareVersionFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetGspFirmwareVersion method") +// }, +// DeviceGetHandleByIndexFunc: func(n int) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetHandleByIndex method") +// }, +// DeviceGetHandleByPciBusIdFunc: func(s string) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetHandleByPciBusId method") +// }, +// DeviceGetHandleBySerialFunc: func(s string) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetHandleBySerial method") +// }, +// DeviceGetHandleByUUIDFunc: func(s string) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetHandleByUUID method") +// }, +// DeviceGetHandleByUUIDVFunc: func(uUID *nvml.UUID) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetHandleByUUIDV method") +// }, +// DeviceGetHostVgpuModeFunc: func(device nvml.Device) (nvml.HostVgpuMode, nvml.Return) { +// panic("mock out the DeviceGetHostVgpuMode method") +// }, +// DeviceGetIndexFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetIndex method") +// }, +// DeviceGetInforomConfigurationChecksumFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetInforomConfigurationChecksum method") +// }, +// DeviceGetInforomImageVersionFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetInforomImageVersion method") +// }, +// DeviceGetInforomVersionFunc: func(device nvml.Device, inforomObject nvml.InforomObject) (string, nvml.Return) { +// panic("mock out the DeviceGetInforomVersion method") +// }, +// DeviceGetIrqNumFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetIrqNum method") +// }, +// DeviceGetJpgUtilizationFunc: func(device nvml.Device) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetJpgUtilization method") +// }, +// DeviceGetLastBBXFlushTimeFunc: func(device nvml.Device) (uint64, uint, nvml.Return) { +// panic("mock out the DeviceGetLastBBXFlushTime method") +// }, +// DeviceGetMPSComputeRunningProcessesFunc: func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { +// panic("mock out the DeviceGetMPSComputeRunningProcesses method") +// }, +// DeviceGetMarginTemperatureFunc: func(device nvml.Device) (nvml.MarginTemperature, nvml.Return) { +// panic("mock out the DeviceGetMarginTemperature method") +// }, +// DeviceGetMaxClockInfoFunc: func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the DeviceGetMaxClockInfo method") +// }, +// DeviceGetMaxCustomerBoostClockFunc: func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { +// panic("mock out the DeviceGetMaxCustomerBoostClock method") +// }, +// DeviceGetMaxMigDeviceCountFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMaxMigDeviceCount method") +// }, +// DeviceGetMaxPcieLinkGenerationFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMaxPcieLinkGeneration method") +// }, +// DeviceGetMaxPcieLinkWidthFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMaxPcieLinkWidth method") +// }, +// DeviceGetMemClkMinMaxVfOffsetFunc: func(device nvml.Device) (int, int, nvml.Return) { +// panic("mock out the DeviceGetMemClkMinMaxVfOffset method") +// }, +// DeviceGetMemClkVfOffsetFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMemClkVfOffset method") +// }, +// DeviceGetMemoryAffinityFunc: func(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { +// panic("mock out the DeviceGetMemoryAffinity method") +// }, +// DeviceGetMemoryBusWidthFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetMemoryBusWidth method") +// }, +// DeviceGetMemoryErrorCounterFunc: func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) { +// panic("mock out the DeviceGetMemoryErrorCounter method") +// }, +// DeviceGetMemoryInfoFunc: func(device nvml.Device) (nvml.Memory, nvml.Return) { +// panic("mock out the DeviceGetMemoryInfo method") +// }, +// DeviceGetMemoryInfo_v2Func: func(device nvml.Device) (nvml.Memory_v2, nvml.Return) { +// panic("mock out the DeviceGetMemoryInfo_v2 method") +// }, +// DeviceGetMigDeviceHandleByIndexFunc: func(device nvml.Device, n int) (nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetMigDeviceHandleByIndex method") +// }, +// DeviceGetMigModeFunc: func(device nvml.Device) (int, int, nvml.Return) { +// panic("mock out the DeviceGetMigMode method") +// }, +// DeviceGetMinMaxClockOfPStateFunc: func(device nvml.Device, clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetMinMaxClockOfPState method") +// }, +// DeviceGetMinMaxFanSpeedFunc: func(device nvml.Device) (int, int, nvml.Return) { +// panic("mock out the DeviceGetMinMaxFanSpeed method") +// }, +// DeviceGetMinorNumberFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMinorNumber method") +// }, +// DeviceGetModuleIdFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetModuleId method") +// }, +// DeviceGetMultiGpuBoardFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetMultiGpuBoard method") +// }, +// DeviceGetNameFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetName method") +// }, +// DeviceGetNumFansFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetNumFans method") +// }, +// DeviceGetNumGpuCoresFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetNumGpuCores method") +// }, +// DeviceGetNumaNodeIdFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetNumaNodeId method") +// }, +// DeviceGetNvLinkCapabilityFunc: func(device nvml.Device, n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) { +// panic("mock out the DeviceGetNvLinkCapability method") +// }, +// DeviceGetNvLinkErrorCounterFunc: func(device nvml.Device, n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) { +// panic("mock out the DeviceGetNvLinkErrorCounter method") +// }, +// DeviceGetNvLinkInfoFunc: func(device nvml.Device) nvml.NvLinkInfoHandler { +// panic("mock out the DeviceGetNvLinkInfo method") +// }, +// DeviceGetNvLinkRemoteDeviceTypeFunc: func(device nvml.Device, n int) (nvml.IntNvLinkDeviceType, nvml.Return) { +// panic("mock out the DeviceGetNvLinkRemoteDeviceType method") +// }, +// DeviceGetNvLinkRemotePciInfoFunc: func(device nvml.Device, n int) (nvml.PciInfo, nvml.Return) { +// panic("mock out the DeviceGetNvLinkRemotePciInfo method") +// }, +// DeviceGetNvLinkStateFunc: func(device nvml.Device, n int) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetNvLinkState method") +// }, +// DeviceGetNvLinkUtilizationControlFunc: func(device nvml.Device, n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) { +// panic("mock out the DeviceGetNvLinkUtilizationControl method") +// }, +// DeviceGetNvLinkUtilizationCounterFunc: func(device nvml.Device, n1 int, n2 int) (uint64, uint64, nvml.Return) { +// panic("mock out the DeviceGetNvLinkUtilizationCounter method") +// }, +// DeviceGetNvLinkVersionFunc: func(device nvml.Device, n int) (uint32, nvml.Return) { +// panic("mock out the DeviceGetNvLinkVersion method") +// }, +// DeviceGetNvlinkBwModeFunc: func(device nvml.Device) (nvml.NvlinkGetBwMode, nvml.Return) { +// panic("mock out the DeviceGetNvlinkBwMode method") +// }, +// DeviceGetNvlinkSupportedBwModesFunc: func(device nvml.Device) (nvml.NvlinkSupportedBwModes, nvml.Return) { +// panic("mock out the DeviceGetNvlinkSupportedBwModes method") +// }, +// DeviceGetOfaUtilizationFunc: func(device nvml.Device) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetOfaUtilization method") +// }, +// DeviceGetP2PStatusFunc: func(device1 nvml.Device, device2 nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) { +// panic("mock out the DeviceGetP2PStatus method") +// }, +// DeviceGetPciInfoFunc: func(device nvml.Device) (nvml.PciInfo, nvml.Return) { +// panic("mock out the DeviceGetPciInfo method") +// }, +// DeviceGetPciInfoExtFunc: func(device nvml.Device) (nvml.PciInfoExt, nvml.Return) { +// panic("mock out the DeviceGetPciInfoExt method") +// }, +// DeviceGetPcieLinkMaxSpeedFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetPcieLinkMaxSpeed method") +// }, +// DeviceGetPcieReplayCounterFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetPcieReplayCounter method") +// }, +// DeviceGetPcieSpeedFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceGetPcieSpeed method") +// }, +// DeviceGetPcieThroughputFunc: func(device nvml.Device, pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) { +// panic("mock out the DeviceGetPcieThroughput method") +// }, +// DeviceGetPdiFunc: func(device nvml.Device) (nvml.Pdi, nvml.Return) { +// panic("mock out the DeviceGetPdi method") +// }, +// DeviceGetPerformanceModesFunc: func(device nvml.Device) (nvml.DevicePerfModes, nvml.Return) { +// panic("mock out the DeviceGetPerformanceModes method") +// }, +// DeviceGetPerformanceStateFunc: func(device nvml.Device) (nvml.Pstates, nvml.Return) { +// panic("mock out the DeviceGetPerformanceState method") +// }, +// DeviceGetPersistenceModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetPersistenceMode method") +// }, +// DeviceGetPgpuMetadataStringFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetPgpuMetadataString method") +// }, +// DeviceGetPlatformInfoFunc: func(device nvml.Device) (nvml.PlatformInfo, nvml.Return) { +// panic("mock out the DeviceGetPlatformInfo method") +// }, +// DeviceGetPowerManagementDefaultLimitFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetPowerManagementDefaultLimit method") +// }, +// DeviceGetPowerManagementLimitFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetPowerManagementLimit method") +// }, +// DeviceGetPowerManagementLimitConstraintsFunc: func(device nvml.Device) (uint32, uint32, nvml.Return) { +// panic("mock out the DeviceGetPowerManagementLimitConstraints method") +// }, +// DeviceGetPowerManagementModeFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetPowerManagementMode method") +// }, +// DeviceGetPowerMizerMode_v1Func: func(device nvml.Device) (nvml.DevicePowerMizerModes_v1, nvml.Return) { +// panic("mock out the DeviceGetPowerMizerMode_v1 method") +// }, +// DeviceGetPowerSourceFunc: func(device nvml.Device) (nvml.PowerSource, nvml.Return) { +// panic("mock out the DeviceGetPowerSource method") +// }, +// DeviceGetPowerStateFunc: func(device nvml.Device) (nvml.Pstates, nvml.Return) { +// panic("mock out the DeviceGetPowerState method") +// }, +// DeviceGetPowerUsageFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the DeviceGetPowerUsage method") +// }, +// DeviceGetProcessUtilizationFunc: func(device nvml.Device, v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) { +// panic("mock out the DeviceGetProcessUtilization method") +// }, +// DeviceGetProcessesUtilizationInfoFunc: func(device nvml.Device) (nvml.ProcessesUtilizationInfo, nvml.Return) { +// panic("mock out the DeviceGetProcessesUtilizationInfo method") +// }, +// DeviceGetRemappedRowsFunc: func(device nvml.Device) (int, int, bool, bool, nvml.Return) { +// panic("mock out the DeviceGetRemappedRows method") +// }, +// DeviceGetRepairStatusFunc: func(device nvml.Device) (nvml.RepairStatus, nvml.Return) { +// panic("mock out the DeviceGetRepairStatus method") +// }, +// DeviceGetRetiredPagesFunc: func(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) { +// panic("mock out the DeviceGetRetiredPages method") +// }, +// DeviceGetRetiredPagesPendingStatusFunc: func(device nvml.Device) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceGetRetiredPagesPendingStatus method") +// }, +// DeviceGetRetiredPages_v2Func: func(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) { +// panic("mock out the DeviceGetRetiredPages_v2 method") +// }, +// DeviceGetRowRemapperHistogramFunc: func(device nvml.Device) (nvml.RowRemapperHistogramValues, nvml.Return) { +// panic("mock out the DeviceGetRowRemapperHistogram method") +// }, +// DeviceGetRunningProcessDetailListFunc: func(device nvml.Device) (nvml.ProcessDetailList, nvml.Return) { +// panic("mock out the DeviceGetRunningProcessDetailList method") +// }, +// DeviceGetSamplesFunc: func(device nvml.Device, samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) { +// panic("mock out the DeviceGetSamples method") +// }, +// DeviceGetSerialFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetSerial method") +// }, +// DeviceGetSramEccErrorStatusFunc: func(device nvml.Device) (nvml.EccSramErrorStatus, nvml.Return) { +// panic("mock out the DeviceGetSramEccErrorStatus method") +// }, +// DeviceGetSramUniqueUncorrectedEccErrorCountsFunc: func(device nvml.Device, eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return { +// panic("mock out the DeviceGetSramUniqueUncorrectedEccErrorCounts method") +// }, +// DeviceGetSupportedClocksEventReasonsFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetSupportedClocksEventReasons method") +// }, +// DeviceGetSupportedClocksThrottleReasonsFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetSupportedClocksThrottleReasons method") +// }, +// DeviceGetSupportedEventTypesFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetSupportedEventTypes method") +// }, +// DeviceGetSupportedGraphicsClocksFunc: func(device nvml.Device, n int) (int, uint32, nvml.Return) { +// panic("mock out the DeviceGetSupportedGraphicsClocks method") +// }, +// DeviceGetSupportedMemoryClocksFunc: func(device nvml.Device) (int, uint32, nvml.Return) { +// panic("mock out the DeviceGetSupportedMemoryClocks method") +// }, +// DeviceGetSupportedPerformanceStatesFunc: func(device nvml.Device) ([]nvml.Pstates, nvml.Return) { +// panic("mock out the DeviceGetSupportedPerformanceStates method") +// }, +// DeviceGetSupportedVgpusFunc: func(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the DeviceGetSupportedVgpus method") +// }, +// DeviceGetTargetFanSpeedFunc: func(device nvml.Device, n int) (int, nvml.Return) { +// panic("mock out the DeviceGetTargetFanSpeed method") +// }, +// DeviceGetTemperatureFunc: func(device nvml.Device, temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) { +// panic("mock out the DeviceGetTemperature method") +// }, +// DeviceGetTemperatureThresholdFunc: func(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) { +// panic("mock out the DeviceGetTemperatureThreshold method") +// }, +// DeviceGetTemperatureVFunc: func(device nvml.Device) nvml.TemperatureHandler { +// panic("mock out the DeviceGetTemperatureV method") +// }, +// DeviceGetThermalSettingsFunc: func(device nvml.Device, v uint32) (nvml.GpuThermalSettings, nvml.Return) { +// panic("mock out the DeviceGetThermalSettings method") +// }, +// DeviceGetTopologyCommonAncestorFunc: func(device1 nvml.Device, device2 nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) { +// panic("mock out the DeviceGetTopologyCommonAncestor method") +// }, +// DeviceGetTopologyNearestGpusFunc: func(device nvml.Device, gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) { +// panic("mock out the DeviceGetTopologyNearestGpus method") +// }, +// DeviceGetTotalEccErrorsFunc: func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) { +// panic("mock out the DeviceGetTotalEccErrors method") +// }, +// DeviceGetTotalEnergyConsumptionFunc: func(device nvml.Device) (uint64, nvml.Return) { +// panic("mock out the DeviceGetTotalEnergyConsumption method") +// }, +// DeviceGetUUIDFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetUUID method") +// }, +// DeviceGetUtilizationRatesFunc: func(device nvml.Device) (nvml.Utilization, nvml.Return) { +// panic("mock out the DeviceGetUtilizationRates method") +// }, +// DeviceGetVbiosVersionFunc: func(device nvml.Device) (string, nvml.Return) { +// panic("mock out the DeviceGetVbiosVersion method") +// }, +// DeviceGetVgpuCapabilitiesFunc: func(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) { +// panic("mock out the DeviceGetVgpuCapabilities method") +// }, +// DeviceGetVgpuHeterogeneousModeFunc: func(device nvml.Device) (nvml.VgpuHeterogeneousMode, nvml.Return) { +// panic("mock out the DeviceGetVgpuHeterogeneousMode method") +// }, +// DeviceGetVgpuInstancesUtilizationInfoFunc: func(device nvml.Device) (nvml.VgpuInstancesUtilizationInfo, nvml.Return) { +// panic("mock out the DeviceGetVgpuInstancesUtilizationInfo method") +// }, +// DeviceGetVgpuMetadataFunc: func(device nvml.Device) (nvml.VgpuPgpuMetadata, nvml.Return) { +// panic("mock out the DeviceGetVgpuMetadata method") +// }, +// DeviceGetVgpuProcessUtilizationFunc: func(device nvml.Device, v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) { +// panic("mock out the DeviceGetVgpuProcessUtilization method") +// }, +// DeviceGetVgpuProcessesUtilizationInfoFunc: func(device nvml.Device) (nvml.VgpuProcessesUtilizationInfo, nvml.Return) { +// panic("mock out the DeviceGetVgpuProcessesUtilizationInfo method") +// }, +// DeviceGetVgpuSchedulerCapabilitiesFunc: func(device nvml.Device) (nvml.VgpuSchedulerCapabilities, nvml.Return) { +// panic("mock out the DeviceGetVgpuSchedulerCapabilities method") +// }, +// DeviceGetVgpuSchedulerLogFunc: func(device nvml.Device) (nvml.VgpuSchedulerLog, nvml.Return) { +// panic("mock out the DeviceGetVgpuSchedulerLog method") +// }, +// DeviceGetVgpuSchedulerStateFunc: func(device nvml.Device) (nvml.VgpuSchedulerGetState, nvml.Return) { +// panic("mock out the DeviceGetVgpuSchedulerState method") +// }, +// DeviceGetVgpuTypeCreatablePlacementsFunc: func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the DeviceGetVgpuTypeCreatablePlacements method") +// }, +// DeviceGetVgpuTypeSupportedPlacementsFunc: func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the DeviceGetVgpuTypeSupportedPlacements method") +// }, +// DeviceGetVgpuUtilizationFunc: func(device nvml.Device, v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) { +// panic("mock out the DeviceGetVgpuUtilization method") +// }, +// DeviceGetViolationStatusFunc: func(device nvml.Device, perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) { +// panic("mock out the DeviceGetViolationStatus method") +// }, +// DeviceGetVirtualizationModeFunc: func(device nvml.Device) (nvml.GpuVirtualizationMode, nvml.Return) { +// panic("mock out the DeviceGetVirtualizationMode method") +// }, +// DeviceIsMigDeviceHandleFunc: func(device nvml.Device) (bool, nvml.Return) { +// panic("mock out the DeviceIsMigDeviceHandle method") +// }, +// DeviceModifyDrainStateFunc: func(pciInfo *nvml.PciInfo, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceModifyDrainState method") +// }, +// DeviceOnSameBoardFunc: func(device1 nvml.Device, device2 nvml.Device) (int, nvml.Return) { +// panic("mock out the DeviceOnSameBoard method") +// }, +// DevicePowerSmoothingActivatePresetProfileFunc: func(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { +// panic("mock out the DevicePowerSmoothingActivatePresetProfile method") +// }, +// DevicePowerSmoothingSetStateFunc: func(device nvml.Device, powerSmoothingState *nvml.PowerSmoothingState) nvml.Return { +// panic("mock out the DevicePowerSmoothingSetState method") +// }, +// DevicePowerSmoothingUpdatePresetProfileParamFunc: func(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { +// panic("mock out the DevicePowerSmoothingUpdatePresetProfileParam method") +// }, +// DeviceQueryDrainStateFunc: func(pciInfo *nvml.PciInfo) (nvml.EnableState, nvml.Return) { +// panic("mock out the DeviceQueryDrainState method") +// }, +// DeviceReadWritePRM_v1Func: func(device nvml.Device, pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return { +// panic("mock out the DeviceReadWritePRM_v1 method") +// }, +// DeviceRegisterEventsFunc: func(device nvml.Device, v uint64, eventSet nvml.EventSet) nvml.Return { +// panic("mock out the DeviceRegisterEvents method") +// }, +// DeviceRemoveGpuFunc: func(pciInfo *nvml.PciInfo) nvml.Return { +// panic("mock out the DeviceRemoveGpu method") +// }, +// DeviceRemoveGpu_v2Func: func(pciInfo *nvml.PciInfo, detachGpuState nvml.DetachGpuState, pcieLinkState nvml.PcieLinkState) nvml.Return { +// panic("mock out the DeviceRemoveGpu_v2 method") +// }, +// DeviceResetApplicationsClocksFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceResetApplicationsClocks method") +// }, +// DeviceResetGpuLockedClocksFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceResetGpuLockedClocks method") +// }, +// DeviceResetMemoryLockedClocksFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceResetMemoryLockedClocks method") +// }, +// DeviceResetNvLinkErrorCountersFunc: func(device nvml.Device, n int) nvml.Return { +// panic("mock out the DeviceResetNvLinkErrorCounters method") +// }, +// DeviceResetNvLinkUtilizationCounterFunc: func(device nvml.Device, n1 int, n2 int) nvml.Return { +// panic("mock out the DeviceResetNvLinkUtilizationCounter method") +// }, +// DeviceSetAPIRestrictionFunc: func(device nvml.Device, restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetAPIRestriction method") +// }, +// DeviceSetAccountingModeFunc: func(device nvml.Device, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetAccountingMode method") +// }, +// DeviceSetApplicationsClocksFunc: func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the DeviceSetApplicationsClocks method") +// }, +// DeviceSetAutoBoostedClocksEnabledFunc: func(device nvml.Device, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetAutoBoostedClocksEnabled method") +// }, +// DeviceSetClockOffsetsFunc: func(device nvml.Device, clockOffset nvml.ClockOffset) nvml.Return { +// panic("mock out the DeviceSetClockOffsets method") +// }, +// DeviceSetComputeModeFunc: func(device nvml.Device, computeMode nvml.ComputeMode) nvml.Return { +// panic("mock out the DeviceSetComputeMode method") +// }, +// DeviceSetConfComputeUnprotectedMemSizeFunc: func(device nvml.Device, v uint64) nvml.Return { +// panic("mock out the DeviceSetConfComputeUnprotectedMemSize method") +// }, +// DeviceSetCpuAffinityFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceSetCpuAffinity method") +// }, +// DeviceSetDefaultAutoBoostedClocksEnabledFunc: func(device nvml.Device, enableState nvml.EnableState, v uint32) nvml.Return { +// panic("mock out the DeviceSetDefaultAutoBoostedClocksEnabled method") +// }, +// DeviceSetDefaultFanSpeed_v2Func: func(device nvml.Device, n int) nvml.Return { +// panic("mock out the DeviceSetDefaultFanSpeed_v2 method") +// }, +// DeviceSetDramEncryptionModeFunc: func(device nvml.Device, dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return { +// panic("mock out the DeviceSetDramEncryptionMode method") +// }, +// DeviceSetDriverModelFunc: func(device nvml.Device, driverModel nvml.DriverModel, v uint32) nvml.Return { +// panic("mock out the DeviceSetDriverModel method") +// }, +// DeviceSetEccModeFunc: func(device nvml.Device, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetEccMode method") +// }, +// DeviceSetFanControlPolicyFunc: func(device nvml.Device, n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return { +// panic("mock out the DeviceSetFanControlPolicy method") +// }, +// DeviceSetFanSpeed_v2Func: func(device nvml.Device, n1 int, n2 int) nvml.Return { +// panic("mock out the DeviceSetFanSpeed_v2 method") +// }, +// DeviceSetGpcClkVfOffsetFunc: func(device nvml.Device, n int) nvml.Return { +// panic("mock out the DeviceSetGpcClkVfOffset method") +// }, +// DeviceSetGpuLockedClocksFunc: func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the DeviceSetGpuLockedClocks method") +// }, +// DeviceSetGpuOperationModeFunc: func(device nvml.Device, gpuOperationMode nvml.GpuOperationMode) nvml.Return { +// panic("mock out the DeviceSetGpuOperationMode method") +// }, +// DeviceSetMemClkVfOffsetFunc: func(device nvml.Device, n int) nvml.Return { +// panic("mock out the DeviceSetMemClkVfOffset method") +// }, +// DeviceSetMemoryLockedClocksFunc: func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { +// panic("mock out the DeviceSetMemoryLockedClocks method") +// }, +// DeviceSetMigModeFunc: func(device nvml.Device, n int) (nvml.Return, nvml.Return) { +// panic("mock out the DeviceSetMigMode method") +// }, +// DeviceSetNvLinkDeviceLowPowerThresholdFunc: func(device nvml.Device, nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return { +// panic("mock out the DeviceSetNvLinkDeviceLowPowerThreshold method") +// }, +// DeviceSetNvLinkUtilizationControlFunc: func(device nvml.Device, n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return { +// panic("mock out the DeviceSetNvLinkUtilizationControl method") +// }, +// DeviceSetNvlinkBwModeFunc: func(device nvml.Device, nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return { +// panic("mock out the DeviceSetNvlinkBwMode method") +// }, +// DeviceSetPersistenceModeFunc: func(device nvml.Device, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetPersistenceMode method") +// }, +// DeviceSetPowerManagementLimitFunc: func(device nvml.Device, v uint32) nvml.Return { +// panic("mock out the DeviceSetPowerManagementLimit method") +// }, +// DeviceSetPowerManagementLimit_v2Func: func(device nvml.Device, powerValue_v2 *nvml.PowerValue_v2) nvml.Return { +// panic("mock out the DeviceSetPowerManagementLimit_v2 method") +// }, +// DeviceSetTemperatureThresholdFunc: func(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return { +// panic("mock out the DeviceSetTemperatureThreshold method") +// }, +// DeviceSetVgpuCapabilitiesFunc: func(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return { +// panic("mock out the DeviceSetVgpuCapabilities method") +// }, +// DeviceSetVgpuHeterogeneousModeFunc: func(device nvml.Device, vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return { +// panic("mock out the DeviceSetVgpuHeterogeneousMode method") +// }, +// DeviceSetVgpuSchedulerStateFunc: func(device nvml.Device, vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return { +// panic("mock out the DeviceSetVgpuSchedulerState method") +// }, +// DeviceSetVirtualizationModeFunc: func(device nvml.Device, gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return { +// panic("mock out the DeviceSetVirtualizationMode method") +// }, +// DeviceValidateInforomFunc: func(device nvml.Device) nvml.Return { +// panic("mock out the DeviceValidateInforom method") +// }, +// DeviceWorkloadPowerProfileClearRequestedProfilesFunc: func(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { +// panic("mock out the DeviceWorkloadPowerProfileClearRequestedProfiles method") +// }, +// DeviceWorkloadPowerProfileGetCurrentProfilesFunc: func(device nvml.Device) (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) { +// panic("mock out the DeviceWorkloadPowerProfileGetCurrentProfiles method") +// }, +// DeviceWorkloadPowerProfileGetProfilesInfoFunc: func(device nvml.Device) (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) { +// panic("mock out the DeviceWorkloadPowerProfileGetProfilesInfo method") +// }, +// DeviceWorkloadPowerProfileSetRequestedProfilesFunc: func(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { +// panic("mock out the DeviceWorkloadPowerProfileSetRequestedProfiles method") +// }, +// ErrorStringFunc: func(returnMoqParam nvml.Return) string { +// panic("mock out the ErrorString method") +// }, +// EventSetCreateFunc: func() (nvml.EventSet, nvml.Return) { +// panic("mock out the EventSetCreate method") +// }, +// EventSetFreeFunc: func(eventSet nvml.EventSet) nvml.Return { +// panic("mock out the EventSetFree method") +// }, +// EventSetWaitFunc: func(eventSet nvml.EventSet, v uint32) (nvml.EventData, nvml.Return) { +// panic("mock out the EventSetWait method") +// }, +// ExtensionsFunc: func() nvml.ExtendedInterface { +// panic("mock out the Extensions method") +// }, +// GetExcludedDeviceCountFunc: func() (int, nvml.Return) { +// panic("mock out the GetExcludedDeviceCount method") +// }, +// GetExcludedDeviceInfoByIndexFunc: func(n int) (nvml.ExcludedDeviceInfo, nvml.Return) { +// panic("mock out the GetExcludedDeviceInfoByIndex method") +// }, +// GetVgpuCompatibilityFunc: func(vgpuMetadata *nvml.VgpuMetadata, vgpuPgpuMetadata *nvml.VgpuPgpuMetadata) (nvml.VgpuPgpuCompatibility, nvml.Return) { +// panic("mock out the GetVgpuCompatibility method") +// }, +// GetVgpuDriverCapabilitiesFunc: func(vgpuDriverCapability nvml.VgpuDriverCapability) (bool, nvml.Return) { +// panic("mock out the GetVgpuDriverCapabilities method") +// }, +// GetVgpuVersionFunc: func() (nvml.VgpuVersion, nvml.VgpuVersion, nvml.Return) { +// panic("mock out the GetVgpuVersion method") +// }, +// GpmMetricsGetFunc: func(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.Return { +// panic("mock out the GpmMetricsGet method") +// }, +// GpmMetricsGetVFunc: func(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.GpmMetricsGetVType { +// panic("mock out the GpmMetricsGetV method") +// }, +// GpmMigSampleGetFunc: func(device nvml.Device, n int, gpmSample nvml.GpmSample) nvml.Return { +// panic("mock out the GpmMigSampleGet method") +// }, +// GpmQueryDeviceSupportFunc: func(device nvml.Device) (nvml.GpmSupport, nvml.Return) { +// panic("mock out the GpmQueryDeviceSupport method") +// }, +// GpmQueryDeviceSupportVFunc: func(device nvml.Device) nvml.GpmSupportV { +// panic("mock out the GpmQueryDeviceSupportV method") +// }, +// GpmQueryIfStreamingEnabledFunc: func(device nvml.Device) (uint32, nvml.Return) { +// panic("mock out the GpmQueryIfStreamingEnabled method") +// }, +// GpmSampleAllocFunc: func() (nvml.GpmSample, nvml.Return) { +// panic("mock out the GpmSampleAlloc method") +// }, +// GpmSampleFreeFunc: func(gpmSample nvml.GpmSample) nvml.Return { +// panic("mock out the GpmSampleFree method") +// }, +// GpmSampleGetFunc: func(device nvml.Device, gpmSample nvml.GpmSample) nvml.Return { +// panic("mock out the GpmSampleGet method") +// }, +// GpmSetStreamingEnabledFunc: func(device nvml.Device, v uint32) nvml.Return { +// panic("mock out the GpmSetStreamingEnabled method") +// }, +// GpuInstanceCreateComputeInstanceFunc: func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GpuInstanceCreateComputeInstance method") +// }, +// GpuInstanceCreateComputeInstanceWithPlacementFunc: func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GpuInstanceCreateComputeInstanceWithPlacement method") +// }, +// GpuInstanceDestroyFunc: func(gpuInstance nvml.GpuInstance) nvml.Return { +// panic("mock out the GpuInstanceDestroy method") +// }, +// GpuInstanceGetActiveVgpusFunc: func(gpuInstance nvml.GpuInstance) (nvml.ActiveVgpuInstanceInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetActiveVgpus method") +// }, +// GpuInstanceGetComputeInstanceByIdFunc: func(gpuInstance nvml.GpuInstance, n int) (nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GpuInstanceGetComputeInstanceById method") +// }, +// GpuInstanceGetComputeInstancePossiblePlacementsFunc: func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) { +// panic("mock out the GpuInstanceGetComputeInstancePossiblePlacements method") +// }, +// GpuInstanceGetComputeInstanceProfileInfoFunc: func(gpuInstance nvml.GpuInstance, n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetComputeInstanceProfileInfo method") +// }, +// GpuInstanceGetComputeInstanceProfileInfoVFunc: func(gpuInstance nvml.GpuInstance, n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler { +// panic("mock out the GpuInstanceGetComputeInstanceProfileInfoV method") +// }, +// GpuInstanceGetComputeInstanceRemainingCapacityFunc: func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) { +// panic("mock out the GpuInstanceGetComputeInstanceRemainingCapacity method") +// }, +// GpuInstanceGetComputeInstancesFunc: func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) { +// panic("mock out the GpuInstanceGetComputeInstances method") +// }, +// GpuInstanceGetCreatableVgpusFunc: func(gpuInstance nvml.GpuInstance) (nvml.VgpuTypeIdInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetCreatableVgpus method") +// }, +// GpuInstanceGetInfoFunc: func(gpuInstance nvml.GpuInstance) (nvml.GpuInstanceInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetInfo method") +// }, +// GpuInstanceGetVgpuHeterogeneousModeFunc: func(gpuInstance nvml.GpuInstance) (nvml.VgpuHeterogeneousMode, nvml.Return) { +// panic("mock out the GpuInstanceGetVgpuHeterogeneousMode method") +// }, +// GpuInstanceGetVgpuSchedulerLogFunc: func(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerLogInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetVgpuSchedulerLog method") +// }, +// GpuInstanceGetVgpuSchedulerStateFunc: func(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerStateInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetVgpuSchedulerState method") +// }, +// GpuInstanceGetVgpuTypeCreatablePlacementsFunc: func(gpuInstance nvml.GpuInstance) (nvml.VgpuCreatablePlacementInfo, nvml.Return) { +// panic("mock out the GpuInstanceGetVgpuTypeCreatablePlacements method") +// }, +// GpuInstanceSetVgpuHeterogeneousModeFunc: func(gpuInstance nvml.GpuInstance, vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return { +// panic("mock out the GpuInstanceSetVgpuHeterogeneousMode method") +// }, +// GpuInstanceSetVgpuSchedulerStateFunc: func(gpuInstance nvml.GpuInstance, vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return { +// panic("mock out the GpuInstanceSetVgpuSchedulerState method") +// }, +// InitFunc: func() nvml.Return { +// panic("mock out the Init method") +// }, +// InitWithFlagsFunc: func(v uint32) nvml.Return { +// panic("mock out the InitWithFlags method") +// }, +// SetVgpuVersionFunc: func(vgpuVersion *nvml.VgpuVersion) nvml.Return { +// panic("mock out the SetVgpuVersion method") +// }, +// ShutdownFunc: func() nvml.Return { +// panic("mock out the Shutdown method") +// }, +// SystemEventSetCreateFunc: func(systemEventSetCreateRequest *nvml.SystemEventSetCreateRequest) nvml.Return { +// panic("mock out the SystemEventSetCreate method") +// }, +// SystemEventSetFreeFunc: func(systemEventSetFreeRequest *nvml.SystemEventSetFreeRequest) nvml.Return { +// panic("mock out the SystemEventSetFree method") +// }, +// SystemEventSetWaitFunc: func(systemEventSetWaitRequest *nvml.SystemEventSetWaitRequest) nvml.Return { +// panic("mock out the SystemEventSetWait method") +// }, +// SystemGetConfComputeCapabilitiesFunc: func() (nvml.ConfComputeSystemCaps, nvml.Return) { +// panic("mock out the SystemGetConfComputeCapabilities method") +// }, +// SystemGetConfComputeGpusReadyStateFunc: func() (uint32, nvml.Return) { +// panic("mock out the SystemGetConfComputeGpusReadyState method") +// }, +// SystemGetConfComputeKeyRotationThresholdInfoFunc: func() (nvml.ConfComputeGetKeyRotationThresholdInfo, nvml.Return) { +// panic("mock out the SystemGetConfComputeKeyRotationThresholdInfo method") +// }, +// SystemGetConfComputeSettingsFunc: func() (nvml.SystemConfComputeSettings, nvml.Return) { +// panic("mock out the SystemGetConfComputeSettings method") +// }, +// SystemGetConfComputeStateFunc: func() (nvml.ConfComputeSystemState, nvml.Return) { +// panic("mock out the SystemGetConfComputeState method") +// }, +// SystemGetCudaDriverVersionFunc: func() (int, nvml.Return) { +// panic("mock out the SystemGetCudaDriverVersion method") +// }, +// SystemGetCudaDriverVersion_v2Func: func() (int, nvml.Return) { +// panic("mock out the SystemGetCudaDriverVersion_v2 method") +// }, +// SystemGetDriverBranchFunc: func() (nvml.SystemDriverBranchInfo, nvml.Return) { +// panic("mock out the SystemGetDriverBranch method") +// }, +// SystemGetDriverVersionFunc: func() (string, nvml.Return) { +// panic("mock out the SystemGetDriverVersion method") +// }, +// SystemGetHicVersionFunc: func() ([]nvml.HwbcEntry, nvml.Return) { +// panic("mock out the SystemGetHicVersion method") +// }, +// SystemGetNVMLVersionFunc: func() (string, nvml.Return) { +// panic("mock out the SystemGetNVMLVersion method") +// }, +// SystemGetNvlinkBwModeFunc: func() (uint32, nvml.Return) { +// panic("mock out the SystemGetNvlinkBwMode method") +// }, +// SystemGetProcessNameFunc: func(n int) (string, nvml.Return) { +// panic("mock out the SystemGetProcessName method") +// }, +// SystemGetTopologyGpuSetFunc: func(n int) ([]nvml.Device, nvml.Return) { +// panic("mock out the SystemGetTopologyGpuSet method") +// }, +// SystemRegisterEventsFunc: func(systemRegisterEventRequest *nvml.SystemRegisterEventRequest) nvml.Return { +// panic("mock out the SystemRegisterEvents method") +// }, +// SystemSetConfComputeGpusReadyStateFunc: func(v uint32) nvml.Return { +// panic("mock out the SystemSetConfComputeGpusReadyState method") +// }, +// SystemSetConfComputeKeyRotationThresholdInfoFunc: func(confComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo) nvml.Return { +// panic("mock out the SystemSetConfComputeKeyRotationThresholdInfo method") +// }, +// SystemSetNvlinkBwModeFunc: func(v uint32) nvml.Return { +// panic("mock out the SystemSetNvlinkBwMode method") +// }, +// UnitGetCountFunc: func() (int, nvml.Return) { +// panic("mock out the UnitGetCount method") +// }, +// UnitGetDevicesFunc: func(unit nvml.Unit) ([]nvml.Device, nvml.Return) { +// panic("mock out the UnitGetDevices method") +// }, +// UnitGetFanSpeedInfoFunc: func(unit nvml.Unit) (nvml.UnitFanSpeeds, nvml.Return) { +// panic("mock out the UnitGetFanSpeedInfo method") +// }, +// UnitGetHandleByIndexFunc: func(n int) (nvml.Unit, nvml.Return) { +// panic("mock out the UnitGetHandleByIndex method") +// }, +// UnitGetLedStateFunc: func(unit nvml.Unit) (nvml.LedState, nvml.Return) { +// panic("mock out the UnitGetLedState method") +// }, +// UnitGetPsuInfoFunc: func(unit nvml.Unit) (nvml.PSUInfo, nvml.Return) { +// panic("mock out the UnitGetPsuInfo method") +// }, +// UnitGetTemperatureFunc: func(unit nvml.Unit, n int) (uint32, nvml.Return) { +// panic("mock out the UnitGetTemperature method") +// }, +// UnitGetUnitInfoFunc: func(unit nvml.Unit) (nvml.UnitInfo, nvml.Return) { +// panic("mock out the UnitGetUnitInfo method") +// }, +// UnitSetLedStateFunc: func(unit nvml.Unit, ledColor nvml.LedColor) nvml.Return { +// panic("mock out the UnitSetLedState method") +// }, +// VgpuInstanceClearAccountingPidsFunc: func(vgpuInstance nvml.VgpuInstance) nvml.Return { +// panic("mock out the VgpuInstanceClearAccountingPids method") +// }, +// VgpuInstanceGetAccountingModeFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) { +// panic("mock out the VgpuInstanceGetAccountingMode method") +// }, +// VgpuInstanceGetAccountingPidsFunc: func(vgpuInstance nvml.VgpuInstance) ([]int, nvml.Return) { +// panic("mock out the VgpuInstanceGetAccountingPids method") +// }, +// VgpuInstanceGetAccountingStatsFunc: func(vgpuInstance nvml.VgpuInstance, n int) (nvml.AccountingStats, nvml.Return) { +// panic("mock out the VgpuInstanceGetAccountingStats method") +// }, +// VgpuInstanceGetEccModeFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) { +// panic("mock out the VgpuInstanceGetEccMode method") +// }, +// VgpuInstanceGetEncoderCapacityFunc: func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { +// panic("mock out the VgpuInstanceGetEncoderCapacity method") +// }, +// VgpuInstanceGetEncoderSessionsFunc: func(vgpuInstance nvml.VgpuInstance) (int, nvml.EncoderSessionInfo, nvml.Return) { +// panic("mock out the VgpuInstanceGetEncoderSessions method") +// }, +// VgpuInstanceGetEncoderStatsFunc: func(vgpuInstance nvml.VgpuInstance) (int, uint32, uint32, nvml.Return) { +// panic("mock out the VgpuInstanceGetEncoderStats method") +// }, +// VgpuInstanceGetFBCSessionsFunc: func(vgpuInstance nvml.VgpuInstance) (int, nvml.FBCSessionInfo, nvml.Return) { +// panic("mock out the VgpuInstanceGetFBCSessions method") +// }, +// VgpuInstanceGetFBCStatsFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.FBCStats, nvml.Return) { +// panic("mock out the VgpuInstanceGetFBCStats method") +// }, +// VgpuInstanceGetFbUsageFunc: func(vgpuInstance nvml.VgpuInstance) (uint64, nvml.Return) { +// panic("mock out the VgpuInstanceGetFbUsage method") +// }, +// VgpuInstanceGetFrameRateLimitFunc: func(vgpuInstance nvml.VgpuInstance) (uint32, nvml.Return) { +// panic("mock out the VgpuInstanceGetFrameRateLimit method") +// }, +// VgpuInstanceGetGpuInstanceIdFunc: func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { +// panic("mock out the VgpuInstanceGetGpuInstanceId method") +// }, +// VgpuInstanceGetGpuPciIdFunc: func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { +// panic("mock out the VgpuInstanceGetGpuPciId method") +// }, +// VgpuInstanceGetLicenseInfoFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuLicenseInfo, nvml.Return) { +// panic("mock out the VgpuInstanceGetLicenseInfo method") +// }, +// VgpuInstanceGetLicenseStatusFunc: func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { +// panic("mock out the VgpuInstanceGetLicenseStatus method") +// }, +// VgpuInstanceGetMdevUUIDFunc: func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { +// panic("mock out the VgpuInstanceGetMdevUUID method") +// }, +// VgpuInstanceGetMetadataFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuMetadata, nvml.Return) { +// panic("mock out the VgpuInstanceGetMetadata method") +// }, +// VgpuInstanceGetRuntimeStateSizeFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuRuntimeState, nvml.Return) { +// panic("mock out the VgpuInstanceGetRuntimeStateSize method") +// }, +// VgpuInstanceGetTypeFunc: func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the VgpuInstanceGetType method") +// }, +// VgpuInstanceGetUUIDFunc: func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { +// panic("mock out the VgpuInstanceGetUUID method") +// }, +// VgpuInstanceGetVmDriverVersionFunc: func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { +// panic("mock out the VgpuInstanceGetVmDriverVersion method") +// }, +// VgpuInstanceGetVmIDFunc: func(vgpuInstance nvml.VgpuInstance) (string, nvml.VgpuVmIdType, nvml.Return) { +// panic("mock out the VgpuInstanceGetVmID method") +// }, +// VgpuInstanceSetEncoderCapacityFunc: func(vgpuInstance nvml.VgpuInstance, n int) nvml.Return { +// panic("mock out the VgpuInstanceSetEncoderCapacity method") +// }, +// VgpuTypeGetBAR1InfoFunc: func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuTypeBar1Info, nvml.Return) { +// panic("mock out the VgpuTypeGetBAR1Info method") +// }, +// VgpuTypeGetCapabilitiesFunc: func(vgpuTypeId nvml.VgpuTypeId, vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) { +// panic("mock out the VgpuTypeGetCapabilities method") +// }, +// VgpuTypeGetClassFunc: func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { +// panic("mock out the VgpuTypeGetClass method") +// }, +// VgpuTypeGetDeviceIDFunc: func(vgpuTypeId nvml.VgpuTypeId) (uint64, uint64, nvml.Return) { +// panic("mock out the VgpuTypeGetDeviceID method") +// }, +// VgpuTypeGetFrameRateLimitFunc: func(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) { +// panic("mock out the VgpuTypeGetFrameRateLimit method") +// }, +// VgpuTypeGetFramebufferSizeFunc: func(vgpuTypeId nvml.VgpuTypeId) (uint64, nvml.Return) { +// panic("mock out the VgpuTypeGetFramebufferSize method") +// }, +// VgpuTypeGetGpuInstanceProfileIdFunc: func(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) { +// panic("mock out the VgpuTypeGetGpuInstanceProfileId method") +// }, +// VgpuTypeGetLicenseFunc: func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { +// panic("mock out the VgpuTypeGetLicense method") +// }, +// VgpuTypeGetMaxInstancesFunc: func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { +// panic("mock out the VgpuTypeGetMaxInstances method") +// }, +// VgpuTypeGetMaxInstancesPerGpuInstanceFunc: func(vgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance) nvml.Return { +// panic("mock out the VgpuTypeGetMaxInstancesPerGpuInstance method") +// }, +// VgpuTypeGetMaxInstancesPerVmFunc: func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { +// panic("mock out the VgpuTypeGetMaxInstancesPerVm method") +// }, +// VgpuTypeGetNameFunc: func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { +// panic("mock out the VgpuTypeGetName method") +// }, +// VgpuTypeGetNumDisplayHeadsFunc: func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { +// panic("mock out the VgpuTypeGetNumDisplayHeads method") +// }, +// VgpuTypeGetResolutionFunc: func(vgpuTypeId nvml.VgpuTypeId, n int) (uint32, uint32, nvml.Return) { +// panic("mock out the VgpuTypeGetResolution method") +// }, +// } +// +// // use mockedInterface in code that requires nvml.Interface +// // and then make assertions. +// +// } +type Interface struct { + // ComputeInstanceDestroyFunc mocks the ComputeInstanceDestroy method. + ComputeInstanceDestroyFunc func(computeInstance nvml.ComputeInstance) nvml.Return + + // ComputeInstanceGetInfoFunc mocks the ComputeInstanceGetInfo method. + ComputeInstanceGetInfoFunc func(computeInstance nvml.ComputeInstance) (nvml.ComputeInstanceInfo, nvml.Return) + + // DeviceClearAccountingPidsFunc mocks the DeviceClearAccountingPids method. + DeviceClearAccountingPidsFunc func(device nvml.Device) nvml.Return + + // DeviceClearCpuAffinityFunc mocks the DeviceClearCpuAffinity method. + DeviceClearCpuAffinityFunc func(device nvml.Device) nvml.Return + + // DeviceClearEccErrorCountsFunc mocks the DeviceClearEccErrorCounts method. + DeviceClearEccErrorCountsFunc func(device nvml.Device, eccCounterType nvml.EccCounterType) nvml.Return + + // DeviceClearFieldValuesFunc mocks the DeviceClearFieldValues method. + DeviceClearFieldValuesFunc func(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return + + // DeviceCreateGpuInstanceFunc mocks the DeviceCreateGpuInstance method. + DeviceCreateGpuInstanceFunc func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) + + // DeviceCreateGpuInstanceWithPlacementFunc mocks the DeviceCreateGpuInstanceWithPlacement method. + DeviceCreateGpuInstanceWithPlacementFunc func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) + + // DeviceDiscoverGpusFunc mocks the DeviceDiscoverGpus method. + DeviceDiscoverGpusFunc func() (nvml.PciInfo, nvml.Return) + + // DeviceFreezeNvLinkUtilizationCounterFunc mocks the DeviceFreezeNvLinkUtilizationCounter method. + DeviceFreezeNvLinkUtilizationCounterFunc func(device nvml.Device, n1 int, n2 int, enableState nvml.EnableState) nvml.Return + + // DeviceGetAPIRestrictionFunc mocks the DeviceGetAPIRestriction method. + DeviceGetAPIRestrictionFunc func(device nvml.Device, restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) + + // DeviceGetAccountingBufferSizeFunc mocks the DeviceGetAccountingBufferSize method. + DeviceGetAccountingBufferSizeFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetAccountingModeFunc mocks the DeviceGetAccountingMode method. + DeviceGetAccountingModeFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetAccountingPidsFunc mocks the DeviceGetAccountingPids method. + DeviceGetAccountingPidsFunc func(device nvml.Device) ([]int, nvml.Return) + + // DeviceGetAccountingStatsFunc mocks the DeviceGetAccountingStats method. + DeviceGetAccountingStatsFunc func(device nvml.Device, v uint32) (nvml.AccountingStats, nvml.Return) + + // DeviceGetActiveVgpusFunc mocks the DeviceGetActiveVgpus method. + DeviceGetActiveVgpusFunc func(device nvml.Device) ([]nvml.VgpuInstance, nvml.Return) + + // DeviceGetAdaptiveClockInfoStatusFunc mocks the DeviceGetAdaptiveClockInfoStatus method. + DeviceGetAdaptiveClockInfoStatusFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetAddressingModeFunc mocks the DeviceGetAddressingMode method. + DeviceGetAddressingModeFunc func(device nvml.Device) (nvml.DeviceAddressingMode, nvml.Return) + + // DeviceGetApplicationsClockFunc mocks the DeviceGetApplicationsClock method. + DeviceGetApplicationsClockFunc func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) + + // DeviceGetArchitectureFunc mocks the DeviceGetArchitecture method. + DeviceGetArchitectureFunc func(device nvml.Device) (nvml.DeviceArchitecture, nvml.Return) + + // DeviceGetAttributesFunc mocks the DeviceGetAttributes method. + DeviceGetAttributesFunc func(device nvml.Device) (nvml.DeviceAttributes, nvml.Return) + + // DeviceGetAutoBoostedClocksEnabledFunc mocks the DeviceGetAutoBoostedClocksEnabled method. + DeviceGetAutoBoostedClocksEnabledFunc func(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) + + // DeviceGetBAR1MemoryInfoFunc mocks the DeviceGetBAR1MemoryInfo method. + DeviceGetBAR1MemoryInfoFunc func(device nvml.Device) (nvml.BAR1Memory, nvml.Return) + + // DeviceGetBoardIdFunc mocks the DeviceGetBoardId method. + DeviceGetBoardIdFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetBoardPartNumberFunc mocks the DeviceGetBoardPartNumber method. + DeviceGetBoardPartNumberFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetBrandFunc mocks the DeviceGetBrand method. + DeviceGetBrandFunc func(device nvml.Device) (nvml.BrandType, nvml.Return) + + // DeviceGetBridgeChipInfoFunc mocks the DeviceGetBridgeChipInfo method. + DeviceGetBridgeChipInfoFunc func(device nvml.Device) (nvml.BridgeChipHierarchy, nvml.Return) + + // DeviceGetBusTypeFunc mocks the DeviceGetBusType method. + DeviceGetBusTypeFunc func(device nvml.Device) (nvml.BusType, nvml.Return) + + // DeviceGetC2cModeInfoVFunc mocks the DeviceGetC2cModeInfoV method. + DeviceGetC2cModeInfoVFunc func(device nvml.Device) nvml.C2cModeInfoHandler + + // DeviceGetCapabilitiesFunc mocks the DeviceGetCapabilities method. + DeviceGetCapabilitiesFunc func(device nvml.Device) (nvml.DeviceCapabilities, nvml.Return) + + // DeviceGetClkMonStatusFunc mocks the DeviceGetClkMonStatus method. + DeviceGetClkMonStatusFunc func(device nvml.Device) (nvml.ClkMonStatus, nvml.Return) + + // DeviceGetClockFunc mocks the DeviceGetClock method. + DeviceGetClockFunc func(device nvml.Device, clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) + + // DeviceGetClockInfoFunc mocks the DeviceGetClockInfo method. + DeviceGetClockInfoFunc func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) + + // DeviceGetClockOffsetsFunc mocks the DeviceGetClockOffsets method. + DeviceGetClockOffsetsFunc func(device nvml.Device) (nvml.ClockOffset, nvml.Return) + + // DeviceGetComputeInstanceIdFunc mocks the DeviceGetComputeInstanceId method. + DeviceGetComputeInstanceIdFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetComputeModeFunc mocks the DeviceGetComputeMode method. + DeviceGetComputeModeFunc func(device nvml.Device) (nvml.ComputeMode, nvml.Return) + + // DeviceGetComputeRunningProcessesFunc mocks the DeviceGetComputeRunningProcesses method. + DeviceGetComputeRunningProcessesFunc func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) + + // DeviceGetConfComputeGpuAttestationReportFunc mocks the DeviceGetConfComputeGpuAttestationReport method. + DeviceGetConfComputeGpuAttestationReportFunc func(device nvml.Device, confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return + + // DeviceGetConfComputeGpuCertificateFunc mocks the DeviceGetConfComputeGpuCertificate method. + DeviceGetConfComputeGpuCertificateFunc func(device nvml.Device) (nvml.ConfComputeGpuCertificate, nvml.Return) + + // DeviceGetConfComputeMemSizeInfoFunc mocks the DeviceGetConfComputeMemSizeInfo method. + DeviceGetConfComputeMemSizeInfoFunc func(device nvml.Device) (nvml.ConfComputeMemSizeInfo, nvml.Return) + + // DeviceGetConfComputeProtectedMemoryUsageFunc mocks the DeviceGetConfComputeProtectedMemoryUsage method. + DeviceGetConfComputeProtectedMemoryUsageFunc func(device nvml.Device) (nvml.Memory, nvml.Return) + + // DeviceGetCoolerInfoFunc mocks the DeviceGetCoolerInfo method. + DeviceGetCoolerInfoFunc func(device nvml.Device) (nvml.CoolerInfo, nvml.Return) + + // DeviceGetCountFunc mocks the DeviceGetCount method. + DeviceGetCountFunc func() (int, nvml.Return) + + // DeviceGetCpuAffinityFunc mocks the DeviceGetCpuAffinity method. + DeviceGetCpuAffinityFunc func(device nvml.Device, n int) ([]uint, nvml.Return) + + // DeviceGetCpuAffinityWithinScopeFunc mocks the DeviceGetCpuAffinityWithinScope method. + DeviceGetCpuAffinityWithinScopeFunc func(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) + + // DeviceGetCreatableVgpusFunc mocks the DeviceGetCreatableVgpus method. + DeviceGetCreatableVgpusFunc func(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) + + // DeviceGetCudaComputeCapabilityFunc mocks the DeviceGetCudaComputeCapability method. + DeviceGetCudaComputeCapabilityFunc func(device nvml.Device) (int, int, nvml.Return) + + // DeviceGetCurrPcieLinkGenerationFunc mocks the DeviceGetCurrPcieLinkGeneration method. + DeviceGetCurrPcieLinkGenerationFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetCurrPcieLinkWidthFunc mocks the DeviceGetCurrPcieLinkWidth method. + DeviceGetCurrPcieLinkWidthFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetCurrentClockFreqsFunc mocks the DeviceGetCurrentClockFreqs method. + DeviceGetCurrentClockFreqsFunc func(device nvml.Device) (nvml.DeviceCurrentClockFreqs, nvml.Return) + + // DeviceGetCurrentClocksEventReasonsFunc mocks the DeviceGetCurrentClocksEventReasons method. + DeviceGetCurrentClocksEventReasonsFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetCurrentClocksThrottleReasonsFunc mocks the DeviceGetCurrentClocksThrottleReasons method. + DeviceGetCurrentClocksThrottleReasonsFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetDecoderUtilizationFunc mocks the DeviceGetDecoderUtilization method. + DeviceGetDecoderUtilizationFunc func(device nvml.Device) (uint32, uint32, nvml.Return) + + // DeviceGetDefaultApplicationsClockFunc mocks the DeviceGetDefaultApplicationsClock method. + DeviceGetDefaultApplicationsClockFunc func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) + + // DeviceGetDefaultEccModeFunc mocks the DeviceGetDefaultEccMode method. + DeviceGetDefaultEccModeFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetDetailedEccErrorsFunc mocks the DeviceGetDetailedEccErrors method. + DeviceGetDetailedEccErrorsFunc func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) + + // DeviceGetDeviceHandleFromMigDeviceHandleFunc mocks the DeviceGetDeviceHandleFromMigDeviceHandle method. + DeviceGetDeviceHandleFromMigDeviceHandleFunc func(device nvml.Device) (nvml.Device, nvml.Return) + + // DeviceGetDisplayActiveFunc mocks the DeviceGetDisplayActive method. + DeviceGetDisplayActiveFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetDisplayModeFunc mocks the DeviceGetDisplayMode method. + DeviceGetDisplayModeFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetDramEncryptionModeFunc mocks the DeviceGetDramEncryptionMode method. + DeviceGetDramEncryptionModeFunc func(device nvml.Device) (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) + + // DeviceGetDriverModelFunc mocks the DeviceGetDriverModel method. + DeviceGetDriverModelFunc func(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) + + // DeviceGetDriverModel_v2Func mocks the DeviceGetDriverModel_v2 method. + DeviceGetDriverModel_v2Func func(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) + + // DeviceGetDynamicPstatesInfoFunc mocks the DeviceGetDynamicPstatesInfo method. + DeviceGetDynamicPstatesInfoFunc func(device nvml.Device) (nvml.GpuDynamicPstatesInfo, nvml.Return) + + // DeviceGetEccModeFunc mocks the DeviceGetEccMode method. + DeviceGetEccModeFunc func(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) + + // DeviceGetEncoderCapacityFunc mocks the DeviceGetEncoderCapacity method. + DeviceGetEncoderCapacityFunc func(device nvml.Device, encoderType nvml.EncoderType) (int, nvml.Return) + + // DeviceGetEncoderSessionsFunc mocks the DeviceGetEncoderSessions method. + DeviceGetEncoderSessionsFunc func(device nvml.Device) ([]nvml.EncoderSessionInfo, nvml.Return) + + // DeviceGetEncoderStatsFunc mocks the DeviceGetEncoderStats method. + DeviceGetEncoderStatsFunc func(device nvml.Device) (int, uint32, uint32, nvml.Return) + + // DeviceGetEncoderUtilizationFunc mocks the DeviceGetEncoderUtilization method. + DeviceGetEncoderUtilizationFunc func(device nvml.Device) (uint32, uint32, nvml.Return) + + // DeviceGetEnforcedPowerLimitFunc mocks the DeviceGetEnforcedPowerLimit method. + DeviceGetEnforcedPowerLimitFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetFBCSessionsFunc mocks the DeviceGetFBCSessions method. + DeviceGetFBCSessionsFunc func(device nvml.Device) ([]nvml.FBCSessionInfo, nvml.Return) + + // DeviceGetFBCStatsFunc mocks the DeviceGetFBCStats method. + DeviceGetFBCStatsFunc func(device nvml.Device) (nvml.FBCStats, nvml.Return) + + // DeviceGetFanControlPolicy_v2Func mocks the DeviceGetFanControlPolicy_v2 method. + DeviceGetFanControlPolicy_v2Func func(device nvml.Device, n int) (nvml.FanControlPolicy, nvml.Return) + + // DeviceGetFanSpeedFunc mocks the DeviceGetFanSpeed method. + DeviceGetFanSpeedFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetFanSpeedRPMFunc mocks the DeviceGetFanSpeedRPM method. + DeviceGetFanSpeedRPMFunc func(device nvml.Device) (nvml.FanSpeedInfo, nvml.Return) + + // DeviceGetFanSpeed_v2Func mocks the DeviceGetFanSpeed_v2 method. + DeviceGetFanSpeed_v2Func func(device nvml.Device, n int) (uint32, nvml.Return) + + // DeviceGetFieldValuesFunc mocks the DeviceGetFieldValues method. + DeviceGetFieldValuesFunc func(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return + + // DeviceGetGpcClkMinMaxVfOffsetFunc mocks the DeviceGetGpcClkMinMaxVfOffset method. + DeviceGetGpcClkMinMaxVfOffsetFunc func(device nvml.Device) (int, int, nvml.Return) + + // DeviceGetGpcClkVfOffsetFunc mocks the DeviceGetGpcClkVfOffset method. + DeviceGetGpcClkVfOffsetFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetGpuFabricInfoFunc mocks the DeviceGetGpuFabricInfo method. + DeviceGetGpuFabricInfoFunc func(device nvml.Device) (nvml.GpuFabricInfo, nvml.Return) + + // DeviceGetGpuFabricInfoVFunc mocks the DeviceGetGpuFabricInfoV method. + DeviceGetGpuFabricInfoVFunc func(device nvml.Device) nvml.GpuFabricInfoHandler + + // DeviceGetGpuInstanceByIdFunc mocks the DeviceGetGpuInstanceById method. + DeviceGetGpuInstanceByIdFunc func(device nvml.Device, n int) (nvml.GpuInstance, nvml.Return) + + // DeviceGetGpuInstanceIdFunc mocks the DeviceGetGpuInstanceId method. + DeviceGetGpuInstanceIdFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetGpuInstancePossiblePlacementsFunc mocks the DeviceGetGpuInstancePossiblePlacements method. + DeviceGetGpuInstancePossiblePlacementsFunc func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) + + // DeviceGetGpuInstanceProfileInfoFunc mocks the DeviceGetGpuInstanceProfileInfo method. + DeviceGetGpuInstanceProfileInfoFunc func(device nvml.Device, n int) (nvml.GpuInstanceProfileInfo, nvml.Return) + + // DeviceGetGpuInstanceProfileInfoByIdVFunc mocks the DeviceGetGpuInstanceProfileInfoByIdV method. + DeviceGetGpuInstanceProfileInfoByIdVFunc func(device nvml.Device, n int) nvml.GpuInstanceProfileInfoByIdHandler + + // DeviceGetGpuInstanceProfileInfoVFunc mocks the DeviceGetGpuInstanceProfileInfoV method. + DeviceGetGpuInstanceProfileInfoVFunc func(device nvml.Device, n int) nvml.GpuInstanceProfileInfoHandler + + // DeviceGetGpuInstanceRemainingCapacityFunc mocks the DeviceGetGpuInstanceRemainingCapacity method. + DeviceGetGpuInstanceRemainingCapacityFunc func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) + + // DeviceGetGpuInstancesFunc mocks the DeviceGetGpuInstances method. + DeviceGetGpuInstancesFunc func(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) + + // DeviceGetGpuMaxPcieLinkGenerationFunc mocks the DeviceGetGpuMaxPcieLinkGeneration method. + DeviceGetGpuMaxPcieLinkGenerationFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetGpuOperationModeFunc mocks the DeviceGetGpuOperationMode method. + DeviceGetGpuOperationModeFunc func(device nvml.Device) (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) + + // DeviceGetGraphicsRunningProcessesFunc mocks the DeviceGetGraphicsRunningProcesses method. + DeviceGetGraphicsRunningProcessesFunc func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) + + // DeviceGetGridLicensableFeaturesFunc mocks the DeviceGetGridLicensableFeatures method. + DeviceGetGridLicensableFeaturesFunc func(device nvml.Device) (nvml.GridLicensableFeatures, nvml.Return) + + // DeviceGetGspFirmwareModeFunc mocks the DeviceGetGspFirmwareMode method. + DeviceGetGspFirmwareModeFunc func(device nvml.Device) (bool, bool, nvml.Return) + + // DeviceGetGspFirmwareVersionFunc mocks the DeviceGetGspFirmwareVersion method. + DeviceGetGspFirmwareVersionFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetHandleByIndexFunc mocks the DeviceGetHandleByIndex method. + DeviceGetHandleByIndexFunc func(n int) (nvml.Device, nvml.Return) + + // DeviceGetHandleByPciBusIdFunc mocks the DeviceGetHandleByPciBusId method. + DeviceGetHandleByPciBusIdFunc func(s string) (nvml.Device, nvml.Return) + + // DeviceGetHandleBySerialFunc mocks the DeviceGetHandleBySerial method. + DeviceGetHandleBySerialFunc func(s string) (nvml.Device, nvml.Return) + + // DeviceGetHandleByUUIDFunc mocks the DeviceGetHandleByUUID method. + DeviceGetHandleByUUIDFunc func(s string) (nvml.Device, nvml.Return) + + // DeviceGetHandleByUUIDVFunc mocks the DeviceGetHandleByUUIDV method. + DeviceGetHandleByUUIDVFunc func(uUID *nvml.UUID) (nvml.Device, nvml.Return) + + // DeviceGetHostVgpuModeFunc mocks the DeviceGetHostVgpuMode method. + DeviceGetHostVgpuModeFunc func(device nvml.Device) (nvml.HostVgpuMode, nvml.Return) + + // DeviceGetIndexFunc mocks the DeviceGetIndex method. + DeviceGetIndexFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetInforomConfigurationChecksumFunc mocks the DeviceGetInforomConfigurationChecksum method. + DeviceGetInforomConfigurationChecksumFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetInforomImageVersionFunc mocks the DeviceGetInforomImageVersion method. + DeviceGetInforomImageVersionFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetInforomVersionFunc mocks the DeviceGetInforomVersion method. + DeviceGetInforomVersionFunc func(device nvml.Device, inforomObject nvml.InforomObject) (string, nvml.Return) + + // DeviceGetIrqNumFunc mocks the DeviceGetIrqNum method. + DeviceGetIrqNumFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetJpgUtilizationFunc mocks the DeviceGetJpgUtilization method. + DeviceGetJpgUtilizationFunc func(device nvml.Device) (uint32, uint32, nvml.Return) + + // DeviceGetLastBBXFlushTimeFunc mocks the DeviceGetLastBBXFlushTime method. + DeviceGetLastBBXFlushTimeFunc func(device nvml.Device) (uint64, uint, nvml.Return) + + // DeviceGetMPSComputeRunningProcessesFunc mocks the DeviceGetMPSComputeRunningProcesses method. + DeviceGetMPSComputeRunningProcessesFunc func(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) + + // DeviceGetMarginTemperatureFunc mocks the DeviceGetMarginTemperature method. + DeviceGetMarginTemperatureFunc func(device nvml.Device) (nvml.MarginTemperature, nvml.Return) + + // DeviceGetMaxClockInfoFunc mocks the DeviceGetMaxClockInfo method. + DeviceGetMaxClockInfoFunc func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) + + // DeviceGetMaxCustomerBoostClockFunc mocks the DeviceGetMaxCustomerBoostClock method. + DeviceGetMaxCustomerBoostClockFunc func(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) + + // DeviceGetMaxMigDeviceCountFunc mocks the DeviceGetMaxMigDeviceCount method. + DeviceGetMaxMigDeviceCountFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetMaxPcieLinkGenerationFunc mocks the DeviceGetMaxPcieLinkGeneration method. + DeviceGetMaxPcieLinkGenerationFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetMaxPcieLinkWidthFunc mocks the DeviceGetMaxPcieLinkWidth method. + DeviceGetMaxPcieLinkWidthFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetMemClkMinMaxVfOffsetFunc mocks the DeviceGetMemClkMinMaxVfOffset method. + DeviceGetMemClkMinMaxVfOffsetFunc func(device nvml.Device) (int, int, nvml.Return) + + // DeviceGetMemClkVfOffsetFunc mocks the DeviceGetMemClkVfOffset method. + DeviceGetMemClkVfOffsetFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetMemoryAffinityFunc mocks the DeviceGetMemoryAffinity method. + DeviceGetMemoryAffinityFunc func(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) + + // DeviceGetMemoryBusWidthFunc mocks the DeviceGetMemoryBusWidth method. + DeviceGetMemoryBusWidthFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetMemoryErrorCounterFunc mocks the DeviceGetMemoryErrorCounter method. + DeviceGetMemoryErrorCounterFunc func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) + + // DeviceGetMemoryInfoFunc mocks the DeviceGetMemoryInfo method. + DeviceGetMemoryInfoFunc func(device nvml.Device) (nvml.Memory, nvml.Return) + + // DeviceGetMemoryInfo_v2Func mocks the DeviceGetMemoryInfo_v2 method. + DeviceGetMemoryInfo_v2Func func(device nvml.Device) (nvml.Memory_v2, nvml.Return) + + // DeviceGetMigDeviceHandleByIndexFunc mocks the DeviceGetMigDeviceHandleByIndex method. + DeviceGetMigDeviceHandleByIndexFunc func(device nvml.Device, n int) (nvml.Device, nvml.Return) + + // DeviceGetMigModeFunc mocks the DeviceGetMigMode method. + DeviceGetMigModeFunc func(device nvml.Device) (int, int, nvml.Return) + + // DeviceGetMinMaxClockOfPStateFunc mocks the DeviceGetMinMaxClockOfPState method. + DeviceGetMinMaxClockOfPStateFunc func(device nvml.Device, clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) + + // DeviceGetMinMaxFanSpeedFunc mocks the DeviceGetMinMaxFanSpeed method. + DeviceGetMinMaxFanSpeedFunc func(device nvml.Device) (int, int, nvml.Return) + + // DeviceGetMinorNumberFunc mocks the DeviceGetMinorNumber method. + DeviceGetMinorNumberFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetModuleIdFunc mocks the DeviceGetModuleId method. + DeviceGetModuleIdFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetMultiGpuBoardFunc mocks the DeviceGetMultiGpuBoard method. + DeviceGetMultiGpuBoardFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetNameFunc mocks the DeviceGetName method. + DeviceGetNameFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetNumFansFunc mocks the DeviceGetNumFans method. + DeviceGetNumFansFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetNumGpuCoresFunc mocks the DeviceGetNumGpuCores method. + DeviceGetNumGpuCoresFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetNumaNodeIdFunc mocks the DeviceGetNumaNodeId method. + DeviceGetNumaNodeIdFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetNvLinkCapabilityFunc mocks the DeviceGetNvLinkCapability method. + DeviceGetNvLinkCapabilityFunc func(device nvml.Device, n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) + + // DeviceGetNvLinkErrorCounterFunc mocks the DeviceGetNvLinkErrorCounter method. + DeviceGetNvLinkErrorCounterFunc func(device nvml.Device, n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) + + // DeviceGetNvLinkInfoFunc mocks the DeviceGetNvLinkInfo method. + DeviceGetNvLinkInfoFunc func(device nvml.Device) nvml.NvLinkInfoHandler + + // DeviceGetNvLinkRemoteDeviceTypeFunc mocks the DeviceGetNvLinkRemoteDeviceType method. + DeviceGetNvLinkRemoteDeviceTypeFunc func(device nvml.Device, n int) (nvml.IntNvLinkDeviceType, nvml.Return) + + // DeviceGetNvLinkRemotePciInfoFunc mocks the DeviceGetNvLinkRemotePciInfo method. + DeviceGetNvLinkRemotePciInfoFunc func(device nvml.Device, n int) (nvml.PciInfo, nvml.Return) + + // DeviceGetNvLinkStateFunc mocks the DeviceGetNvLinkState method. + DeviceGetNvLinkStateFunc func(device nvml.Device, n int) (nvml.EnableState, nvml.Return) + + // DeviceGetNvLinkUtilizationControlFunc mocks the DeviceGetNvLinkUtilizationControl method. + DeviceGetNvLinkUtilizationControlFunc func(device nvml.Device, n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) + + // DeviceGetNvLinkUtilizationCounterFunc mocks the DeviceGetNvLinkUtilizationCounter method. + DeviceGetNvLinkUtilizationCounterFunc func(device nvml.Device, n1 int, n2 int) (uint64, uint64, nvml.Return) + + // DeviceGetNvLinkVersionFunc mocks the DeviceGetNvLinkVersion method. + DeviceGetNvLinkVersionFunc func(device nvml.Device, n int) (uint32, nvml.Return) + + // DeviceGetNvlinkBwModeFunc mocks the DeviceGetNvlinkBwMode method. + DeviceGetNvlinkBwModeFunc func(device nvml.Device) (nvml.NvlinkGetBwMode, nvml.Return) + + // DeviceGetNvlinkSupportedBwModesFunc mocks the DeviceGetNvlinkSupportedBwModes method. + DeviceGetNvlinkSupportedBwModesFunc func(device nvml.Device) (nvml.NvlinkSupportedBwModes, nvml.Return) + + // DeviceGetOfaUtilizationFunc mocks the DeviceGetOfaUtilization method. + DeviceGetOfaUtilizationFunc func(device nvml.Device) (uint32, uint32, nvml.Return) + + // DeviceGetP2PStatusFunc mocks the DeviceGetP2PStatus method. + DeviceGetP2PStatusFunc func(device1 nvml.Device, device2 nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) + + // DeviceGetPciInfoFunc mocks the DeviceGetPciInfo method. + DeviceGetPciInfoFunc func(device nvml.Device) (nvml.PciInfo, nvml.Return) + + // DeviceGetPciInfoExtFunc mocks the DeviceGetPciInfoExt method. + DeviceGetPciInfoExtFunc func(device nvml.Device) (nvml.PciInfoExt, nvml.Return) + + // DeviceGetPcieLinkMaxSpeedFunc mocks the DeviceGetPcieLinkMaxSpeed method. + DeviceGetPcieLinkMaxSpeedFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetPcieReplayCounterFunc mocks the DeviceGetPcieReplayCounter method. + DeviceGetPcieReplayCounterFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetPcieSpeedFunc mocks the DeviceGetPcieSpeed method. + DeviceGetPcieSpeedFunc func(device nvml.Device) (int, nvml.Return) + + // DeviceGetPcieThroughputFunc mocks the DeviceGetPcieThroughput method. + DeviceGetPcieThroughputFunc func(device nvml.Device, pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) + + // DeviceGetPdiFunc mocks the DeviceGetPdi method. + DeviceGetPdiFunc func(device nvml.Device) (nvml.Pdi, nvml.Return) + + // DeviceGetPerformanceModesFunc mocks the DeviceGetPerformanceModes method. + DeviceGetPerformanceModesFunc func(device nvml.Device) (nvml.DevicePerfModes, nvml.Return) + + // DeviceGetPerformanceStateFunc mocks the DeviceGetPerformanceState method. + DeviceGetPerformanceStateFunc func(device nvml.Device) (nvml.Pstates, nvml.Return) + + // DeviceGetPersistenceModeFunc mocks the DeviceGetPersistenceMode method. + DeviceGetPersistenceModeFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetPgpuMetadataStringFunc mocks the DeviceGetPgpuMetadataString method. + DeviceGetPgpuMetadataStringFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetPlatformInfoFunc mocks the DeviceGetPlatformInfo method. + DeviceGetPlatformInfoFunc func(device nvml.Device) (nvml.PlatformInfo, nvml.Return) + + // DeviceGetPowerManagementDefaultLimitFunc mocks the DeviceGetPowerManagementDefaultLimit method. + DeviceGetPowerManagementDefaultLimitFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetPowerManagementLimitFunc mocks the DeviceGetPowerManagementLimit method. + DeviceGetPowerManagementLimitFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetPowerManagementLimitConstraintsFunc mocks the DeviceGetPowerManagementLimitConstraints method. + DeviceGetPowerManagementLimitConstraintsFunc func(device nvml.Device) (uint32, uint32, nvml.Return) + + // DeviceGetPowerManagementModeFunc mocks the DeviceGetPowerManagementMode method. + DeviceGetPowerManagementModeFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetPowerMizerMode_v1Func mocks the DeviceGetPowerMizerMode_v1 method. + DeviceGetPowerMizerMode_v1Func func(device nvml.Device) (nvml.DevicePowerMizerModes_v1, nvml.Return) + + // DeviceGetPowerSourceFunc mocks the DeviceGetPowerSource method. + DeviceGetPowerSourceFunc func(device nvml.Device) (nvml.PowerSource, nvml.Return) + + // DeviceGetPowerStateFunc mocks the DeviceGetPowerState method. + DeviceGetPowerStateFunc func(device nvml.Device) (nvml.Pstates, nvml.Return) + + // DeviceGetPowerUsageFunc mocks the DeviceGetPowerUsage method. + DeviceGetPowerUsageFunc func(device nvml.Device) (uint32, nvml.Return) + + // DeviceGetProcessUtilizationFunc mocks the DeviceGetProcessUtilization method. + DeviceGetProcessUtilizationFunc func(device nvml.Device, v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) + + // DeviceGetProcessesUtilizationInfoFunc mocks the DeviceGetProcessesUtilizationInfo method. + DeviceGetProcessesUtilizationInfoFunc func(device nvml.Device) (nvml.ProcessesUtilizationInfo, nvml.Return) + + // DeviceGetRemappedRowsFunc mocks the DeviceGetRemappedRows method. + DeviceGetRemappedRowsFunc func(device nvml.Device) (int, int, bool, bool, nvml.Return) + + // DeviceGetRepairStatusFunc mocks the DeviceGetRepairStatus method. + DeviceGetRepairStatusFunc func(device nvml.Device) (nvml.RepairStatus, nvml.Return) + + // DeviceGetRetiredPagesFunc mocks the DeviceGetRetiredPages method. + DeviceGetRetiredPagesFunc func(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) + + // DeviceGetRetiredPagesPendingStatusFunc mocks the DeviceGetRetiredPagesPendingStatus method. + DeviceGetRetiredPagesPendingStatusFunc func(device nvml.Device) (nvml.EnableState, nvml.Return) + + // DeviceGetRetiredPages_v2Func mocks the DeviceGetRetiredPages_v2 method. + DeviceGetRetiredPages_v2Func func(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) + + // DeviceGetRowRemapperHistogramFunc mocks the DeviceGetRowRemapperHistogram method. + DeviceGetRowRemapperHistogramFunc func(device nvml.Device) (nvml.RowRemapperHistogramValues, nvml.Return) + + // DeviceGetRunningProcessDetailListFunc mocks the DeviceGetRunningProcessDetailList method. + DeviceGetRunningProcessDetailListFunc func(device nvml.Device) (nvml.ProcessDetailList, nvml.Return) + + // DeviceGetSamplesFunc mocks the DeviceGetSamples method. + DeviceGetSamplesFunc func(device nvml.Device, samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) + + // DeviceGetSerialFunc mocks the DeviceGetSerial method. + DeviceGetSerialFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetSramEccErrorStatusFunc mocks the DeviceGetSramEccErrorStatus method. + DeviceGetSramEccErrorStatusFunc func(device nvml.Device) (nvml.EccSramErrorStatus, nvml.Return) + + // DeviceGetSramUniqueUncorrectedEccErrorCountsFunc mocks the DeviceGetSramUniqueUncorrectedEccErrorCounts method. + DeviceGetSramUniqueUncorrectedEccErrorCountsFunc func(device nvml.Device, eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return + + // DeviceGetSupportedClocksEventReasonsFunc mocks the DeviceGetSupportedClocksEventReasons method. + DeviceGetSupportedClocksEventReasonsFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetSupportedClocksThrottleReasonsFunc mocks the DeviceGetSupportedClocksThrottleReasons method. + DeviceGetSupportedClocksThrottleReasonsFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetSupportedEventTypesFunc mocks the DeviceGetSupportedEventTypes method. + DeviceGetSupportedEventTypesFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetSupportedGraphicsClocksFunc mocks the DeviceGetSupportedGraphicsClocks method. + DeviceGetSupportedGraphicsClocksFunc func(device nvml.Device, n int) (int, uint32, nvml.Return) + + // DeviceGetSupportedMemoryClocksFunc mocks the DeviceGetSupportedMemoryClocks method. + DeviceGetSupportedMemoryClocksFunc func(device nvml.Device) (int, uint32, nvml.Return) + + // DeviceGetSupportedPerformanceStatesFunc mocks the DeviceGetSupportedPerformanceStates method. + DeviceGetSupportedPerformanceStatesFunc func(device nvml.Device) ([]nvml.Pstates, nvml.Return) + + // DeviceGetSupportedVgpusFunc mocks the DeviceGetSupportedVgpus method. + DeviceGetSupportedVgpusFunc func(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) + + // DeviceGetTargetFanSpeedFunc mocks the DeviceGetTargetFanSpeed method. + DeviceGetTargetFanSpeedFunc func(device nvml.Device, n int) (int, nvml.Return) + + // DeviceGetTemperatureFunc mocks the DeviceGetTemperature method. + DeviceGetTemperatureFunc func(device nvml.Device, temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) + + // DeviceGetTemperatureThresholdFunc mocks the DeviceGetTemperatureThreshold method. + DeviceGetTemperatureThresholdFunc func(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) + + // DeviceGetTemperatureVFunc mocks the DeviceGetTemperatureV method. + DeviceGetTemperatureVFunc func(device nvml.Device) nvml.TemperatureHandler + + // DeviceGetThermalSettingsFunc mocks the DeviceGetThermalSettings method. + DeviceGetThermalSettingsFunc func(device nvml.Device, v uint32) (nvml.GpuThermalSettings, nvml.Return) + + // DeviceGetTopologyCommonAncestorFunc mocks the DeviceGetTopologyCommonAncestor method. + DeviceGetTopologyCommonAncestorFunc func(device1 nvml.Device, device2 nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) + + // DeviceGetTopologyNearestGpusFunc mocks the DeviceGetTopologyNearestGpus method. + DeviceGetTopologyNearestGpusFunc func(device nvml.Device, gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) + + // DeviceGetTotalEccErrorsFunc mocks the DeviceGetTotalEccErrors method. + DeviceGetTotalEccErrorsFunc func(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) + + // DeviceGetTotalEnergyConsumptionFunc mocks the DeviceGetTotalEnergyConsumption method. + DeviceGetTotalEnergyConsumptionFunc func(device nvml.Device) (uint64, nvml.Return) + + // DeviceGetUUIDFunc mocks the DeviceGetUUID method. + DeviceGetUUIDFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetUtilizationRatesFunc mocks the DeviceGetUtilizationRates method. + DeviceGetUtilizationRatesFunc func(device nvml.Device) (nvml.Utilization, nvml.Return) + + // DeviceGetVbiosVersionFunc mocks the DeviceGetVbiosVersion method. + DeviceGetVbiosVersionFunc func(device nvml.Device) (string, nvml.Return) + + // DeviceGetVgpuCapabilitiesFunc mocks the DeviceGetVgpuCapabilities method. + DeviceGetVgpuCapabilitiesFunc func(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) + + // DeviceGetVgpuHeterogeneousModeFunc mocks the DeviceGetVgpuHeterogeneousMode method. + DeviceGetVgpuHeterogeneousModeFunc func(device nvml.Device) (nvml.VgpuHeterogeneousMode, nvml.Return) + + // DeviceGetVgpuInstancesUtilizationInfoFunc mocks the DeviceGetVgpuInstancesUtilizationInfo method. + DeviceGetVgpuInstancesUtilizationInfoFunc func(device nvml.Device) (nvml.VgpuInstancesUtilizationInfo, nvml.Return) + + // DeviceGetVgpuMetadataFunc mocks the DeviceGetVgpuMetadata method. + DeviceGetVgpuMetadataFunc func(device nvml.Device) (nvml.VgpuPgpuMetadata, nvml.Return) + + // DeviceGetVgpuProcessUtilizationFunc mocks the DeviceGetVgpuProcessUtilization method. + DeviceGetVgpuProcessUtilizationFunc func(device nvml.Device, v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) + + // DeviceGetVgpuProcessesUtilizationInfoFunc mocks the DeviceGetVgpuProcessesUtilizationInfo method. + DeviceGetVgpuProcessesUtilizationInfoFunc func(device nvml.Device) (nvml.VgpuProcessesUtilizationInfo, nvml.Return) + + // DeviceGetVgpuSchedulerCapabilitiesFunc mocks the DeviceGetVgpuSchedulerCapabilities method. + DeviceGetVgpuSchedulerCapabilitiesFunc func(device nvml.Device) (nvml.VgpuSchedulerCapabilities, nvml.Return) + + // DeviceGetVgpuSchedulerLogFunc mocks the DeviceGetVgpuSchedulerLog method. + DeviceGetVgpuSchedulerLogFunc func(device nvml.Device) (nvml.VgpuSchedulerLog, nvml.Return) + + // DeviceGetVgpuSchedulerStateFunc mocks the DeviceGetVgpuSchedulerState method. + DeviceGetVgpuSchedulerStateFunc func(device nvml.Device) (nvml.VgpuSchedulerGetState, nvml.Return) + + // DeviceGetVgpuTypeCreatablePlacementsFunc mocks the DeviceGetVgpuTypeCreatablePlacements method. + DeviceGetVgpuTypeCreatablePlacementsFunc func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) + + // DeviceGetVgpuTypeSupportedPlacementsFunc mocks the DeviceGetVgpuTypeSupportedPlacements method. + DeviceGetVgpuTypeSupportedPlacementsFunc func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) + + // DeviceGetVgpuUtilizationFunc mocks the DeviceGetVgpuUtilization method. + DeviceGetVgpuUtilizationFunc func(device nvml.Device, v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) + + // DeviceGetViolationStatusFunc mocks the DeviceGetViolationStatus method. + DeviceGetViolationStatusFunc func(device nvml.Device, perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) + + // DeviceGetVirtualizationModeFunc mocks the DeviceGetVirtualizationMode method. + DeviceGetVirtualizationModeFunc func(device nvml.Device) (nvml.GpuVirtualizationMode, nvml.Return) + + // DeviceIsMigDeviceHandleFunc mocks the DeviceIsMigDeviceHandle method. + DeviceIsMigDeviceHandleFunc func(device nvml.Device) (bool, nvml.Return) + + // DeviceModifyDrainStateFunc mocks the DeviceModifyDrainState method. + DeviceModifyDrainStateFunc func(pciInfo *nvml.PciInfo, enableState nvml.EnableState) nvml.Return + + // DeviceOnSameBoardFunc mocks the DeviceOnSameBoard method. + DeviceOnSameBoardFunc func(device1 nvml.Device, device2 nvml.Device) (int, nvml.Return) + + // DevicePowerSmoothingActivatePresetProfileFunc mocks the DevicePowerSmoothingActivatePresetProfile method. + DevicePowerSmoothingActivatePresetProfileFunc func(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return + + // DevicePowerSmoothingSetStateFunc mocks the DevicePowerSmoothingSetState method. + DevicePowerSmoothingSetStateFunc func(device nvml.Device, powerSmoothingState *nvml.PowerSmoothingState) nvml.Return + + // DevicePowerSmoothingUpdatePresetProfileParamFunc mocks the DevicePowerSmoothingUpdatePresetProfileParam method. + DevicePowerSmoothingUpdatePresetProfileParamFunc func(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return + + // DeviceQueryDrainStateFunc mocks the DeviceQueryDrainState method. + DeviceQueryDrainStateFunc func(pciInfo *nvml.PciInfo) (nvml.EnableState, nvml.Return) + + // DeviceReadWritePRM_v1Func mocks the DeviceReadWritePRM_v1 method. + DeviceReadWritePRM_v1Func func(device nvml.Device, pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return + + // DeviceRegisterEventsFunc mocks the DeviceRegisterEvents method. + DeviceRegisterEventsFunc func(device nvml.Device, v uint64, eventSet nvml.EventSet) nvml.Return + + // DeviceRemoveGpuFunc mocks the DeviceRemoveGpu method. + DeviceRemoveGpuFunc func(pciInfo *nvml.PciInfo) nvml.Return + + // DeviceRemoveGpu_v2Func mocks the DeviceRemoveGpu_v2 method. + DeviceRemoveGpu_v2Func func(pciInfo *nvml.PciInfo, detachGpuState nvml.DetachGpuState, pcieLinkState nvml.PcieLinkState) nvml.Return + + // DeviceResetApplicationsClocksFunc mocks the DeviceResetApplicationsClocks method. + DeviceResetApplicationsClocksFunc func(device nvml.Device) nvml.Return + + // DeviceResetGpuLockedClocksFunc mocks the DeviceResetGpuLockedClocks method. + DeviceResetGpuLockedClocksFunc func(device nvml.Device) nvml.Return + + // DeviceResetMemoryLockedClocksFunc mocks the DeviceResetMemoryLockedClocks method. + DeviceResetMemoryLockedClocksFunc func(device nvml.Device) nvml.Return + + // DeviceResetNvLinkErrorCountersFunc mocks the DeviceResetNvLinkErrorCounters method. + DeviceResetNvLinkErrorCountersFunc func(device nvml.Device, n int) nvml.Return + + // DeviceResetNvLinkUtilizationCounterFunc mocks the DeviceResetNvLinkUtilizationCounter method. + DeviceResetNvLinkUtilizationCounterFunc func(device nvml.Device, n1 int, n2 int) nvml.Return + + // DeviceSetAPIRestrictionFunc mocks the DeviceSetAPIRestriction method. + DeviceSetAPIRestrictionFunc func(device nvml.Device, restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return + + // DeviceSetAccountingModeFunc mocks the DeviceSetAccountingMode method. + DeviceSetAccountingModeFunc func(device nvml.Device, enableState nvml.EnableState) nvml.Return + + // DeviceSetApplicationsClocksFunc mocks the DeviceSetApplicationsClocks method. + DeviceSetApplicationsClocksFunc func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return + + // DeviceSetAutoBoostedClocksEnabledFunc mocks the DeviceSetAutoBoostedClocksEnabled method. + DeviceSetAutoBoostedClocksEnabledFunc func(device nvml.Device, enableState nvml.EnableState) nvml.Return + + // DeviceSetClockOffsetsFunc mocks the DeviceSetClockOffsets method. + DeviceSetClockOffsetsFunc func(device nvml.Device, clockOffset nvml.ClockOffset) nvml.Return + + // DeviceSetComputeModeFunc mocks the DeviceSetComputeMode method. + DeviceSetComputeModeFunc func(device nvml.Device, computeMode nvml.ComputeMode) nvml.Return + + // DeviceSetConfComputeUnprotectedMemSizeFunc mocks the DeviceSetConfComputeUnprotectedMemSize method. + DeviceSetConfComputeUnprotectedMemSizeFunc func(device nvml.Device, v uint64) nvml.Return + + // DeviceSetCpuAffinityFunc mocks the DeviceSetCpuAffinity method. + DeviceSetCpuAffinityFunc func(device nvml.Device) nvml.Return + + // DeviceSetDefaultAutoBoostedClocksEnabledFunc mocks the DeviceSetDefaultAutoBoostedClocksEnabled method. + DeviceSetDefaultAutoBoostedClocksEnabledFunc func(device nvml.Device, enableState nvml.EnableState, v uint32) nvml.Return + + // DeviceSetDefaultFanSpeed_v2Func mocks the DeviceSetDefaultFanSpeed_v2 method. + DeviceSetDefaultFanSpeed_v2Func func(device nvml.Device, n int) nvml.Return + + // DeviceSetDramEncryptionModeFunc mocks the DeviceSetDramEncryptionMode method. + DeviceSetDramEncryptionModeFunc func(device nvml.Device, dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return + + // DeviceSetDriverModelFunc mocks the DeviceSetDriverModel method. + DeviceSetDriverModelFunc func(device nvml.Device, driverModel nvml.DriverModel, v uint32) nvml.Return + + // DeviceSetEccModeFunc mocks the DeviceSetEccMode method. + DeviceSetEccModeFunc func(device nvml.Device, enableState nvml.EnableState) nvml.Return + + // DeviceSetFanControlPolicyFunc mocks the DeviceSetFanControlPolicy method. + DeviceSetFanControlPolicyFunc func(device nvml.Device, n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return + + // DeviceSetFanSpeed_v2Func mocks the DeviceSetFanSpeed_v2 method. + DeviceSetFanSpeed_v2Func func(device nvml.Device, n1 int, n2 int) nvml.Return + + // DeviceSetGpcClkVfOffsetFunc mocks the DeviceSetGpcClkVfOffset method. + DeviceSetGpcClkVfOffsetFunc func(device nvml.Device, n int) nvml.Return + + // DeviceSetGpuLockedClocksFunc mocks the DeviceSetGpuLockedClocks method. + DeviceSetGpuLockedClocksFunc func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return + + // DeviceSetGpuOperationModeFunc mocks the DeviceSetGpuOperationMode method. + DeviceSetGpuOperationModeFunc func(device nvml.Device, gpuOperationMode nvml.GpuOperationMode) nvml.Return + + // DeviceSetMemClkVfOffsetFunc mocks the DeviceSetMemClkVfOffset method. + DeviceSetMemClkVfOffsetFunc func(device nvml.Device, n int) nvml.Return + + // DeviceSetMemoryLockedClocksFunc mocks the DeviceSetMemoryLockedClocks method. + DeviceSetMemoryLockedClocksFunc func(device nvml.Device, v1 uint32, v2 uint32) nvml.Return + + // DeviceSetMigModeFunc mocks the DeviceSetMigMode method. + DeviceSetMigModeFunc func(device nvml.Device, n int) (nvml.Return, nvml.Return) + + // DeviceSetNvLinkDeviceLowPowerThresholdFunc mocks the DeviceSetNvLinkDeviceLowPowerThreshold method. + DeviceSetNvLinkDeviceLowPowerThresholdFunc func(device nvml.Device, nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return + + // DeviceSetNvLinkUtilizationControlFunc mocks the DeviceSetNvLinkUtilizationControl method. + DeviceSetNvLinkUtilizationControlFunc func(device nvml.Device, n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return + + // DeviceSetNvlinkBwModeFunc mocks the DeviceSetNvlinkBwMode method. + DeviceSetNvlinkBwModeFunc func(device nvml.Device, nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return + + // DeviceSetPersistenceModeFunc mocks the DeviceSetPersistenceMode method. + DeviceSetPersistenceModeFunc func(device nvml.Device, enableState nvml.EnableState) nvml.Return + + // DeviceSetPowerManagementLimitFunc mocks the DeviceSetPowerManagementLimit method. + DeviceSetPowerManagementLimitFunc func(device nvml.Device, v uint32) nvml.Return + + // DeviceSetPowerManagementLimit_v2Func mocks the DeviceSetPowerManagementLimit_v2 method. + DeviceSetPowerManagementLimit_v2Func func(device nvml.Device, powerValue_v2 *nvml.PowerValue_v2) nvml.Return + + // DeviceSetTemperatureThresholdFunc mocks the DeviceSetTemperatureThreshold method. + DeviceSetTemperatureThresholdFunc func(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return + + // DeviceSetVgpuCapabilitiesFunc mocks the DeviceSetVgpuCapabilities method. + DeviceSetVgpuCapabilitiesFunc func(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return + + // DeviceSetVgpuHeterogeneousModeFunc mocks the DeviceSetVgpuHeterogeneousMode method. + DeviceSetVgpuHeterogeneousModeFunc func(device nvml.Device, vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return + + // DeviceSetVgpuSchedulerStateFunc mocks the DeviceSetVgpuSchedulerState method. + DeviceSetVgpuSchedulerStateFunc func(device nvml.Device, vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return + + // DeviceSetVirtualizationModeFunc mocks the DeviceSetVirtualizationMode method. + DeviceSetVirtualizationModeFunc func(device nvml.Device, gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return + + // DeviceValidateInforomFunc mocks the DeviceValidateInforom method. + DeviceValidateInforomFunc func(device nvml.Device) nvml.Return + + // DeviceWorkloadPowerProfileClearRequestedProfilesFunc mocks the DeviceWorkloadPowerProfileClearRequestedProfiles method. + DeviceWorkloadPowerProfileClearRequestedProfilesFunc func(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return + + // DeviceWorkloadPowerProfileGetCurrentProfilesFunc mocks the DeviceWorkloadPowerProfileGetCurrentProfiles method. + DeviceWorkloadPowerProfileGetCurrentProfilesFunc func(device nvml.Device) (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) + + // DeviceWorkloadPowerProfileGetProfilesInfoFunc mocks the DeviceWorkloadPowerProfileGetProfilesInfo method. + DeviceWorkloadPowerProfileGetProfilesInfoFunc func(device nvml.Device) (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) + + // DeviceWorkloadPowerProfileSetRequestedProfilesFunc mocks the DeviceWorkloadPowerProfileSetRequestedProfiles method. + DeviceWorkloadPowerProfileSetRequestedProfilesFunc func(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return + + // ErrorStringFunc mocks the ErrorString method. + ErrorStringFunc func(returnMoqParam nvml.Return) string + + // EventSetCreateFunc mocks the EventSetCreate method. + EventSetCreateFunc func() (nvml.EventSet, nvml.Return) + + // EventSetFreeFunc mocks the EventSetFree method. + EventSetFreeFunc func(eventSet nvml.EventSet) nvml.Return + + // EventSetWaitFunc mocks the EventSetWait method. + EventSetWaitFunc func(eventSet nvml.EventSet, v uint32) (nvml.EventData, nvml.Return) + + // ExtensionsFunc mocks the Extensions method. + ExtensionsFunc func() nvml.ExtendedInterface + + // GetExcludedDeviceCountFunc mocks the GetExcludedDeviceCount method. + GetExcludedDeviceCountFunc func() (int, nvml.Return) + + // GetExcludedDeviceInfoByIndexFunc mocks the GetExcludedDeviceInfoByIndex method. + GetExcludedDeviceInfoByIndexFunc func(n int) (nvml.ExcludedDeviceInfo, nvml.Return) + + // GetVgpuCompatibilityFunc mocks the GetVgpuCompatibility method. + GetVgpuCompatibilityFunc func(vgpuMetadata *nvml.VgpuMetadata, vgpuPgpuMetadata *nvml.VgpuPgpuMetadata) (nvml.VgpuPgpuCompatibility, nvml.Return) + + // GetVgpuDriverCapabilitiesFunc mocks the GetVgpuDriverCapabilities method. + GetVgpuDriverCapabilitiesFunc func(vgpuDriverCapability nvml.VgpuDriverCapability) (bool, nvml.Return) + + // GetVgpuVersionFunc mocks the GetVgpuVersion method. + GetVgpuVersionFunc func() (nvml.VgpuVersion, nvml.VgpuVersion, nvml.Return) + + // GpmMetricsGetFunc mocks the GpmMetricsGet method. + GpmMetricsGetFunc func(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.Return + + // GpmMetricsGetVFunc mocks the GpmMetricsGetV method. + GpmMetricsGetVFunc func(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.GpmMetricsGetVType + + // GpmMigSampleGetFunc mocks the GpmMigSampleGet method. + GpmMigSampleGetFunc func(device nvml.Device, n int, gpmSample nvml.GpmSample) nvml.Return + + // GpmQueryDeviceSupportFunc mocks the GpmQueryDeviceSupport method. + GpmQueryDeviceSupportFunc func(device nvml.Device) (nvml.GpmSupport, nvml.Return) + + // GpmQueryDeviceSupportVFunc mocks the GpmQueryDeviceSupportV method. + GpmQueryDeviceSupportVFunc func(device nvml.Device) nvml.GpmSupportV + + // GpmQueryIfStreamingEnabledFunc mocks the GpmQueryIfStreamingEnabled method. + GpmQueryIfStreamingEnabledFunc func(device nvml.Device) (uint32, nvml.Return) + + // GpmSampleAllocFunc mocks the GpmSampleAlloc method. + GpmSampleAllocFunc func() (nvml.GpmSample, nvml.Return) + + // GpmSampleFreeFunc mocks the GpmSampleFree method. + GpmSampleFreeFunc func(gpmSample nvml.GpmSample) nvml.Return + + // GpmSampleGetFunc mocks the GpmSampleGet method. + GpmSampleGetFunc func(device nvml.Device, gpmSample nvml.GpmSample) nvml.Return + + // GpmSetStreamingEnabledFunc mocks the GpmSetStreamingEnabled method. + GpmSetStreamingEnabledFunc func(device nvml.Device, v uint32) nvml.Return + + // GpuInstanceCreateComputeInstanceFunc mocks the GpuInstanceCreateComputeInstance method. + GpuInstanceCreateComputeInstanceFunc func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) + + // GpuInstanceCreateComputeInstanceWithPlacementFunc mocks the GpuInstanceCreateComputeInstanceWithPlacement method. + GpuInstanceCreateComputeInstanceWithPlacementFunc func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) + + // GpuInstanceDestroyFunc mocks the GpuInstanceDestroy method. + GpuInstanceDestroyFunc func(gpuInstance nvml.GpuInstance) nvml.Return + + // GpuInstanceGetActiveVgpusFunc mocks the GpuInstanceGetActiveVgpus method. + GpuInstanceGetActiveVgpusFunc func(gpuInstance nvml.GpuInstance) (nvml.ActiveVgpuInstanceInfo, nvml.Return) + + // GpuInstanceGetComputeInstanceByIdFunc mocks the GpuInstanceGetComputeInstanceById method. + GpuInstanceGetComputeInstanceByIdFunc func(gpuInstance nvml.GpuInstance, n int) (nvml.ComputeInstance, nvml.Return) + + // GpuInstanceGetComputeInstancePossiblePlacementsFunc mocks the GpuInstanceGetComputeInstancePossiblePlacements method. + GpuInstanceGetComputeInstancePossiblePlacementsFunc func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) + + // GpuInstanceGetComputeInstanceProfileInfoFunc mocks the GpuInstanceGetComputeInstanceProfileInfo method. + GpuInstanceGetComputeInstanceProfileInfoFunc func(gpuInstance nvml.GpuInstance, n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) + + // GpuInstanceGetComputeInstanceProfileInfoVFunc mocks the GpuInstanceGetComputeInstanceProfileInfoV method. + GpuInstanceGetComputeInstanceProfileInfoVFunc func(gpuInstance nvml.GpuInstance, n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler + + // GpuInstanceGetComputeInstanceRemainingCapacityFunc mocks the GpuInstanceGetComputeInstanceRemainingCapacity method. + GpuInstanceGetComputeInstanceRemainingCapacityFunc func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) + + // GpuInstanceGetComputeInstancesFunc mocks the GpuInstanceGetComputeInstances method. + GpuInstanceGetComputeInstancesFunc func(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) + + // GpuInstanceGetCreatableVgpusFunc mocks the GpuInstanceGetCreatableVgpus method. + GpuInstanceGetCreatableVgpusFunc func(gpuInstance nvml.GpuInstance) (nvml.VgpuTypeIdInfo, nvml.Return) + + // GpuInstanceGetInfoFunc mocks the GpuInstanceGetInfo method. + GpuInstanceGetInfoFunc func(gpuInstance nvml.GpuInstance) (nvml.GpuInstanceInfo, nvml.Return) + + // GpuInstanceGetVgpuHeterogeneousModeFunc mocks the GpuInstanceGetVgpuHeterogeneousMode method. + GpuInstanceGetVgpuHeterogeneousModeFunc func(gpuInstance nvml.GpuInstance) (nvml.VgpuHeterogeneousMode, nvml.Return) + + // GpuInstanceGetVgpuSchedulerLogFunc mocks the GpuInstanceGetVgpuSchedulerLog method. + GpuInstanceGetVgpuSchedulerLogFunc func(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerLogInfo, nvml.Return) + + // GpuInstanceGetVgpuSchedulerStateFunc mocks the GpuInstanceGetVgpuSchedulerState method. + GpuInstanceGetVgpuSchedulerStateFunc func(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerStateInfo, nvml.Return) + + // GpuInstanceGetVgpuTypeCreatablePlacementsFunc mocks the GpuInstanceGetVgpuTypeCreatablePlacements method. + GpuInstanceGetVgpuTypeCreatablePlacementsFunc func(gpuInstance nvml.GpuInstance) (nvml.VgpuCreatablePlacementInfo, nvml.Return) + + // GpuInstanceSetVgpuHeterogeneousModeFunc mocks the GpuInstanceSetVgpuHeterogeneousMode method. + GpuInstanceSetVgpuHeterogeneousModeFunc func(gpuInstance nvml.GpuInstance, vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return + + // GpuInstanceSetVgpuSchedulerStateFunc mocks the GpuInstanceSetVgpuSchedulerState method. + GpuInstanceSetVgpuSchedulerStateFunc func(gpuInstance nvml.GpuInstance, vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return + + // InitFunc mocks the Init method. + InitFunc func() nvml.Return + + // InitWithFlagsFunc mocks the InitWithFlags method. + InitWithFlagsFunc func(v uint32) nvml.Return + + // SetVgpuVersionFunc mocks the SetVgpuVersion method. + SetVgpuVersionFunc func(vgpuVersion *nvml.VgpuVersion) nvml.Return + + // ShutdownFunc mocks the Shutdown method. + ShutdownFunc func() nvml.Return + + // SystemEventSetCreateFunc mocks the SystemEventSetCreate method. + SystemEventSetCreateFunc func(systemEventSetCreateRequest *nvml.SystemEventSetCreateRequest) nvml.Return + + // SystemEventSetFreeFunc mocks the SystemEventSetFree method. + SystemEventSetFreeFunc func(systemEventSetFreeRequest *nvml.SystemEventSetFreeRequest) nvml.Return + + // SystemEventSetWaitFunc mocks the SystemEventSetWait method. + SystemEventSetWaitFunc func(systemEventSetWaitRequest *nvml.SystemEventSetWaitRequest) nvml.Return + + // SystemGetConfComputeCapabilitiesFunc mocks the SystemGetConfComputeCapabilities method. + SystemGetConfComputeCapabilitiesFunc func() (nvml.ConfComputeSystemCaps, nvml.Return) + + // SystemGetConfComputeGpusReadyStateFunc mocks the SystemGetConfComputeGpusReadyState method. + SystemGetConfComputeGpusReadyStateFunc func() (uint32, nvml.Return) + + // SystemGetConfComputeKeyRotationThresholdInfoFunc mocks the SystemGetConfComputeKeyRotationThresholdInfo method. + SystemGetConfComputeKeyRotationThresholdInfoFunc func() (nvml.ConfComputeGetKeyRotationThresholdInfo, nvml.Return) + + // SystemGetConfComputeSettingsFunc mocks the SystemGetConfComputeSettings method. + SystemGetConfComputeSettingsFunc func() (nvml.SystemConfComputeSettings, nvml.Return) + + // SystemGetConfComputeStateFunc mocks the SystemGetConfComputeState method. + SystemGetConfComputeStateFunc func() (nvml.ConfComputeSystemState, nvml.Return) + + // SystemGetCudaDriverVersionFunc mocks the SystemGetCudaDriverVersion method. + SystemGetCudaDriverVersionFunc func() (int, nvml.Return) + + // SystemGetCudaDriverVersion_v2Func mocks the SystemGetCudaDriverVersion_v2 method. + SystemGetCudaDriverVersion_v2Func func() (int, nvml.Return) + + // SystemGetDriverBranchFunc mocks the SystemGetDriverBranch method. + SystemGetDriverBranchFunc func() (nvml.SystemDriverBranchInfo, nvml.Return) + + // SystemGetDriverVersionFunc mocks the SystemGetDriverVersion method. + SystemGetDriverVersionFunc func() (string, nvml.Return) + + // SystemGetHicVersionFunc mocks the SystemGetHicVersion method. + SystemGetHicVersionFunc func() ([]nvml.HwbcEntry, nvml.Return) + + // SystemGetNVMLVersionFunc mocks the SystemGetNVMLVersion method. + SystemGetNVMLVersionFunc func() (string, nvml.Return) + + // SystemGetNvlinkBwModeFunc mocks the SystemGetNvlinkBwMode method. + SystemGetNvlinkBwModeFunc func() (uint32, nvml.Return) + + // SystemGetProcessNameFunc mocks the SystemGetProcessName method. + SystemGetProcessNameFunc func(n int) (string, nvml.Return) + + // SystemGetTopologyGpuSetFunc mocks the SystemGetTopologyGpuSet method. + SystemGetTopologyGpuSetFunc func(n int) ([]nvml.Device, nvml.Return) + + // SystemRegisterEventsFunc mocks the SystemRegisterEvents method. + SystemRegisterEventsFunc func(systemRegisterEventRequest *nvml.SystemRegisterEventRequest) nvml.Return + + // SystemSetConfComputeGpusReadyStateFunc mocks the SystemSetConfComputeGpusReadyState method. + SystemSetConfComputeGpusReadyStateFunc func(v uint32) nvml.Return + + // SystemSetConfComputeKeyRotationThresholdInfoFunc mocks the SystemSetConfComputeKeyRotationThresholdInfo method. + SystemSetConfComputeKeyRotationThresholdInfoFunc func(confComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo) nvml.Return + + // SystemSetNvlinkBwModeFunc mocks the SystemSetNvlinkBwMode method. + SystemSetNvlinkBwModeFunc func(v uint32) nvml.Return + + // UnitGetCountFunc mocks the UnitGetCount method. + UnitGetCountFunc func() (int, nvml.Return) + + // UnitGetDevicesFunc mocks the UnitGetDevices method. + UnitGetDevicesFunc func(unit nvml.Unit) ([]nvml.Device, nvml.Return) + + // UnitGetFanSpeedInfoFunc mocks the UnitGetFanSpeedInfo method. + UnitGetFanSpeedInfoFunc func(unit nvml.Unit) (nvml.UnitFanSpeeds, nvml.Return) + + // UnitGetHandleByIndexFunc mocks the UnitGetHandleByIndex method. + UnitGetHandleByIndexFunc func(n int) (nvml.Unit, nvml.Return) + + // UnitGetLedStateFunc mocks the UnitGetLedState method. + UnitGetLedStateFunc func(unit nvml.Unit) (nvml.LedState, nvml.Return) + + // UnitGetPsuInfoFunc mocks the UnitGetPsuInfo method. + UnitGetPsuInfoFunc func(unit nvml.Unit) (nvml.PSUInfo, nvml.Return) + + // UnitGetTemperatureFunc mocks the UnitGetTemperature method. + UnitGetTemperatureFunc func(unit nvml.Unit, n int) (uint32, nvml.Return) + + // UnitGetUnitInfoFunc mocks the UnitGetUnitInfo method. + UnitGetUnitInfoFunc func(unit nvml.Unit) (nvml.UnitInfo, nvml.Return) + + // UnitSetLedStateFunc mocks the UnitSetLedState method. + UnitSetLedStateFunc func(unit nvml.Unit, ledColor nvml.LedColor) nvml.Return + + // VgpuInstanceClearAccountingPidsFunc mocks the VgpuInstanceClearAccountingPids method. + VgpuInstanceClearAccountingPidsFunc func(vgpuInstance nvml.VgpuInstance) nvml.Return + + // VgpuInstanceGetAccountingModeFunc mocks the VgpuInstanceGetAccountingMode method. + VgpuInstanceGetAccountingModeFunc func(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) + + // VgpuInstanceGetAccountingPidsFunc mocks the VgpuInstanceGetAccountingPids method. + VgpuInstanceGetAccountingPidsFunc func(vgpuInstance nvml.VgpuInstance) ([]int, nvml.Return) + + // VgpuInstanceGetAccountingStatsFunc mocks the VgpuInstanceGetAccountingStats method. + VgpuInstanceGetAccountingStatsFunc func(vgpuInstance nvml.VgpuInstance, n int) (nvml.AccountingStats, nvml.Return) + + // VgpuInstanceGetEccModeFunc mocks the VgpuInstanceGetEccMode method. + VgpuInstanceGetEccModeFunc func(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) + + // VgpuInstanceGetEncoderCapacityFunc mocks the VgpuInstanceGetEncoderCapacity method. + VgpuInstanceGetEncoderCapacityFunc func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) + + // VgpuInstanceGetEncoderSessionsFunc mocks the VgpuInstanceGetEncoderSessions method. + VgpuInstanceGetEncoderSessionsFunc func(vgpuInstance nvml.VgpuInstance) (int, nvml.EncoderSessionInfo, nvml.Return) + + // VgpuInstanceGetEncoderStatsFunc mocks the VgpuInstanceGetEncoderStats method. + VgpuInstanceGetEncoderStatsFunc func(vgpuInstance nvml.VgpuInstance) (int, uint32, uint32, nvml.Return) + + // VgpuInstanceGetFBCSessionsFunc mocks the VgpuInstanceGetFBCSessions method. + VgpuInstanceGetFBCSessionsFunc func(vgpuInstance nvml.VgpuInstance) (int, nvml.FBCSessionInfo, nvml.Return) + + // VgpuInstanceGetFBCStatsFunc mocks the VgpuInstanceGetFBCStats method. + VgpuInstanceGetFBCStatsFunc func(vgpuInstance nvml.VgpuInstance) (nvml.FBCStats, nvml.Return) + + // VgpuInstanceGetFbUsageFunc mocks the VgpuInstanceGetFbUsage method. + VgpuInstanceGetFbUsageFunc func(vgpuInstance nvml.VgpuInstance) (uint64, nvml.Return) + + // VgpuInstanceGetFrameRateLimitFunc mocks the VgpuInstanceGetFrameRateLimit method. + VgpuInstanceGetFrameRateLimitFunc func(vgpuInstance nvml.VgpuInstance) (uint32, nvml.Return) + + // VgpuInstanceGetGpuInstanceIdFunc mocks the VgpuInstanceGetGpuInstanceId method. + VgpuInstanceGetGpuInstanceIdFunc func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) + + // VgpuInstanceGetGpuPciIdFunc mocks the VgpuInstanceGetGpuPciId method. + VgpuInstanceGetGpuPciIdFunc func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) + + // VgpuInstanceGetLicenseInfoFunc mocks the VgpuInstanceGetLicenseInfo method. + VgpuInstanceGetLicenseInfoFunc func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuLicenseInfo, nvml.Return) + + // VgpuInstanceGetLicenseStatusFunc mocks the VgpuInstanceGetLicenseStatus method. + VgpuInstanceGetLicenseStatusFunc func(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) + + // VgpuInstanceGetMdevUUIDFunc mocks the VgpuInstanceGetMdevUUID method. + VgpuInstanceGetMdevUUIDFunc func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) + + // VgpuInstanceGetMetadataFunc mocks the VgpuInstanceGetMetadata method. + VgpuInstanceGetMetadataFunc func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuMetadata, nvml.Return) + + // VgpuInstanceGetRuntimeStateSizeFunc mocks the VgpuInstanceGetRuntimeStateSize method. + VgpuInstanceGetRuntimeStateSizeFunc func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuRuntimeState, nvml.Return) + + // VgpuInstanceGetTypeFunc mocks the VgpuInstanceGetType method. + VgpuInstanceGetTypeFunc func(vgpuInstance nvml.VgpuInstance) (nvml.VgpuTypeId, nvml.Return) + + // VgpuInstanceGetUUIDFunc mocks the VgpuInstanceGetUUID method. + VgpuInstanceGetUUIDFunc func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) + + // VgpuInstanceGetVmDriverVersionFunc mocks the VgpuInstanceGetVmDriverVersion method. + VgpuInstanceGetVmDriverVersionFunc func(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) + + // VgpuInstanceGetVmIDFunc mocks the VgpuInstanceGetVmID method. + VgpuInstanceGetVmIDFunc func(vgpuInstance nvml.VgpuInstance) (string, nvml.VgpuVmIdType, nvml.Return) + + // VgpuInstanceSetEncoderCapacityFunc mocks the VgpuInstanceSetEncoderCapacity method. + VgpuInstanceSetEncoderCapacityFunc func(vgpuInstance nvml.VgpuInstance, n int) nvml.Return + + // VgpuTypeGetBAR1InfoFunc mocks the VgpuTypeGetBAR1Info method. + VgpuTypeGetBAR1InfoFunc func(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuTypeBar1Info, nvml.Return) + + // VgpuTypeGetCapabilitiesFunc mocks the VgpuTypeGetCapabilities method. + VgpuTypeGetCapabilitiesFunc func(vgpuTypeId nvml.VgpuTypeId, vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) + + // VgpuTypeGetClassFunc mocks the VgpuTypeGetClass method. + VgpuTypeGetClassFunc func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) + + // VgpuTypeGetDeviceIDFunc mocks the VgpuTypeGetDeviceID method. + VgpuTypeGetDeviceIDFunc func(vgpuTypeId nvml.VgpuTypeId) (uint64, uint64, nvml.Return) + + // VgpuTypeGetFrameRateLimitFunc mocks the VgpuTypeGetFrameRateLimit method. + VgpuTypeGetFrameRateLimitFunc func(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) + + // VgpuTypeGetFramebufferSizeFunc mocks the VgpuTypeGetFramebufferSize method. + VgpuTypeGetFramebufferSizeFunc func(vgpuTypeId nvml.VgpuTypeId) (uint64, nvml.Return) + + // VgpuTypeGetGpuInstanceProfileIdFunc mocks the VgpuTypeGetGpuInstanceProfileId method. + VgpuTypeGetGpuInstanceProfileIdFunc func(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) + + // VgpuTypeGetLicenseFunc mocks the VgpuTypeGetLicense method. + VgpuTypeGetLicenseFunc func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) + + // VgpuTypeGetMaxInstancesFunc mocks the VgpuTypeGetMaxInstances method. + VgpuTypeGetMaxInstancesFunc func(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) + + // VgpuTypeGetMaxInstancesPerGpuInstanceFunc mocks the VgpuTypeGetMaxInstancesPerGpuInstance method. + VgpuTypeGetMaxInstancesPerGpuInstanceFunc func(vgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance) nvml.Return + + // VgpuTypeGetMaxInstancesPerVmFunc mocks the VgpuTypeGetMaxInstancesPerVm method. + VgpuTypeGetMaxInstancesPerVmFunc func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) + + // VgpuTypeGetNameFunc mocks the VgpuTypeGetName method. + VgpuTypeGetNameFunc func(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) + + // VgpuTypeGetNumDisplayHeadsFunc mocks the VgpuTypeGetNumDisplayHeads method. + VgpuTypeGetNumDisplayHeadsFunc func(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) + + // VgpuTypeGetResolutionFunc mocks the VgpuTypeGetResolution method. + VgpuTypeGetResolutionFunc func(vgpuTypeId nvml.VgpuTypeId, n int) (uint32, uint32, nvml.Return) + + // calls tracks calls to the methods. + calls struct { + // ComputeInstanceDestroy holds details about calls to the ComputeInstanceDestroy method. + ComputeInstanceDestroy []struct { + // ComputeInstance is the computeInstance argument value. + ComputeInstance nvml.ComputeInstance + } + // ComputeInstanceGetInfo holds details about calls to the ComputeInstanceGetInfo method. + ComputeInstanceGetInfo []struct { + // ComputeInstance is the computeInstance argument value. + ComputeInstance nvml.ComputeInstance + } + // DeviceClearAccountingPids holds details about calls to the DeviceClearAccountingPids method. + DeviceClearAccountingPids []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceClearCpuAffinity holds details about calls to the DeviceClearCpuAffinity method. + DeviceClearCpuAffinity []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceClearEccErrorCounts holds details about calls to the DeviceClearEccErrorCounts method. + DeviceClearEccErrorCounts []struct { + // Device is the device argument value. + Device nvml.Device + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // DeviceClearFieldValues holds details about calls to the DeviceClearFieldValues method. + DeviceClearFieldValues []struct { + // Device is the device argument value. + Device nvml.Device + // FieldValues is the fieldValues argument value. + FieldValues []nvml.FieldValue + } + // DeviceCreateGpuInstance holds details about calls to the DeviceCreateGpuInstance method. + DeviceCreateGpuInstance []struct { + // Device is the device argument value. + Device nvml.Device + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // DeviceCreateGpuInstanceWithPlacement holds details about calls to the DeviceCreateGpuInstanceWithPlacement method. + DeviceCreateGpuInstanceWithPlacement []struct { + // Device is the device argument value. + Device nvml.Device + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + // GpuInstancePlacement is the gpuInstancePlacement argument value. + GpuInstancePlacement *nvml.GpuInstancePlacement + } + // DeviceDiscoverGpus holds details about calls to the DeviceDiscoverGpus method. + DeviceDiscoverGpus []struct { + } + // DeviceFreezeNvLinkUtilizationCounter holds details about calls to the DeviceFreezeNvLinkUtilizationCounter method. + DeviceFreezeNvLinkUtilizationCounter []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceGetAPIRestriction holds details about calls to the DeviceGetAPIRestriction method. + DeviceGetAPIRestriction []struct { + // Device is the device argument value. + Device nvml.Device + // RestrictedAPI is the restrictedAPI argument value. + RestrictedAPI nvml.RestrictedAPI + } + // DeviceGetAccountingBufferSize holds details about calls to the DeviceGetAccountingBufferSize method. + DeviceGetAccountingBufferSize []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAccountingMode holds details about calls to the DeviceGetAccountingMode method. + DeviceGetAccountingMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAccountingPids holds details about calls to the DeviceGetAccountingPids method. + DeviceGetAccountingPids []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAccountingStats holds details about calls to the DeviceGetAccountingStats method. + DeviceGetAccountingStats []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint32 + } + // DeviceGetActiveVgpus holds details about calls to the DeviceGetActiveVgpus method. + DeviceGetActiveVgpus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAdaptiveClockInfoStatus holds details about calls to the DeviceGetAdaptiveClockInfoStatus method. + DeviceGetAdaptiveClockInfoStatus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAddressingMode holds details about calls to the DeviceGetAddressingMode method. + DeviceGetAddressingMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetApplicationsClock holds details about calls to the DeviceGetApplicationsClock method. + DeviceGetApplicationsClock []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // DeviceGetArchitecture holds details about calls to the DeviceGetArchitecture method. + DeviceGetArchitecture []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAttributes holds details about calls to the DeviceGetAttributes method. + DeviceGetAttributes []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetAutoBoostedClocksEnabled holds details about calls to the DeviceGetAutoBoostedClocksEnabled method. + DeviceGetAutoBoostedClocksEnabled []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBAR1MemoryInfo holds details about calls to the DeviceGetBAR1MemoryInfo method. + DeviceGetBAR1MemoryInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBoardId holds details about calls to the DeviceGetBoardId method. + DeviceGetBoardId []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBoardPartNumber holds details about calls to the DeviceGetBoardPartNumber method. + DeviceGetBoardPartNumber []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBrand holds details about calls to the DeviceGetBrand method. + DeviceGetBrand []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBridgeChipInfo holds details about calls to the DeviceGetBridgeChipInfo method. + DeviceGetBridgeChipInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetBusType holds details about calls to the DeviceGetBusType method. + DeviceGetBusType []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetC2cModeInfoV holds details about calls to the DeviceGetC2cModeInfoV method. + DeviceGetC2cModeInfoV []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCapabilities holds details about calls to the DeviceGetCapabilities method. + DeviceGetCapabilities []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetClkMonStatus holds details about calls to the DeviceGetClkMonStatus method. + DeviceGetClkMonStatus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetClock holds details about calls to the DeviceGetClock method. + DeviceGetClock []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + // ClockId is the clockId argument value. + ClockId nvml.ClockId + } + // DeviceGetClockInfo holds details about calls to the DeviceGetClockInfo method. + DeviceGetClockInfo []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // DeviceGetClockOffsets holds details about calls to the DeviceGetClockOffsets method. + DeviceGetClockOffsets []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetComputeInstanceId holds details about calls to the DeviceGetComputeInstanceId method. + DeviceGetComputeInstanceId []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetComputeMode holds details about calls to the DeviceGetComputeMode method. + DeviceGetComputeMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetComputeRunningProcesses holds details about calls to the DeviceGetComputeRunningProcesses method. + DeviceGetComputeRunningProcesses []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetConfComputeGpuAttestationReport holds details about calls to the DeviceGetConfComputeGpuAttestationReport method. + DeviceGetConfComputeGpuAttestationReport []struct { + // Device is the device argument value. + Device nvml.Device + // ConfComputeGpuAttestationReport is the confComputeGpuAttestationReport argument value. + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + } + // DeviceGetConfComputeGpuCertificate holds details about calls to the DeviceGetConfComputeGpuCertificate method. + DeviceGetConfComputeGpuCertificate []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetConfComputeMemSizeInfo holds details about calls to the DeviceGetConfComputeMemSizeInfo method. + DeviceGetConfComputeMemSizeInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetConfComputeProtectedMemoryUsage holds details about calls to the DeviceGetConfComputeProtectedMemoryUsage method. + DeviceGetConfComputeProtectedMemoryUsage []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCoolerInfo holds details about calls to the DeviceGetCoolerInfo method. + DeviceGetCoolerInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCount holds details about calls to the DeviceGetCount method. + DeviceGetCount []struct { + } + // DeviceGetCpuAffinity holds details about calls to the DeviceGetCpuAffinity method. + DeviceGetCpuAffinity []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetCpuAffinityWithinScope holds details about calls to the DeviceGetCpuAffinityWithinScope method. + DeviceGetCpuAffinityWithinScope []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // AffinityScope is the affinityScope argument value. + AffinityScope nvml.AffinityScope + } + // DeviceGetCreatableVgpus holds details about calls to the DeviceGetCreatableVgpus method. + DeviceGetCreatableVgpus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCudaComputeCapability holds details about calls to the DeviceGetCudaComputeCapability method. + DeviceGetCudaComputeCapability []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCurrPcieLinkGeneration holds details about calls to the DeviceGetCurrPcieLinkGeneration method. + DeviceGetCurrPcieLinkGeneration []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCurrPcieLinkWidth holds details about calls to the DeviceGetCurrPcieLinkWidth method. + DeviceGetCurrPcieLinkWidth []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCurrentClockFreqs holds details about calls to the DeviceGetCurrentClockFreqs method. + DeviceGetCurrentClockFreqs []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCurrentClocksEventReasons holds details about calls to the DeviceGetCurrentClocksEventReasons method. + DeviceGetCurrentClocksEventReasons []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetCurrentClocksThrottleReasons holds details about calls to the DeviceGetCurrentClocksThrottleReasons method. + DeviceGetCurrentClocksThrottleReasons []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDecoderUtilization holds details about calls to the DeviceGetDecoderUtilization method. + DeviceGetDecoderUtilization []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDefaultApplicationsClock holds details about calls to the DeviceGetDefaultApplicationsClock method. + DeviceGetDefaultApplicationsClock []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // DeviceGetDefaultEccMode holds details about calls to the DeviceGetDefaultEccMode method. + DeviceGetDefaultEccMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDetailedEccErrors holds details about calls to the DeviceGetDetailedEccErrors method. + DeviceGetDetailedEccErrors []struct { + // Device is the device argument value. + Device nvml.Device + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // DeviceGetDeviceHandleFromMigDeviceHandle holds details about calls to the DeviceGetDeviceHandleFromMigDeviceHandle method. + DeviceGetDeviceHandleFromMigDeviceHandle []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDisplayActive holds details about calls to the DeviceGetDisplayActive method. + DeviceGetDisplayActive []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDisplayMode holds details about calls to the DeviceGetDisplayMode method. + DeviceGetDisplayMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDramEncryptionMode holds details about calls to the DeviceGetDramEncryptionMode method. + DeviceGetDramEncryptionMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDriverModel holds details about calls to the DeviceGetDriverModel method. + DeviceGetDriverModel []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDriverModel_v2 holds details about calls to the DeviceGetDriverModel_v2 method. + DeviceGetDriverModel_v2 []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetDynamicPstatesInfo holds details about calls to the DeviceGetDynamicPstatesInfo method. + DeviceGetDynamicPstatesInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetEccMode holds details about calls to the DeviceGetEccMode method. + DeviceGetEccMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetEncoderCapacity holds details about calls to the DeviceGetEncoderCapacity method. + DeviceGetEncoderCapacity []struct { + // Device is the device argument value. + Device nvml.Device + // EncoderType is the encoderType argument value. + EncoderType nvml.EncoderType + } + // DeviceGetEncoderSessions holds details about calls to the DeviceGetEncoderSessions method. + DeviceGetEncoderSessions []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetEncoderStats holds details about calls to the DeviceGetEncoderStats method. + DeviceGetEncoderStats []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetEncoderUtilization holds details about calls to the DeviceGetEncoderUtilization method. + DeviceGetEncoderUtilization []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetEnforcedPowerLimit holds details about calls to the DeviceGetEnforcedPowerLimit method. + DeviceGetEnforcedPowerLimit []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetFBCSessions holds details about calls to the DeviceGetFBCSessions method. + DeviceGetFBCSessions []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetFBCStats holds details about calls to the DeviceGetFBCStats method. + DeviceGetFBCStats []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetFanControlPolicy_v2 holds details about calls to the DeviceGetFanControlPolicy_v2 method. + DeviceGetFanControlPolicy_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetFanSpeed holds details about calls to the DeviceGetFanSpeed method. + DeviceGetFanSpeed []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetFanSpeedRPM holds details about calls to the DeviceGetFanSpeedRPM method. + DeviceGetFanSpeedRPM []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetFanSpeed_v2 holds details about calls to the DeviceGetFanSpeed_v2 method. + DeviceGetFanSpeed_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetFieldValues holds details about calls to the DeviceGetFieldValues method. + DeviceGetFieldValues []struct { + // Device is the device argument value. + Device nvml.Device + // FieldValues is the fieldValues argument value. + FieldValues []nvml.FieldValue + } + // DeviceGetGpcClkMinMaxVfOffset holds details about calls to the DeviceGetGpcClkMinMaxVfOffset method. + DeviceGetGpcClkMinMaxVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpcClkVfOffset holds details about calls to the DeviceGetGpcClkVfOffset method. + DeviceGetGpcClkVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpuFabricInfo holds details about calls to the DeviceGetGpuFabricInfo method. + DeviceGetGpuFabricInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpuFabricInfoV holds details about calls to the DeviceGetGpuFabricInfoV method. + DeviceGetGpuFabricInfoV []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpuInstanceById holds details about calls to the DeviceGetGpuInstanceById method. + DeviceGetGpuInstanceById []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetGpuInstanceId holds details about calls to the DeviceGetGpuInstanceId method. + DeviceGetGpuInstanceId []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpuInstancePossiblePlacements holds details about calls to the DeviceGetGpuInstancePossiblePlacements method. + DeviceGetGpuInstancePossiblePlacements []struct { + // Device is the device argument value. + Device nvml.Device + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // DeviceGetGpuInstanceProfileInfo holds details about calls to the DeviceGetGpuInstanceProfileInfo method. + DeviceGetGpuInstanceProfileInfo []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetGpuInstanceProfileInfoByIdV holds details about calls to the DeviceGetGpuInstanceProfileInfoByIdV method. + DeviceGetGpuInstanceProfileInfoByIdV []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetGpuInstanceProfileInfoV holds details about calls to the DeviceGetGpuInstanceProfileInfoV method. + DeviceGetGpuInstanceProfileInfoV []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetGpuInstanceRemainingCapacity holds details about calls to the DeviceGetGpuInstanceRemainingCapacity method. + DeviceGetGpuInstanceRemainingCapacity []struct { + // Device is the device argument value. + Device nvml.Device + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // DeviceGetGpuInstances holds details about calls to the DeviceGetGpuInstances method. + DeviceGetGpuInstances []struct { + // Device is the device argument value. + Device nvml.Device + // GpuInstanceProfileInfo is the gpuInstanceProfileInfo argument value. + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + // DeviceGetGpuMaxPcieLinkGeneration holds details about calls to the DeviceGetGpuMaxPcieLinkGeneration method. + DeviceGetGpuMaxPcieLinkGeneration []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGpuOperationMode holds details about calls to the DeviceGetGpuOperationMode method. + DeviceGetGpuOperationMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGraphicsRunningProcesses holds details about calls to the DeviceGetGraphicsRunningProcesses method. + DeviceGetGraphicsRunningProcesses []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGridLicensableFeatures holds details about calls to the DeviceGetGridLicensableFeatures method. + DeviceGetGridLicensableFeatures []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGspFirmwareMode holds details about calls to the DeviceGetGspFirmwareMode method. + DeviceGetGspFirmwareMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetGspFirmwareVersion holds details about calls to the DeviceGetGspFirmwareVersion method. + DeviceGetGspFirmwareVersion []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetHandleByIndex holds details about calls to the DeviceGetHandleByIndex method. + DeviceGetHandleByIndex []struct { + // N is the n argument value. + N int + } + // DeviceGetHandleByPciBusId holds details about calls to the DeviceGetHandleByPciBusId method. + DeviceGetHandleByPciBusId []struct { + // S is the s argument value. + S string + } + // DeviceGetHandleBySerial holds details about calls to the DeviceGetHandleBySerial method. + DeviceGetHandleBySerial []struct { + // S is the s argument value. + S string + } + // DeviceGetHandleByUUID holds details about calls to the DeviceGetHandleByUUID method. + DeviceGetHandleByUUID []struct { + // S is the s argument value. + S string + } + // DeviceGetHandleByUUIDV holds details about calls to the DeviceGetHandleByUUIDV method. + DeviceGetHandleByUUIDV []struct { + // UUID is the uUID argument value. + UUID *nvml.UUID + } + // DeviceGetHostVgpuMode holds details about calls to the DeviceGetHostVgpuMode method. + DeviceGetHostVgpuMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetIndex holds details about calls to the DeviceGetIndex method. + DeviceGetIndex []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetInforomConfigurationChecksum holds details about calls to the DeviceGetInforomConfigurationChecksum method. + DeviceGetInforomConfigurationChecksum []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetInforomImageVersion holds details about calls to the DeviceGetInforomImageVersion method. + DeviceGetInforomImageVersion []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetInforomVersion holds details about calls to the DeviceGetInforomVersion method. + DeviceGetInforomVersion []struct { + // Device is the device argument value. + Device nvml.Device + // InforomObject is the inforomObject argument value. + InforomObject nvml.InforomObject + } + // DeviceGetIrqNum holds details about calls to the DeviceGetIrqNum method. + DeviceGetIrqNum []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetJpgUtilization holds details about calls to the DeviceGetJpgUtilization method. + DeviceGetJpgUtilization []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetLastBBXFlushTime holds details about calls to the DeviceGetLastBBXFlushTime method. + DeviceGetLastBBXFlushTime []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMPSComputeRunningProcesses holds details about calls to the DeviceGetMPSComputeRunningProcesses method. + DeviceGetMPSComputeRunningProcesses []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMarginTemperature holds details about calls to the DeviceGetMarginTemperature method. + DeviceGetMarginTemperature []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMaxClockInfo holds details about calls to the DeviceGetMaxClockInfo method. + DeviceGetMaxClockInfo []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // DeviceGetMaxCustomerBoostClock holds details about calls to the DeviceGetMaxCustomerBoostClock method. + DeviceGetMaxCustomerBoostClock []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + } + // DeviceGetMaxMigDeviceCount holds details about calls to the DeviceGetMaxMigDeviceCount method. + DeviceGetMaxMigDeviceCount []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMaxPcieLinkGeneration holds details about calls to the DeviceGetMaxPcieLinkGeneration method. + DeviceGetMaxPcieLinkGeneration []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMaxPcieLinkWidth holds details about calls to the DeviceGetMaxPcieLinkWidth method. + DeviceGetMaxPcieLinkWidth []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMemClkMinMaxVfOffset holds details about calls to the DeviceGetMemClkMinMaxVfOffset method. + DeviceGetMemClkMinMaxVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMemClkVfOffset holds details about calls to the DeviceGetMemClkVfOffset method. + DeviceGetMemClkVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMemoryAffinity holds details about calls to the DeviceGetMemoryAffinity method. + DeviceGetMemoryAffinity []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // AffinityScope is the affinityScope argument value. + AffinityScope nvml.AffinityScope + } + // DeviceGetMemoryBusWidth holds details about calls to the DeviceGetMemoryBusWidth method. + DeviceGetMemoryBusWidth []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMemoryErrorCounter holds details about calls to the DeviceGetMemoryErrorCounter method. + DeviceGetMemoryErrorCounter []struct { + // Device is the device argument value. + Device nvml.Device + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + // MemoryLocation is the memoryLocation argument value. + MemoryLocation nvml.MemoryLocation + } + // DeviceGetMemoryInfo holds details about calls to the DeviceGetMemoryInfo method. + DeviceGetMemoryInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMemoryInfo_v2 holds details about calls to the DeviceGetMemoryInfo_v2 method. + DeviceGetMemoryInfo_v2 []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMigDeviceHandleByIndex holds details about calls to the DeviceGetMigDeviceHandleByIndex method. + DeviceGetMigDeviceHandleByIndex []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetMigMode holds details about calls to the DeviceGetMigMode method. + DeviceGetMigMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMinMaxClockOfPState holds details about calls to the DeviceGetMinMaxClockOfPState method. + DeviceGetMinMaxClockOfPState []struct { + // Device is the device argument value. + Device nvml.Device + // ClockType is the clockType argument value. + ClockType nvml.ClockType + // Pstates is the pstates argument value. + Pstates nvml.Pstates + } + // DeviceGetMinMaxFanSpeed holds details about calls to the DeviceGetMinMaxFanSpeed method. + DeviceGetMinMaxFanSpeed []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMinorNumber holds details about calls to the DeviceGetMinorNumber method. + DeviceGetMinorNumber []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetModuleId holds details about calls to the DeviceGetModuleId method. + DeviceGetModuleId []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetMultiGpuBoard holds details about calls to the DeviceGetMultiGpuBoard method. + DeviceGetMultiGpuBoard []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetName holds details about calls to the DeviceGetName method. + DeviceGetName []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNumFans holds details about calls to the DeviceGetNumFans method. + DeviceGetNumFans []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNumGpuCores holds details about calls to the DeviceGetNumGpuCores method. + DeviceGetNumGpuCores []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNumaNodeId holds details about calls to the DeviceGetNumaNodeId method. + DeviceGetNumaNodeId []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNvLinkCapability holds details about calls to the DeviceGetNvLinkCapability method. + DeviceGetNvLinkCapability []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // NvLinkCapability is the nvLinkCapability argument value. + NvLinkCapability nvml.NvLinkCapability + } + // DeviceGetNvLinkErrorCounter holds details about calls to the DeviceGetNvLinkErrorCounter method. + DeviceGetNvLinkErrorCounter []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // NvLinkErrorCounter is the nvLinkErrorCounter argument value. + NvLinkErrorCounter nvml.NvLinkErrorCounter + } + // DeviceGetNvLinkInfo holds details about calls to the DeviceGetNvLinkInfo method. + DeviceGetNvLinkInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNvLinkRemoteDeviceType holds details about calls to the DeviceGetNvLinkRemoteDeviceType method. + DeviceGetNvLinkRemoteDeviceType []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetNvLinkRemotePciInfo holds details about calls to the DeviceGetNvLinkRemotePciInfo method. + DeviceGetNvLinkRemotePciInfo []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetNvLinkState holds details about calls to the DeviceGetNvLinkState method. + DeviceGetNvLinkState []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetNvLinkUtilizationControl holds details about calls to the DeviceGetNvLinkUtilizationControl method. + DeviceGetNvLinkUtilizationControl []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // DeviceGetNvLinkUtilizationCounter holds details about calls to the DeviceGetNvLinkUtilizationCounter method. + DeviceGetNvLinkUtilizationCounter []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // DeviceGetNvLinkVersion holds details about calls to the DeviceGetNvLinkVersion method. + DeviceGetNvLinkVersion []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetNvlinkBwMode holds details about calls to the DeviceGetNvlinkBwMode method. + DeviceGetNvlinkBwMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetNvlinkSupportedBwModes holds details about calls to the DeviceGetNvlinkSupportedBwModes method. + DeviceGetNvlinkSupportedBwModes []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetOfaUtilization holds details about calls to the DeviceGetOfaUtilization method. + DeviceGetOfaUtilization []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetP2PStatus holds details about calls to the DeviceGetP2PStatus method. + DeviceGetP2PStatus []struct { + // Device1 is the device1 argument value. + Device1 nvml.Device + // Device2 is the device2 argument value. + Device2 nvml.Device + // GpuP2PCapsIndex is the gpuP2PCapsIndex argument value. + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + } + // DeviceGetPciInfo holds details about calls to the DeviceGetPciInfo method. + DeviceGetPciInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPciInfoExt holds details about calls to the DeviceGetPciInfoExt method. + DeviceGetPciInfoExt []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPcieLinkMaxSpeed holds details about calls to the DeviceGetPcieLinkMaxSpeed method. + DeviceGetPcieLinkMaxSpeed []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPcieReplayCounter holds details about calls to the DeviceGetPcieReplayCounter method. + DeviceGetPcieReplayCounter []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPcieSpeed holds details about calls to the DeviceGetPcieSpeed method. + DeviceGetPcieSpeed []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPcieThroughput holds details about calls to the DeviceGetPcieThroughput method. + DeviceGetPcieThroughput []struct { + // Device is the device argument value. + Device nvml.Device + // PcieUtilCounter is the pcieUtilCounter argument value. + PcieUtilCounter nvml.PcieUtilCounter + } + // DeviceGetPdi holds details about calls to the DeviceGetPdi method. + DeviceGetPdi []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPerformanceModes holds details about calls to the DeviceGetPerformanceModes method. + DeviceGetPerformanceModes []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPerformanceState holds details about calls to the DeviceGetPerformanceState method. + DeviceGetPerformanceState []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPersistenceMode holds details about calls to the DeviceGetPersistenceMode method. + DeviceGetPersistenceMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPgpuMetadataString holds details about calls to the DeviceGetPgpuMetadataString method. + DeviceGetPgpuMetadataString []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPlatformInfo holds details about calls to the DeviceGetPlatformInfo method. + DeviceGetPlatformInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerManagementDefaultLimit holds details about calls to the DeviceGetPowerManagementDefaultLimit method. + DeviceGetPowerManagementDefaultLimit []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerManagementLimit holds details about calls to the DeviceGetPowerManagementLimit method. + DeviceGetPowerManagementLimit []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerManagementLimitConstraints holds details about calls to the DeviceGetPowerManagementLimitConstraints method. + DeviceGetPowerManagementLimitConstraints []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerManagementMode holds details about calls to the DeviceGetPowerManagementMode method. + DeviceGetPowerManagementMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerMizerMode_v1 holds details about calls to the DeviceGetPowerMizerMode_v1 method. + DeviceGetPowerMizerMode_v1 []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerSource holds details about calls to the DeviceGetPowerSource method. + DeviceGetPowerSource []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerState holds details about calls to the DeviceGetPowerState method. + DeviceGetPowerState []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetPowerUsage holds details about calls to the DeviceGetPowerUsage method. + DeviceGetPowerUsage []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetProcessUtilization holds details about calls to the DeviceGetProcessUtilization method. + DeviceGetProcessUtilization []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint64 + } + // DeviceGetProcessesUtilizationInfo holds details about calls to the DeviceGetProcessesUtilizationInfo method. + DeviceGetProcessesUtilizationInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetRemappedRows holds details about calls to the DeviceGetRemappedRows method. + DeviceGetRemappedRows []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetRepairStatus holds details about calls to the DeviceGetRepairStatus method. + DeviceGetRepairStatus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetRetiredPages holds details about calls to the DeviceGetRetiredPages method. + DeviceGetRetiredPages []struct { + // Device is the device argument value. + Device nvml.Device + // PageRetirementCause is the pageRetirementCause argument value. + PageRetirementCause nvml.PageRetirementCause + } + // DeviceGetRetiredPagesPendingStatus holds details about calls to the DeviceGetRetiredPagesPendingStatus method. + DeviceGetRetiredPagesPendingStatus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetRetiredPages_v2 holds details about calls to the DeviceGetRetiredPages_v2 method. + DeviceGetRetiredPages_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // PageRetirementCause is the pageRetirementCause argument value. + PageRetirementCause nvml.PageRetirementCause + } + // DeviceGetRowRemapperHistogram holds details about calls to the DeviceGetRowRemapperHistogram method. + DeviceGetRowRemapperHistogram []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetRunningProcessDetailList holds details about calls to the DeviceGetRunningProcessDetailList method. + DeviceGetRunningProcessDetailList []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSamples holds details about calls to the DeviceGetSamples method. + DeviceGetSamples []struct { + // Device is the device argument value. + Device nvml.Device + // SamplingType is the samplingType argument value. + SamplingType nvml.SamplingType + // V is the v argument value. + V uint64 + } + // DeviceGetSerial holds details about calls to the DeviceGetSerial method. + DeviceGetSerial []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSramEccErrorStatus holds details about calls to the DeviceGetSramEccErrorStatus method. + DeviceGetSramEccErrorStatus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSramUniqueUncorrectedEccErrorCounts holds details about calls to the DeviceGetSramUniqueUncorrectedEccErrorCounts method. + DeviceGetSramUniqueUncorrectedEccErrorCounts []struct { + // Device is the device argument value. + Device nvml.Device + // EccSramUniqueUncorrectedErrorCounts is the eccSramUniqueUncorrectedErrorCounts argument value. + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + } + // DeviceGetSupportedClocksEventReasons holds details about calls to the DeviceGetSupportedClocksEventReasons method. + DeviceGetSupportedClocksEventReasons []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSupportedClocksThrottleReasons holds details about calls to the DeviceGetSupportedClocksThrottleReasons method. + DeviceGetSupportedClocksThrottleReasons []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSupportedEventTypes holds details about calls to the DeviceGetSupportedEventTypes method. + DeviceGetSupportedEventTypes []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSupportedGraphicsClocks holds details about calls to the DeviceGetSupportedGraphicsClocks method. + DeviceGetSupportedGraphicsClocks []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetSupportedMemoryClocks holds details about calls to the DeviceGetSupportedMemoryClocks method. + DeviceGetSupportedMemoryClocks []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSupportedPerformanceStates holds details about calls to the DeviceGetSupportedPerformanceStates method. + DeviceGetSupportedPerformanceStates []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetSupportedVgpus holds details about calls to the DeviceGetSupportedVgpus method. + DeviceGetSupportedVgpus []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetTargetFanSpeed holds details about calls to the DeviceGetTargetFanSpeed method. + DeviceGetTargetFanSpeed []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceGetTemperature holds details about calls to the DeviceGetTemperature method. + DeviceGetTemperature []struct { + // Device is the device argument value. + Device nvml.Device + // TemperatureSensors is the temperatureSensors argument value. + TemperatureSensors nvml.TemperatureSensors + } + // DeviceGetTemperatureThreshold holds details about calls to the DeviceGetTemperatureThreshold method. + DeviceGetTemperatureThreshold []struct { + // Device is the device argument value. + Device nvml.Device + // TemperatureThresholds is the temperatureThresholds argument value. + TemperatureThresholds nvml.TemperatureThresholds + } + // DeviceGetTemperatureV holds details about calls to the DeviceGetTemperatureV method. + DeviceGetTemperatureV []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetThermalSettings holds details about calls to the DeviceGetThermalSettings method. + DeviceGetThermalSettings []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint32 + } + // DeviceGetTopologyCommonAncestor holds details about calls to the DeviceGetTopologyCommonAncestor method. + DeviceGetTopologyCommonAncestor []struct { + // Device1 is the device1 argument value. + Device1 nvml.Device + // Device2 is the device2 argument value. + Device2 nvml.Device + } + // DeviceGetTopologyNearestGpus holds details about calls to the DeviceGetTopologyNearestGpus method. + DeviceGetTopologyNearestGpus []struct { + // Device is the device argument value. + Device nvml.Device + // GpuTopologyLevel is the gpuTopologyLevel argument value. + GpuTopologyLevel nvml.GpuTopologyLevel + } + // DeviceGetTotalEccErrors holds details about calls to the DeviceGetTotalEccErrors method. + DeviceGetTotalEccErrors []struct { + // Device is the device argument value. + Device nvml.Device + // MemoryErrorType is the memoryErrorType argument value. + MemoryErrorType nvml.MemoryErrorType + // EccCounterType is the eccCounterType argument value. + EccCounterType nvml.EccCounterType + } + // DeviceGetTotalEnergyConsumption holds details about calls to the DeviceGetTotalEnergyConsumption method. + DeviceGetTotalEnergyConsumption []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetUUID holds details about calls to the DeviceGetUUID method. + DeviceGetUUID []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetUtilizationRates holds details about calls to the DeviceGetUtilizationRates method. + DeviceGetUtilizationRates []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVbiosVersion holds details about calls to the DeviceGetVbiosVersion method. + DeviceGetVbiosVersion []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuCapabilities holds details about calls to the DeviceGetVgpuCapabilities method. + DeviceGetVgpuCapabilities []struct { + // Device is the device argument value. + Device nvml.Device + // DeviceVgpuCapability is the deviceVgpuCapability argument value. + DeviceVgpuCapability nvml.DeviceVgpuCapability + } + // DeviceGetVgpuHeterogeneousMode holds details about calls to the DeviceGetVgpuHeterogeneousMode method. + DeviceGetVgpuHeterogeneousMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuInstancesUtilizationInfo holds details about calls to the DeviceGetVgpuInstancesUtilizationInfo method. + DeviceGetVgpuInstancesUtilizationInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuMetadata holds details about calls to the DeviceGetVgpuMetadata method. + DeviceGetVgpuMetadata []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuProcessUtilization holds details about calls to the DeviceGetVgpuProcessUtilization method. + DeviceGetVgpuProcessUtilization []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint64 + } + // DeviceGetVgpuProcessesUtilizationInfo holds details about calls to the DeviceGetVgpuProcessesUtilizationInfo method. + DeviceGetVgpuProcessesUtilizationInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuSchedulerCapabilities holds details about calls to the DeviceGetVgpuSchedulerCapabilities method. + DeviceGetVgpuSchedulerCapabilities []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuSchedulerLog holds details about calls to the DeviceGetVgpuSchedulerLog method. + DeviceGetVgpuSchedulerLog []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuSchedulerState holds details about calls to the DeviceGetVgpuSchedulerState method. + DeviceGetVgpuSchedulerState []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceGetVgpuTypeCreatablePlacements holds details about calls to the DeviceGetVgpuTypeCreatablePlacements method. + DeviceGetVgpuTypeCreatablePlacements []struct { + // Device is the device argument value. + Device nvml.Device + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // DeviceGetVgpuTypeSupportedPlacements holds details about calls to the DeviceGetVgpuTypeSupportedPlacements method. + DeviceGetVgpuTypeSupportedPlacements []struct { + // Device is the device argument value. + Device nvml.Device + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // DeviceGetVgpuUtilization holds details about calls to the DeviceGetVgpuUtilization method. + DeviceGetVgpuUtilization []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint64 + } + // DeviceGetViolationStatus holds details about calls to the DeviceGetViolationStatus method. + DeviceGetViolationStatus []struct { + // Device is the device argument value. + Device nvml.Device + // PerfPolicyType is the perfPolicyType argument value. + PerfPolicyType nvml.PerfPolicyType + } + // DeviceGetVirtualizationMode holds details about calls to the DeviceGetVirtualizationMode method. + DeviceGetVirtualizationMode []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceIsMigDeviceHandle holds details about calls to the DeviceIsMigDeviceHandle method. + DeviceIsMigDeviceHandle []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceModifyDrainState holds details about calls to the DeviceModifyDrainState method. + DeviceModifyDrainState []struct { + // PciInfo is the pciInfo argument value. + PciInfo *nvml.PciInfo + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceOnSameBoard holds details about calls to the DeviceOnSameBoard method. + DeviceOnSameBoard []struct { + // Device1 is the device1 argument value. + Device1 nvml.Device + // Device2 is the device2 argument value. + Device2 nvml.Device + } + // DevicePowerSmoothingActivatePresetProfile holds details about calls to the DevicePowerSmoothingActivatePresetProfile method. + DevicePowerSmoothingActivatePresetProfile []struct { + // Device is the device argument value. + Device nvml.Device + // PowerSmoothingProfile is the powerSmoothingProfile argument value. + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + // DevicePowerSmoothingSetState holds details about calls to the DevicePowerSmoothingSetState method. + DevicePowerSmoothingSetState []struct { + // Device is the device argument value. + Device nvml.Device + // PowerSmoothingState is the powerSmoothingState argument value. + PowerSmoothingState *nvml.PowerSmoothingState + } + // DevicePowerSmoothingUpdatePresetProfileParam holds details about calls to the DevicePowerSmoothingUpdatePresetProfileParam method. + DevicePowerSmoothingUpdatePresetProfileParam []struct { + // Device is the device argument value. + Device nvml.Device + // PowerSmoothingProfile is the powerSmoothingProfile argument value. + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + // DeviceQueryDrainState holds details about calls to the DeviceQueryDrainState method. + DeviceQueryDrainState []struct { + // PciInfo is the pciInfo argument value. + PciInfo *nvml.PciInfo + } + // DeviceReadWritePRM_v1 holds details about calls to the DeviceReadWritePRM_v1 method. + DeviceReadWritePRM_v1 []struct { + // Device is the device argument value. + Device nvml.Device + // PRMTLV_v1 is the pRMTLV_v1 argument value. + PRMTLV_v1 *nvml.PRMTLV_v1 + } + // DeviceRegisterEvents holds details about calls to the DeviceRegisterEvents method. + DeviceRegisterEvents []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint64 + // EventSet is the eventSet argument value. + EventSet nvml.EventSet + } + // DeviceRemoveGpu holds details about calls to the DeviceRemoveGpu method. + DeviceRemoveGpu []struct { + // PciInfo is the pciInfo argument value. + PciInfo *nvml.PciInfo + } + // DeviceRemoveGpu_v2 holds details about calls to the DeviceRemoveGpu_v2 method. + DeviceRemoveGpu_v2 []struct { + // PciInfo is the pciInfo argument value. + PciInfo *nvml.PciInfo + // DetachGpuState is the detachGpuState argument value. + DetachGpuState nvml.DetachGpuState + // PcieLinkState is the pcieLinkState argument value. + PcieLinkState nvml.PcieLinkState + } + // DeviceResetApplicationsClocks holds details about calls to the DeviceResetApplicationsClocks method. + DeviceResetApplicationsClocks []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceResetGpuLockedClocks holds details about calls to the DeviceResetGpuLockedClocks method. + DeviceResetGpuLockedClocks []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceResetMemoryLockedClocks holds details about calls to the DeviceResetMemoryLockedClocks method. + DeviceResetMemoryLockedClocks []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceResetNvLinkErrorCounters holds details about calls to the DeviceResetNvLinkErrorCounters method. + DeviceResetNvLinkErrorCounters []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceResetNvLinkUtilizationCounter holds details about calls to the DeviceResetNvLinkUtilizationCounter method. + DeviceResetNvLinkUtilizationCounter []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // DeviceSetAPIRestriction holds details about calls to the DeviceSetAPIRestriction method. + DeviceSetAPIRestriction []struct { + // Device is the device argument value. + Device nvml.Device + // RestrictedAPI is the restrictedAPI argument value. + RestrictedAPI nvml.RestrictedAPI + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetAccountingMode holds details about calls to the DeviceSetAccountingMode method. + DeviceSetAccountingMode []struct { + // Device is the device argument value. + Device nvml.Device + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetApplicationsClocks holds details about calls to the DeviceSetApplicationsClocks method. + DeviceSetApplicationsClocks []struct { + // Device is the device argument value. + Device nvml.Device + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // DeviceSetAutoBoostedClocksEnabled holds details about calls to the DeviceSetAutoBoostedClocksEnabled method. + DeviceSetAutoBoostedClocksEnabled []struct { + // Device is the device argument value. + Device nvml.Device + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetClockOffsets holds details about calls to the DeviceSetClockOffsets method. + DeviceSetClockOffsets []struct { + // Device is the device argument value. + Device nvml.Device + // ClockOffset is the clockOffset argument value. + ClockOffset nvml.ClockOffset + } + // DeviceSetComputeMode holds details about calls to the DeviceSetComputeMode method. + DeviceSetComputeMode []struct { + // Device is the device argument value. + Device nvml.Device + // ComputeMode is the computeMode argument value. + ComputeMode nvml.ComputeMode + } + // DeviceSetConfComputeUnprotectedMemSize holds details about calls to the DeviceSetConfComputeUnprotectedMemSize method. + DeviceSetConfComputeUnprotectedMemSize []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint64 + } + // DeviceSetCpuAffinity holds details about calls to the DeviceSetCpuAffinity method. + DeviceSetCpuAffinity []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceSetDefaultAutoBoostedClocksEnabled holds details about calls to the DeviceSetDefaultAutoBoostedClocksEnabled method. + DeviceSetDefaultAutoBoostedClocksEnabled []struct { + // Device is the device argument value. + Device nvml.Device + // EnableState is the enableState argument value. + EnableState nvml.EnableState + // V is the v argument value. + V uint32 + } + // DeviceSetDefaultFanSpeed_v2 holds details about calls to the DeviceSetDefaultFanSpeed_v2 method. + DeviceSetDefaultFanSpeed_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceSetDramEncryptionMode holds details about calls to the DeviceSetDramEncryptionMode method. + DeviceSetDramEncryptionMode []struct { + // Device is the device argument value. + Device nvml.Device + // DramEncryptionInfo is the dramEncryptionInfo argument value. + DramEncryptionInfo *nvml.DramEncryptionInfo + } + // DeviceSetDriverModel holds details about calls to the DeviceSetDriverModel method. + DeviceSetDriverModel []struct { + // Device is the device argument value. + Device nvml.Device + // DriverModel is the driverModel argument value. + DriverModel nvml.DriverModel + // V is the v argument value. + V uint32 + } + // DeviceSetEccMode holds details about calls to the DeviceSetEccMode method. + DeviceSetEccMode []struct { + // Device is the device argument value. + Device nvml.Device + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetFanControlPolicy holds details about calls to the DeviceSetFanControlPolicy method. + DeviceSetFanControlPolicy []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // FanControlPolicy is the fanControlPolicy argument value. + FanControlPolicy nvml.FanControlPolicy + } + // DeviceSetFanSpeed_v2 holds details about calls to the DeviceSetFanSpeed_v2 method. + DeviceSetFanSpeed_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // DeviceSetGpcClkVfOffset holds details about calls to the DeviceSetGpcClkVfOffset method. + DeviceSetGpcClkVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceSetGpuLockedClocks holds details about calls to the DeviceSetGpuLockedClocks method. + DeviceSetGpuLockedClocks []struct { + // Device is the device argument value. + Device nvml.Device + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // DeviceSetGpuOperationMode holds details about calls to the DeviceSetGpuOperationMode method. + DeviceSetGpuOperationMode []struct { + // Device is the device argument value. + Device nvml.Device + // GpuOperationMode is the gpuOperationMode argument value. + GpuOperationMode nvml.GpuOperationMode + } + // DeviceSetMemClkVfOffset holds details about calls to the DeviceSetMemClkVfOffset method. + DeviceSetMemClkVfOffset []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceSetMemoryLockedClocks holds details about calls to the DeviceSetMemoryLockedClocks method. + DeviceSetMemoryLockedClocks []struct { + // Device is the device argument value. + Device nvml.Device + // V1 is the v1 argument value. + V1 uint32 + // V2 is the v2 argument value. + V2 uint32 + } + // DeviceSetMigMode holds details about calls to the DeviceSetMigMode method. + DeviceSetMigMode []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + } + // DeviceSetNvLinkDeviceLowPowerThreshold holds details about calls to the DeviceSetNvLinkDeviceLowPowerThreshold method. + DeviceSetNvLinkDeviceLowPowerThreshold []struct { + // Device is the device argument value. + Device nvml.Device + // NvLinkPowerThres is the nvLinkPowerThres argument value. + NvLinkPowerThres *nvml.NvLinkPowerThres + } + // DeviceSetNvLinkUtilizationControl holds details about calls to the DeviceSetNvLinkUtilizationControl method. + DeviceSetNvLinkUtilizationControl []struct { + // Device is the device argument value. + Device nvml.Device + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + // NvLinkUtilizationControl is the nvLinkUtilizationControl argument value. + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + // B is the b argument value. + B bool + } + // DeviceSetNvlinkBwMode holds details about calls to the DeviceSetNvlinkBwMode method. + DeviceSetNvlinkBwMode []struct { + // Device is the device argument value. + Device nvml.Device + // NvlinkSetBwMode is the nvlinkSetBwMode argument value. + NvlinkSetBwMode *nvml.NvlinkSetBwMode + } + // DeviceSetPersistenceMode holds details about calls to the DeviceSetPersistenceMode method. + DeviceSetPersistenceMode []struct { + // Device is the device argument value. + Device nvml.Device + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetPowerManagementLimit holds details about calls to the DeviceSetPowerManagementLimit method. + DeviceSetPowerManagementLimit []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint32 + } + // DeviceSetPowerManagementLimit_v2 holds details about calls to the DeviceSetPowerManagementLimit_v2 method. + DeviceSetPowerManagementLimit_v2 []struct { + // Device is the device argument value. + Device nvml.Device + // PowerValue_v2 is the powerValue_v2 argument value. + PowerValue_v2 *nvml.PowerValue_v2 + } + // DeviceSetTemperatureThreshold holds details about calls to the DeviceSetTemperatureThreshold method. + DeviceSetTemperatureThreshold []struct { + // Device is the device argument value. + Device nvml.Device + // TemperatureThresholds is the temperatureThresholds argument value. + TemperatureThresholds nvml.TemperatureThresholds + // N is the n argument value. + N int + } + // DeviceSetVgpuCapabilities holds details about calls to the DeviceSetVgpuCapabilities method. + DeviceSetVgpuCapabilities []struct { + // Device is the device argument value. + Device nvml.Device + // DeviceVgpuCapability is the deviceVgpuCapability argument value. + DeviceVgpuCapability nvml.DeviceVgpuCapability + // EnableState is the enableState argument value. + EnableState nvml.EnableState + } + // DeviceSetVgpuHeterogeneousMode holds details about calls to the DeviceSetVgpuHeterogeneousMode method. + DeviceSetVgpuHeterogeneousMode []struct { + // Device is the device argument value. + Device nvml.Device + // VgpuHeterogeneousMode is the vgpuHeterogeneousMode argument value. + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + } + // DeviceSetVgpuSchedulerState holds details about calls to the DeviceSetVgpuSchedulerState method. + DeviceSetVgpuSchedulerState []struct { + // Device is the device argument value. + Device nvml.Device + // VgpuSchedulerSetState is the vgpuSchedulerSetState argument value. + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + } + // DeviceSetVirtualizationMode holds details about calls to the DeviceSetVirtualizationMode method. + DeviceSetVirtualizationMode []struct { + // Device is the device argument value. + Device nvml.Device + // GpuVirtualizationMode is the gpuVirtualizationMode argument value. + GpuVirtualizationMode nvml.GpuVirtualizationMode + } + // DeviceValidateInforom holds details about calls to the DeviceValidateInforom method. + DeviceValidateInforom []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceWorkloadPowerProfileClearRequestedProfiles holds details about calls to the DeviceWorkloadPowerProfileClearRequestedProfiles method. + DeviceWorkloadPowerProfileClearRequestedProfiles []struct { + // Device is the device argument value. + Device nvml.Device + // WorkloadPowerProfileRequestedProfiles is the workloadPowerProfileRequestedProfiles argument value. + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + // DeviceWorkloadPowerProfileGetCurrentProfiles holds details about calls to the DeviceWorkloadPowerProfileGetCurrentProfiles method. + DeviceWorkloadPowerProfileGetCurrentProfiles []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceWorkloadPowerProfileGetProfilesInfo holds details about calls to the DeviceWorkloadPowerProfileGetProfilesInfo method. + DeviceWorkloadPowerProfileGetProfilesInfo []struct { + // Device is the device argument value. + Device nvml.Device + } + // DeviceWorkloadPowerProfileSetRequestedProfiles holds details about calls to the DeviceWorkloadPowerProfileSetRequestedProfiles method. + DeviceWorkloadPowerProfileSetRequestedProfiles []struct { + // Device is the device argument value. + Device nvml.Device + // WorkloadPowerProfileRequestedProfiles is the workloadPowerProfileRequestedProfiles argument value. + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + // ErrorString holds details about calls to the ErrorString method. + ErrorString []struct { + // ReturnMoqParam is the returnMoqParam argument value. + ReturnMoqParam nvml.Return + } + // EventSetCreate holds details about calls to the EventSetCreate method. + EventSetCreate []struct { + } + // EventSetFree holds details about calls to the EventSetFree method. + EventSetFree []struct { + // EventSet is the eventSet argument value. + EventSet nvml.EventSet + } + // EventSetWait holds details about calls to the EventSetWait method. + EventSetWait []struct { + // EventSet is the eventSet argument value. + EventSet nvml.EventSet + // V is the v argument value. + V uint32 + } + // Extensions holds details about calls to the Extensions method. + Extensions []struct { + } + // GetExcludedDeviceCount holds details about calls to the GetExcludedDeviceCount method. + GetExcludedDeviceCount []struct { + } + // GetExcludedDeviceInfoByIndex holds details about calls to the GetExcludedDeviceInfoByIndex method. + GetExcludedDeviceInfoByIndex []struct { + // N is the n argument value. + N int + } + // GetVgpuCompatibility holds details about calls to the GetVgpuCompatibility method. + GetVgpuCompatibility []struct { + // VgpuMetadata is the vgpuMetadata argument value. + VgpuMetadata *nvml.VgpuMetadata + // VgpuPgpuMetadata is the vgpuPgpuMetadata argument value. + VgpuPgpuMetadata *nvml.VgpuPgpuMetadata + } + // GetVgpuDriverCapabilities holds details about calls to the GetVgpuDriverCapabilities method. + GetVgpuDriverCapabilities []struct { + // VgpuDriverCapability is the vgpuDriverCapability argument value. + VgpuDriverCapability nvml.VgpuDriverCapability + } + // GetVgpuVersion holds details about calls to the GetVgpuVersion method. + GetVgpuVersion []struct { + } + // GpmMetricsGet holds details about calls to the GpmMetricsGet method. + GpmMetricsGet []struct { + // GpmMetricsGetType is the gpmMetricsGetType argument value. + GpmMetricsGetType *nvml.GpmMetricsGetType + } + // GpmMetricsGetV holds details about calls to the GpmMetricsGetV method. + GpmMetricsGetV []struct { + // GpmMetricsGetType is the gpmMetricsGetType argument value. + GpmMetricsGetType *nvml.GpmMetricsGetType + } + // GpmMigSampleGet holds details about calls to the GpmMigSampleGet method. + GpmMigSampleGet []struct { + // Device is the device argument value. + Device nvml.Device + // N is the n argument value. + N int + // GpmSample is the gpmSample argument value. + GpmSample nvml.GpmSample + } + // GpmQueryDeviceSupport holds details about calls to the GpmQueryDeviceSupport method. + GpmQueryDeviceSupport []struct { + // Device is the device argument value. + Device nvml.Device + } + // GpmQueryDeviceSupportV holds details about calls to the GpmQueryDeviceSupportV method. + GpmQueryDeviceSupportV []struct { + // Device is the device argument value. + Device nvml.Device + } + // GpmQueryIfStreamingEnabled holds details about calls to the GpmQueryIfStreamingEnabled method. + GpmQueryIfStreamingEnabled []struct { + // Device is the device argument value. + Device nvml.Device + } + // GpmSampleAlloc holds details about calls to the GpmSampleAlloc method. + GpmSampleAlloc []struct { + } + // GpmSampleFree holds details about calls to the GpmSampleFree method. + GpmSampleFree []struct { + // GpmSample is the gpmSample argument value. + GpmSample nvml.GpmSample + } + // GpmSampleGet holds details about calls to the GpmSampleGet method. + GpmSampleGet []struct { + // Device is the device argument value. + Device nvml.Device + // GpmSample is the gpmSample argument value. + GpmSample nvml.GpmSample + } + // GpmSetStreamingEnabled holds details about calls to the GpmSetStreamingEnabled method. + GpmSetStreamingEnabled []struct { + // Device is the device argument value. + Device nvml.Device + // V is the v argument value. + V uint32 + } + // GpuInstanceCreateComputeInstance holds details about calls to the GpuInstanceCreateComputeInstance method. + GpuInstanceCreateComputeInstance []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GpuInstanceCreateComputeInstanceWithPlacement holds details about calls to the GpuInstanceCreateComputeInstanceWithPlacement method. + GpuInstanceCreateComputeInstanceWithPlacement []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + // ComputeInstancePlacement is the computeInstancePlacement argument value. + ComputeInstancePlacement *nvml.ComputeInstancePlacement + } + // GpuInstanceDestroy holds details about calls to the GpuInstanceDestroy method. + GpuInstanceDestroy []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetActiveVgpus holds details about calls to the GpuInstanceGetActiveVgpus method. + GpuInstanceGetActiveVgpus []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetComputeInstanceById holds details about calls to the GpuInstanceGetComputeInstanceById method. + GpuInstanceGetComputeInstanceById []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // N is the n argument value. + N int + } + // GpuInstanceGetComputeInstancePossiblePlacements holds details about calls to the GpuInstanceGetComputeInstancePossiblePlacements method. + GpuInstanceGetComputeInstancePossiblePlacements []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GpuInstanceGetComputeInstanceProfileInfo holds details about calls to the GpuInstanceGetComputeInstanceProfileInfo method. + GpuInstanceGetComputeInstanceProfileInfo []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GpuInstanceGetComputeInstanceProfileInfoV holds details about calls to the GpuInstanceGetComputeInstanceProfileInfoV method. + GpuInstanceGetComputeInstanceProfileInfoV []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // N1 is the n1 argument value. + N1 int + // N2 is the n2 argument value. + N2 int + } + // GpuInstanceGetComputeInstanceRemainingCapacity holds details about calls to the GpuInstanceGetComputeInstanceRemainingCapacity method. + GpuInstanceGetComputeInstanceRemainingCapacity []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GpuInstanceGetComputeInstances holds details about calls to the GpuInstanceGetComputeInstances method. + GpuInstanceGetComputeInstances []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // ComputeInstanceProfileInfo is the computeInstanceProfileInfo argument value. + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + // GpuInstanceGetCreatableVgpus holds details about calls to the GpuInstanceGetCreatableVgpus method. + GpuInstanceGetCreatableVgpus []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetInfo holds details about calls to the GpuInstanceGetInfo method. + GpuInstanceGetInfo []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetVgpuHeterogeneousMode holds details about calls to the GpuInstanceGetVgpuHeterogeneousMode method. + GpuInstanceGetVgpuHeterogeneousMode []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetVgpuSchedulerLog holds details about calls to the GpuInstanceGetVgpuSchedulerLog method. + GpuInstanceGetVgpuSchedulerLog []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetVgpuSchedulerState holds details about calls to the GpuInstanceGetVgpuSchedulerState method. + GpuInstanceGetVgpuSchedulerState []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceGetVgpuTypeCreatablePlacements holds details about calls to the GpuInstanceGetVgpuTypeCreatablePlacements method. + GpuInstanceGetVgpuTypeCreatablePlacements []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + } + // GpuInstanceSetVgpuHeterogeneousMode holds details about calls to the GpuInstanceSetVgpuHeterogeneousMode method. + GpuInstanceSetVgpuHeterogeneousMode []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // VgpuHeterogeneousMode is the vgpuHeterogeneousMode argument value. + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + } + // GpuInstanceSetVgpuSchedulerState holds details about calls to the GpuInstanceSetVgpuSchedulerState method. + GpuInstanceSetVgpuSchedulerState []struct { + // GpuInstance is the gpuInstance argument value. + GpuInstance nvml.GpuInstance + // VgpuSchedulerState is the vgpuSchedulerState argument value. + VgpuSchedulerState *nvml.VgpuSchedulerState + } + // Init holds details about calls to the Init method. + Init []struct { + } + // InitWithFlags holds details about calls to the InitWithFlags method. + InitWithFlags []struct { + // V is the v argument value. + V uint32 + } + // SetVgpuVersion holds details about calls to the SetVgpuVersion method. + SetVgpuVersion []struct { + // VgpuVersion is the vgpuVersion argument value. + VgpuVersion *nvml.VgpuVersion + } + // Shutdown holds details about calls to the Shutdown method. + Shutdown []struct { + } + // SystemEventSetCreate holds details about calls to the SystemEventSetCreate method. + SystemEventSetCreate []struct { + // SystemEventSetCreateRequest is the systemEventSetCreateRequest argument value. + SystemEventSetCreateRequest *nvml.SystemEventSetCreateRequest + } + // SystemEventSetFree holds details about calls to the SystemEventSetFree method. + SystemEventSetFree []struct { + // SystemEventSetFreeRequest is the systemEventSetFreeRequest argument value. + SystemEventSetFreeRequest *nvml.SystemEventSetFreeRequest + } + // SystemEventSetWait holds details about calls to the SystemEventSetWait method. + SystemEventSetWait []struct { + // SystemEventSetWaitRequest is the systemEventSetWaitRequest argument value. + SystemEventSetWaitRequest *nvml.SystemEventSetWaitRequest + } + // SystemGetConfComputeCapabilities holds details about calls to the SystemGetConfComputeCapabilities method. + SystemGetConfComputeCapabilities []struct { + } + // SystemGetConfComputeGpusReadyState holds details about calls to the SystemGetConfComputeGpusReadyState method. + SystemGetConfComputeGpusReadyState []struct { + } + // SystemGetConfComputeKeyRotationThresholdInfo holds details about calls to the SystemGetConfComputeKeyRotationThresholdInfo method. + SystemGetConfComputeKeyRotationThresholdInfo []struct { + } + // SystemGetConfComputeSettings holds details about calls to the SystemGetConfComputeSettings method. + SystemGetConfComputeSettings []struct { + } + // SystemGetConfComputeState holds details about calls to the SystemGetConfComputeState method. + SystemGetConfComputeState []struct { + } + // SystemGetCudaDriverVersion holds details about calls to the SystemGetCudaDriverVersion method. + SystemGetCudaDriverVersion []struct { + } + // SystemGetCudaDriverVersion_v2 holds details about calls to the SystemGetCudaDriverVersion_v2 method. + SystemGetCudaDriverVersion_v2 []struct { + } + // SystemGetDriverBranch holds details about calls to the SystemGetDriverBranch method. + SystemGetDriverBranch []struct { + } + // SystemGetDriverVersion holds details about calls to the SystemGetDriverVersion method. + SystemGetDriverVersion []struct { + } + // SystemGetHicVersion holds details about calls to the SystemGetHicVersion method. + SystemGetHicVersion []struct { + } + // SystemGetNVMLVersion holds details about calls to the SystemGetNVMLVersion method. + SystemGetNVMLVersion []struct { + } + // SystemGetNvlinkBwMode holds details about calls to the SystemGetNvlinkBwMode method. + SystemGetNvlinkBwMode []struct { + } + // SystemGetProcessName holds details about calls to the SystemGetProcessName method. + SystemGetProcessName []struct { + // N is the n argument value. + N int + } + // SystemGetTopologyGpuSet holds details about calls to the SystemGetTopologyGpuSet method. + SystemGetTopologyGpuSet []struct { + // N is the n argument value. + N int + } + // SystemRegisterEvents holds details about calls to the SystemRegisterEvents method. + SystemRegisterEvents []struct { + // SystemRegisterEventRequest is the systemRegisterEventRequest argument value. + SystemRegisterEventRequest *nvml.SystemRegisterEventRequest + } + // SystemSetConfComputeGpusReadyState holds details about calls to the SystemSetConfComputeGpusReadyState method. + SystemSetConfComputeGpusReadyState []struct { + // V is the v argument value. + V uint32 + } + // SystemSetConfComputeKeyRotationThresholdInfo holds details about calls to the SystemSetConfComputeKeyRotationThresholdInfo method. + SystemSetConfComputeKeyRotationThresholdInfo []struct { + // ConfComputeSetKeyRotationThresholdInfo is the confComputeSetKeyRotationThresholdInfo argument value. + ConfComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo + } + // SystemSetNvlinkBwMode holds details about calls to the SystemSetNvlinkBwMode method. + SystemSetNvlinkBwMode []struct { + // V is the v argument value. + V uint32 + } + // UnitGetCount holds details about calls to the UnitGetCount method. + UnitGetCount []struct { + } + // UnitGetDevices holds details about calls to the UnitGetDevices method. + UnitGetDevices []struct { + // Unit is the unit argument value. + Unit nvml.Unit + } + // UnitGetFanSpeedInfo holds details about calls to the UnitGetFanSpeedInfo method. + UnitGetFanSpeedInfo []struct { + // Unit is the unit argument value. + Unit nvml.Unit + } + // UnitGetHandleByIndex holds details about calls to the UnitGetHandleByIndex method. + UnitGetHandleByIndex []struct { + // N is the n argument value. + N int + } + // UnitGetLedState holds details about calls to the UnitGetLedState method. + UnitGetLedState []struct { + // Unit is the unit argument value. + Unit nvml.Unit + } + // UnitGetPsuInfo holds details about calls to the UnitGetPsuInfo method. + UnitGetPsuInfo []struct { + // Unit is the unit argument value. + Unit nvml.Unit + } + // UnitGetTemperature holds details about calls to the UnitGetTemperature method. + UnitGetTemperature []struct { + // Unit is the unit argument value. + Unit nvml.Unit + // N is the n argument value. + N int + } + // UnitGetUnitInfo holds details about calls to the UnitGetUnitInfo method. + UnitGetUnitInfo []struct { + // Unit is the unit argument value. + Unit nvml.Unit + } + // UnitSetLedState holds details about calls to the UnitSetLedState method. + UnitSetLedState []struct { + // Unit is the unit argument value. + Unit nvml.Unit + // LedColor is the ledColor argument value. + LedColor nvml.LedColor + } + // VgpuInstanceClearAccountingPids holds details about calls to the VgpuInstanceClearAccountingPids method. + VgpuInstanceClearAccountingPids []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetAccountingMode holds details about calls to the VgpuInstanceGetAccountingMode method. + VgpuInstanceGetAccountingMode []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetAccountingPids holds details about calls to the VgpuInstanceGetAccountingPids method. + VgpuInstanceGetAccountingPids []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetAccountingStats holds details about calls to the VgpuInstanceGetAccountingStats method. + VgpuInstanceGetAccountingStats []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + // N is the n argument value. + N int + } + // VgpuInstanceGetEccMode holds details about calls to the VgpuInstanceGetEccMode method. + VgpuInstanceGetEccMode []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetEncoderCapacity holds details about calls to the VgpuInstanceGetEncoderCapacity method. + VgpuInstanceGetEncoderCapacity []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetEncoderSessions holds details about calls to the VgpuInstanceGetEncoderSessions method. + VgpuInstanceGetEncoderSessions []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetEncoderStats holds details about calls to the VgpuInstanceGetEncoderStats method. + VgpuInstanceGetEncoderStats []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetFBCSessions holds details about calls to the VgpuInstanceGetFBCSessions method. + VgpuInstanceGetFBCSessions []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetFBCStats holds details about calls to the VgpuInstanceGetFBCStats method. + VgpuInstanceGetFBCStats []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetFbUsage holds details about calls to the VgpuInstanceGetFbUsage method. + VgpuInstanceGetFbUsage []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetFrameRateLimit holds details about calls to the VgpuInstanceGetFrameRateLimit method. + VgpuInstanceGetFrameRateLimit []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetGpuInstanceId holds details about calls to the VgpuInstanceGetGpuInstanceId method. + VgpuInstanceGetGpuInstanceId []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetGpuPciId holds details about calls to the VgpuInstanceGetGpuPciId method. + VgpuInstanceGetGpuPciId []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetLicenseInfo holds details about calls to the VgpuInstanceGetLicenseInfo method. + VgpuInstanceGetLicenseInfo []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetLicenseStatus holds details about calls to the VgpuInstanceGetLicenseStatus method. + VgpuInstanceGetLicenseStatus []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetMdevUUID holds details about calls to the VgpuInstanceGetMdevUUID method. + VgpuInstanceGetMdevUUID []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetMetadata holds details about calls to the VgpuInstanceGetMetadata method. + VgpuInstanceGetMetadata []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetRuntimeStateSize holds details about calls to the VgpuInstanceGetRuntimeStateSize method. + VgpuInstanceGetRuntimeStateSize []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetType holds details about calls to the VgpuInstanceGetType method. + VgpuInstanceGetType []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetUUID holds details about calls to the VgpuInstanceGetUUID method. + VgpuInstanceGetUUID []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetVmDriverVersion holds details about calls to the VgpuInstanceGetVmDriverVersion method. + VgpuInstanceGetVmDriverVersion []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceGetVmID holds details about calls to the VgpuInstanceGetVmID method. + VgpuInstanceGetVmID []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + } + // VgpuInstanceSetEncoderCapacity holds details about calls to the VgpuInstanceSetEncoderCapacity method. + VgpuInstanceSetEncoderCapacity []struct { + // VgpuInstance is the vgpuInstance argument value. + VgpuInstance nvml.VgpuInstance + // N is the n argument value. + N int + } + // VgpuTypeGetBAR1Info holds details about calls to the VgpuTypeGetBAR1Info method. + VgpuTypeGetBAR1Info []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetCapabilities holds details about calls to the VgpuTypeGetCapabilities method. + VgpuTypeGetCapabilities []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + // VgpuCapability is the vgpuCapability argument value. + VgpuCapability nvml.VgpuCapability + } + // VgpuTypeGetClass holds details about calls to the VgpuTypeGetClass method. + VgpuTypeGetClass []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetDeviceID holds details about calls to the VgpuTypeGetDeviceID method. + VgpuTypeGetDeviceID []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetFrameRateLimit holds details about calls to the VgpuTypeGetFrameRateLimit method. + VgpuTypeGetFrameRateLimit []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetFramebufferSize holds details about calls to the VgpuTypeGetFramebufferSize method. + VgpuTypeGetFramebufferSize []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetGpuInstanceProfileId holds details about calls to the VgpuTypeGetGpuInstanceProfileId method. + VgpuTypeGetGpuInstanceProfileId []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetLicense holds details about calls to the VgpuTypeGetLicense method. + VgpuTypeGetLicense []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetMaxInstances holds details about calls to the VgpuTypeGetMaxInstances method. + VgpuTypeGetMaxInstances []struct { + // Device is the device argument value. + Device nvml.Device + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetMaxInstancesPerGpuInstance holds details about calls to the VgpuTypeGetMaxInstancesPerGpuInstance method. + VgpuTypeGetMaxInstancesPerGpuInstance []struct { + // VgpuTypeMaxInstance is the vgpuTypeMaxInstance argument value. + VgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance + } + // VgpuTypeGetMaxInstancesPerVm holds details about calls to the VgpuTypeGetMaxInstancesPerVm method. + VgpuTypeGetMaxInstancesPerVm []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetName holds details about calls to the VgpuTypeGetName method. + VgpuTypeGetName []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetNumDisplayHeads holds details about calls to the VgpuTypeGetNumDisplayHeads method. + VgpuTypeGetNumDisplayHeads []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + } + // VgpuTypeGetResolution holds details about calls to the VgpuTypeGetResolution method. + VgpuTypeGetResolution []struct { + // VgpuTypeId is the vgpuTypeId argument value. + VgpuTypeId nvml.VgpuTypeId + // N is the n argument value. + N int + } + } + lockComputeInstanceDestroy sync.RWMutex + lockComputeInstanceGetInfo sync.RWMutex + lockDeviceClearAccountingPids sync.RWMutex + lockDeviceClearCpuAffinity sync.RWMutex + lockDeviceClearEccErrorCounts sync.RWMutex + lockDeviceClearFieldValues sync.RWMutex + lockDeviceCreateGpuInstance sync.RWMutex + lockDeviceCreateGpuInstanceWithPlacement sync.RWMutex + lockDeviceDiscoverGpus sync.RWMutex + lockDeviceFreezeNvLinkUtilizationCounter sync.RWMutex + lockDeviceGetAPIRestriction sync.RWMutex + lockDeviceGetAccountingBufferSize sync.RWMutex + lockDeviceGetAccountingMode sync.RWMutex + lockDeviceGetAccountingPids sync.RWMutex + lockDeviceGetAccountingStats sync.RWMutex + lockDeviceGetActiveVgpus sync.RWMutex + lockDeviceGetAdaptiveClockInfoStatus sync.RWMutex + lockDeviceGetAddressingMode sync.RWMutex + lockDeviceGetApplicationsClock sync.RWMutex + lockDeviceGetArchitecture sync.RWMutex + lockDeviceGetAttributes sync.RWMutex + lockDeviceGetAutoBoostedClocksEnabled sync.RWMutex + lockDeviceGetBAR1MemoryInfo sync.RWMutex + lockDeviceGetBoardId sync.RWMutex + lockDeviceGetBoardPartNumber sync.RWMutex + lockDeviceGetBrand sync.RWMutex + lockDeviceGetBridgeChipInfo sync.RWMutex + lockDeviceGetBusType sync.RWMutex + lockDeviceGetC2cModeInfoV sync.RWMutex + lockDeviceGetCapabilities sync.RWMutex + lockDeviceGetClkMonStatus sync.RWMutex + lockDeviceGetClock sync.RWMutex + lockDeviceGetClockInfo sync.RWMutex + lockDeviceGetClockOffsets sync.RWMutex + lockDeviceGetComputeInstanceId sync.RWMutex + lockDeviceGetComputeMode sync.RWMutex + lockDeviceGetComputeRunningProcesses sync.RWMutex + lockDeviceGetConfComputeGpuAttestationReport sync.RWMutex + lockDeviceGetConfComputeGpuCertificate sync.RWMutex + lockDeviceGetConfComputeMemSizeInfo sync.RWMutex + lockDeviceGetConfComputeProtectedMemoryUsage sync.RWMutex + lockDeviceGetCoolerInfo sync.RWMutex + lockDeviceGetCount sync.RWMutex + lockDeviceGetCpuAffinity sync.RWMutex + lockDeviceGetCpuAffinityWithinScope sync.RWMutex + lockDeviceGetCreatableVgpus sync.RWMutex + lockDeviceGetCudaComputeCapability sync.RWMutex + lockDeviceGetCurrPcieLinkGeneration sync.RWMutex + lockDeviceGetCurrPcieLinkWidth sync.RWMutex + lockDeviceGetCurrentClockFreqs sync.RWMutex + lockDeviceGetCurrentClocksEventReasons sync.RWMutex + lockDeviceGetCurrentClocksThrottleReasons sync.RWMutex + lockDeviceGetDecoderUtilization sync.RWMutex + lockDeviceGetDefaultApplicationsClock sync.RWMutex + lockDeviceGetDefaultEccMode sync.RWMutex + lockDeviceGetDetailedEccErrors sync.RWMutex + lockDeviceGetDeviceHandleFromMigDeviceHandle sync.RWMutex + lockDeviceGetDisplayActive sync.RWMutex + lockDeviceGetDisplayMode sync.RWMutex + lockDeviceGetDramEncryptionMode sync.RWMutex + lockDeviceGetDriverModel sync.RWMutex + lockDeviceGetDriverModel_v2 sync.RWMutex + lockDeviceGetDynamicPstatesInfo sync.RWMutex + lockDeviceGetEccMode sync.RWMutex + lockDeviceGetEncoderCapacity sync.RWMutex + lockDeviceGetEncoderSessions sync.RWMutex + lockDeviceGetEncoderStats sync.RWMutex + lockDeviceGetEncoderUtilization sync.RWMutex + lockDeviceGetEnforcedPowerLimit sync.RWMutex + lockDeviceGetFBCSessions sync.RWMutex + lockDeviceGetFBCStats sync.RWMutex + lockDeviceGetFanControlPolicy_v2 sync.RWMutex + lockDeviceGetFanSpeed sync.RWMutex + lockDeviceGetFanSpeedRPM sync.RWMutex + lockDeviceGetFanSpeed_v2 sync.RWMutex + lockDeviceGetFieldValues sync.RWMutex + lockDeviceGetGpcClkMinMaxVfOffset sync.RWMutex + lockDeviceGetGpcClkVfOffset sync.RWMutex + lockDeviceGetGpuFabricInfo sync.RWMutex + lockDeviceGetGpuFabricInfoV sync.RWMutex + lockDeviceGetGpuInstanceById sync.RWMutex + lockDeviceGetGpuInstanceId sync.RWMutex + lockDeviceGetGpuInstancePossiblePlacements sync.RWMutex + lockDeviceGetGpuInstanceProfileInfo sync.RWMutex + lockDeviceGetGpuInstanceProfileInfoByIdV sync.RWMutex + lockDeviceGetGpuInstanceProfileInfoV sync.RWMutex + lockDeviceGetGpuInstanceRemainingCapacity sync.RWMutex + lockDeviceGetGpuInstances sync.RWMutex + lockDeviceGetGpuMaxPcieLinkGeneration sync.RWMutex + lockDeviceGetGpuOperationMode sync.RWMutex + lockDeviceGetGraphicsRunningProcesses sync.RWMutex + lockDeviceGetGridLicensableFeatures sync.RWMutex + lockDeviceGetGspFirmwareMode sync.RWMutex + lockDeviceGetGspFirmwareVersion sync.RWMutex + lockDeviceGetHandleByIndex sync.RWMutex + lockDeviceGetHandleByPciBusId sync.RWMutex + lockDeviceGetHandleBySerial sync.RWMutex + lockDeviceGetHandleByUUID sync.RWMutex + lockDeviceGetHandleByUUIDV sync.RWMutex + lockDeviceGetHostVgpuMode sync.RWMutex + lockDeviceGetIndex sync.RWMutex + lockDeviceGetInforomConfigurationChecksum sync.RWMutex + lockDeviceGetInforomImageVersion sync.RWMutex + lockDeviceGetInforomVersion sync.RWMutex + lockDeviceGetIrqNum sync.RWMutex + lockDeviceGetJpgUtilization sync.RWMutex + lockDeviceGetLastBBXFlushTime sync.RWMutex + lockDeviceGetMPSComputeRunningProcesses sync.RWMutex + lockDeviceGetMarginTemperature sync.RWMutex + lockDeviceGetMaxClockInfo sync.RWMutex + lockDeviceGetMaxCustomerBoostClock sync.RWMutex + lockDeviceGetMaxMigDeviceCount sync.RWMutex + lockDeviceGetMaxPcieLinkGeneration sync.RWMutex + lockDeviceGetMaxPcieLinkWidth sync.RWMutex + lockDeviceGetMemClkMinMaxVfOffset sync.RWMutex + lockDeviceGetMemClkVfOffset sync.RWMutex + lockDeviceGetMemoryAffinity sync.RWMutex + lockDeviceGetMemoryBusWidth sync.RWMutex + lockDeviceGetMemoryErrorCounter sync.RWMutex + lockDeviceGetMemoryInfo sync.RWMutex + lockDeviceGetMemoryInfo_v2 sync.RWMutex + lockDeviceGetMigDeviceHandleByIndex sync.RWMutex + lockDeviceGetMigMode sync.RWMutex + lockDeviceGetMinMaxClockOfPState sync.RWMutex + lockDeviceGetMinMaxFanSpeed sync.RWMutex + lockDeviceGetMinorNumber sync.RWMutex + lockDeviceGetModuleId sync.RWMutex + lockDeviceGetMultiGpuBoard sync.RWMutex + lockDeviceGetName sync.RWMutex + lockDeviceGetNumFans sync.RWMutex + lockDeviceGetNumGpuCores sync.RWMutex + lockDeviceGetNumaNodeId sync.RWMutex + lockDeviceGetNvLinkCapability sync.RWMutex + lockDeviceGetNvLinkErrorCounter sync.RWMutex + lockDeviceGetNvLinkInfo sync.RWMutex + lockDeviceGetNvLinkRemoteDeviceType sync.RWMutex + lockDeviceGetNvLinkRemotePciInfo sync.RWMutex + lockDeviceGetNvLinkState sync.RWMutex + lockDeviceGetNvLinkUtilizationControl sync.RWMutex + lockDeviceGetNvLinkUtilizationCounter sync.RWMutex + lockDeviceGetNvLinkVersion sync.RWMutex + lockDeviceGetNvlinkBwMode sync.RWMutex + lockDeviceGetNvlinkSupportedBwModes sync.RWMutex + lockDeviceGetOfaUtilization sync.RWMutex + lockDeviceGetP2PStatus sync.RWMutex + lockDeviceGetPciInfo sync.RWMutex + lockDeviceGetPciInfoExt sync.RWMutex + lockDeviceGetPcieLinkMaxSpeed sync.RWMutex + lockDeviceGetPcieReplayCounter sync.RWMutex + lockDeviceGetPcieSpeed sync.RWMutex + lockDeviceGetPcieThroughput sync.RWMutex + lockDeviceGetPdi sync.RWMutex + lockDeviceGetPerformanceModes sync.RWMutex + lockDeviceGetPerformanceState sync.RWMutex + lockDeviceGetPersistenceMode sync.RWMutex + lockDeviceGetPgpuMetadataString sync.RWMutex + lockDeviceGetPlatformInfo sync.RWMutex + lockDeviceGetPowerManagementDefaultLimit sync.RWMutex + lockDeviceGetPowerManagementLimit sync.RWMutex + lockDeviceGetPowerManagementLimitConstraints sync.RWMutex + lockDeviceGetPowerManagementMode sync.RWMutex + lockDeviceGetPowerMizerMode_v1 sync.RWMutex + lockDeviceGetPowerSource sync.RWMutex + lockDeviceGetPowerState sync.RWMutex + lockDeviceGetPowerUsage sync.RWMutex + lockDeviceGetProcessUtilization sync.RWMutex + lockDeviceGetProcessesUtilizationInfo sync.RWMutex + lockDeviceGetRemappedRows sync.RWMutex + lockDeviceGetRepairStatus sync.RWMutex + lockDeviceGetRetiredPages sync.RWMutex + lockDeviceGetRetiredPagesPendingStatus sync.RWMutex + lockDeviceGetRetiredPages_v2 sync.RWMutex + lockDeviceGetRowRemapperHistogram sync.RWMutex + lockDeviceGetRunningProcessDetailList sync.RWMutex + lockDeviceGetSamples sync.RWMutex + lockDeviceGetSerial sync.RWMutex + lockDeviceGetSramEccErrorStatus sync.RWMutex + lockDeviceGetSramUniqueUncorrectedEccErrorCounts sync.RWMutex + lockDeviceGetSupportedClocksEventReasons sync.RWMutex + lockDeviceGetSupportedClocksThrottleReasons sync.RWMutex + lockDeviceGetSupportedEventTypes sync.RWMutex + lockDeviceGetSupportedGraphicsClocks sync.RWMutex + lockDeviceGetSupportedMemoryClocks sync.RWMutex + lockDeviceGetSupportedPerformanceStates sync.RWMutex + lockDeviceGetSupportedVgpus sync.RWMutex + lockDeviceGetTargetFanSpeed sync.RWMutex + lockDeviceGetTemperature sync.RWMutex + lockDeviceGetTemperatureThreshold sync.RWMutex + lockDeviceGetTemperatureV sync.RWMutex + lockDeviceGetThermalSettings sync.RWMutex + lockDeviceGetTopologyCommonAncestor sync.RWMutex + lockDeviceGetTopologyNearestGpus sync.RWMutex + lockDeviceGetTotalEccErrors sync.RWMutex + lockDeviceGetTotalEnergyConsumption sync.RWMutex + lockDeviceGetUUID sync.RWMutex + lockDeviceGetUtilizationRates sync.RWMutex + lockDeviceGetVbiosVersion sync.RWMutex + lockDeviceGetVgpuCapabilities sync.RWMutex + lockDeviceGetVgpuHeterogeneousMode sync.RWMutex + lockDeviceGetVgpuInstancesUtilizationInfo sync.RWMutex + lockDeviceGetVgpuMetadata sync.RWMutex + lockDeviceGetVgpuProcessUtilization sync.RWMutex + lockDeviceGetVgpuProcessesUtilizationInfo sync.RWMutex + lockDeviceGetVgpuSchedulerCapabilities sync.RWMutex + lockDeviceGetVgpuSchedulerLog sync.RWMutex + lockDeviceGetVgpuSchedulerState sync.RWMutex + lockDeviceGetVgpuTypeCreatablePlacements sync.RWMutex + lockDeviceGetVgpuTypeSupportedPlacements sync.RWMutex + lockDeviceGetVgpuUtilization sync.RWMutex + lockDeviceGetViolationStatus sync.RWMutex + lockDeviceGetVirtualizationMode sync.RWMutex + lockDeviceIsMigDeviceHandle sync.RWMutex + lockDeviceModifyDrainState sync.RWMutex + lockDeviceOnSameBoard sync.RWMutex + lockDevicePowerSmoothingActivatePresetProfile sync.RWMutex + lockDevicePowerSmoothingSetState sync.RWMutex + lockDevicePowerSmoothingUpdatePresetProfileParam sync.RWMutex + lockDeviceQueryDrainState sync.RWMutex + lockDeviceReadWritePRM_v1 sync.RWMutex + lockDeviceRegisterEvents sync.RWMutex + lockDeviceRemoveGpu sync.RWMutex + lockDeviceRemoveGpu_v2 sync.RWMutex + lockDeviceResetApplicationsClocks sync.RWMutex + lockDeviceResetGpuLockedClocks sync.RWMutex + lockDeviceResetMemoryLockedClocks sync.RWMutex + lockDeviceResetNvLinkErrorCounters sync.RWMutex + lockDeviceResetNvLinkUtilizationCounter sync.RWMutex + lockDeviceSetAPIRestriction sync.RWMutex + lockDeviceSetAccountingMode sync.RWMutex + lockDeviceSetApplicationsClocks sync.RWMutex + lockDeviceSetAutoBoostedClocksEnabled sync.RWMutex + lockDeviceSetClockOffsets sync.RWMutex + lockDeviceSetComputeMode sync.RWMutex + lockDeviceSetConfComputeUnprotectedMemSize sync.RWMutex + lockDeviceSetCpuAffinity sync.RWMutex + lockDeviceSetDefaultAutoBoostedClocksEnabled sync.RWMutex + lockDeviceSetDefaultFanSpeed_v2 sync.RWMutex + lockDeviceSetDramEncryptionMode sync.RWMutex + lockDeviceSetDriverModel sync.RWMutex + lockDeviceSetEccMode sync.RWMutex + lockDeviceSetFanControlPolicy sync.RWMutex + lockDeviceSetFanSpeed_v2 sync.RWMutex + lockDeviceSetGpcClkVfOffset sync.RWMutex + lockDeviceSetGpuLockedClocks sync.RWMutex + lockDeviceSetGpuOperationMode sync.RWMutex + lockDeviceSetMemClkVfOffset sync.RWMutex + lockDeviceSetMemoryLockedClocks sync.RWMutex + lockDeviceSetMigMode sync.RWMutex + lockDeviceSetNvLinkDeviceLowPowerThreshold sync.RWMutex + lockDeviceSetNvLinkUtilizationControl sync.RWMutex + lockDeviceSetNvlinkBwMode sync.RWMutex + lockDeviceSetPersistenceMode sync.RWMutex + lockDeviceSetPowerManagementLimit sync.RWMutex + lockDeviceSetPowerManagementLimit_v2 sync.RWMutex + lockDeviceSetTemperatureThreshold sync.RWMutex + lockDeviceSetVgpuCapabilities sync.RWMutex + lockDeviceSetVgpuHeterogeneousMode sync.RWMutex + lockDeviceSetVgpuSchedulerState sync.RWMutex + lockDeviceSetVirtualizationMode sync.RWMutex + lockDeviceValidateInforom sync.RWMutex + lockDeviceWorkloadPowerProfileClearRequestedProfiles sync.RWMutex + lockDeviceWorkloadPowerProfileGetCurrentProfiles sync.RWMutex + lockDeviceWorkloadPowerProfileGetProfilesInfo sync.RWMutex + lockDeviceWorkloadPowerProfileSetRequestedProfiles sync.RWMutex + lockErrorString sync.RWMutex + lockEventSetCreate sync.RWMutex + lockEventSetFree sync.RWMutex + lockEventSetWait sync.RWMutex + lockExtensions sync.RWMutex + lockGetExcludedDeviceCount sync.RWMutex + lockGetExcludedDeviceInfoByIndex sync.RWMutex + lockGetVgpuCompatibility sync.RWMutex + lockGetVgpuDriverCapabilities sync.RWMutex + lockGetVgpuVersion sync.RWMutex + lockGpmMetricsGet sync.RWMutex + lockGpmMetricsGetV sync.RWMutex + lockGpmMigSampleGet sync.RWMutex + lockGpmQueryDeviceSupport sync.RWMutex + lockGpmQueryDeviceSupportV sync.RWMutex + lockGpmQueryIfStreamingEnabled sync.RWMutex + lockGpmSampleAlloc sync.RWMutex + lockGpmSampleFree sync.RWMutex + lockGpmSampleGet sync.RWMutex + lockGpmSetStreamingEnabled sync.RWMutex + lockGpuInstanceCreateComputeInstance sync.RWMutex + lockGpuInstanceCreateComputeInstanceWithPlacement sync.RWMutex + lockGpuInstanceDestroy sync.RWMutex + lockGpuInstanceGetActiveVgpus sync.RWMutex + lockGpuInstanceGetComputeInstanceById sync.RWMutex + lockGpuInstanceGetComputeInstancePossiblePlacements sync.RWMutex + lockGpuInstanceGetComputeInstanceProfileInfo sync.RWMutex + lockGpuInstanceGetComputeInstanceProfileInfoV sync.RWMutex + lockGpuInstanceGetComputeInstanceRemainingCapacity sync.RWMutex + lockGpuInstanceGetComputeInstances sync.RWMutex + lockGpuInstanceGetCreatableVgpus sync.RWMutex + lockGpuInstanceGetInfo sync.RWMutex + lockGpuInstanceGetVgpuHeterogeneousMode sync.RWMutex + lockGpuInstanceGetVgpuSchedulerLog sync.RWMutex + lockGpuInstanceGetVgpuSchedulerState sync.RWMutex + lockGpuInstanceGetVgpuTypeCreatablePlacements sync.RWMutex + lockGpuInstanceSetVgpuHeterogeneousMode sync.RWMutex + lockGpuInstanceSetVgpuSchedulerState sync.RWMutex + lockInit sync.RWMutex + lockInitWithFlags sync.RWMutex + lockSetVgpuVersion sync.RWMutex + lockShutdown sync.RWMutex + lockSystemEventSetCreate sync.RWMutex + lockSystemEventSetFree sync.RWMutex + lockSystemEventSetWait sync.RWMutex + lockSystemGetConfComputeCapabilities sync.RWMutex + lockSystemGetConfComputeGpusReadyState sync.RWMutex + lockSystemGetConfComputeKeyRotationThresholdInfo sync.RWMutex + lockSystemGetConfComputeSettings sync.RWMutex + lockSystemGetConfComputeState sync.RWMutex + lockSystemGetCudaDriverVersion sync.RWMutex + lockSystemGetCudaDriverVersion_v2 sync.RWMutex + lockSystemGetDriverBranch sync.RWMutex + lockSystemGetDriverVersion sync.RWMutex + lockSystemGetHicVersion sync.RWMutex + lockSystemGetNVMLVersion sync.RWMutex + lockSystemGetNvlinkBwMode sync.RWMutex + lockSystemGetProcessName sync.RWMutex + lockSystemGetTopologyGpuSet sync.RWMutex + lockSystemRegisterEvents sync.RWMutex + lockSystemSetConfComputeGpusReadyState sync.RWMutex + lockSystemSetConfComputeKeyRotationThresholdInfo sync.RWMutex + lockSystemSetNvlinkBwMode sync.RWMutex + lockUnitGetCount sync.RWMutex + lockUnitGetDevices sync.RWMutex + lockUnitGetFanSpeedInfo sync.RWMutex + lockUnitGetHandleByIndex sync.RWMutex + lockUnitGetLedState sync.RWMutex + lockUnitGetPsuInfo sync.RWMutex + lockUnitGetTemperature sync.RWMutex + lockUnitGetUnitInfo sync.RWMutex + lockUnitSetLedState sync.RWMutex + lockVgpuInstanceClearAccountingPids sync.RWMutex + lockVgpuInstanceGetAccountingMode sync.RWMutex + lockVgpuInstanceGetAccountingPids sync.RWMutex + lockVgpuInstanceGetAccountingStats sync.RWMutex + lockVgpuInstanceGetEccMode sync.RWMutex + lockVgpuInstanceGetEncoderCapacity sync.RWMutex + lockVgpuInstanceGetEncoderSessions sync.RWMutex + lockVgpuInstanceGetEncoderStats sync.RWMutex + lockVgpuInstanceGetFBCSessions sync.RWMutex + lockVgpuInstanceGetFBCStats sync.RWMutex + lockVgpuInstanceGetFbUsage sync.RWMutex + lockVgpuInstanceGetFrameRateLimit sync.RWMutex + lockVgpuInstanceGetGpuInstanceId sync.RWMutex + lockVgpuInstanceGetGpuPciId sync.RWMutex + lockVgpuInstanceGetLicenseInfo sync.RWMutex + lockVgpuInstanceGetLicenseStatus sync.RWMutex + lockVgpuInstanceGetMdevUUID sync.RWMutex + lockVgpuInstanceGetMetadata sync.RWMutex + lockVgpuInstanceGetRuntimeStateSize sync.RWMutex + lockVgpuInstanceGetType sync.RWMutex + lockVgpuInstanceGetUUID sync.RWMutex + lockVgpuInstanceGetVmDriverVersion sync.RWMutex + lockVgpuInstanceGetVmID sync.RWMutex + lockVgpuInstanceSetEncoderCapacity sync.RWMutex + lockVgpuTypeGetBAR1Info sync.RWMutex + lockVgpuTypeGetCapabilities sync.RWMutex + lockVgpuTypeGetClass sync.RWMutex + lockVgpuTypeGetDeviceID sync.RWMutex + lockVgpuTypeGetFrameRateLimit sync.RWMutex + lockVgpuTypeGetFramebufferSize sync.RWMutex + lockVgpuTypeGetGpuInstanceProfileId sync.RWMutex + lockVgpuTypeGetLicense sync.RWMutex + lockVgpuTypeGetMaxInstances sync.RWMutex + lockVgpuTypeGetMaxInstancesPerGpuInstance sync.RWMutex + lockVgpuTypeGetMaxInstancesPerVm sync.RWMutex + lockVgpuTypeGetName sync.RWMutex + lockVgpuTypeGetNumDisplayHeads sync.RWMutex + lockVgpuTypeGetResolution sync.RWMutex +} + +// ComputeInstanceDestroy calls ComputeInstanceDestroyFunc. +func (mock *Interface) ComputeInstanceDestroy(computeInstance nvml.ComputeInstance) nvml.Return { + if mock.ComputeInstanceDestroyFunc == nil { + panic("Interface.ComputeInstanceDestroyFunc: method is nil but Interface.ComputeInstanceDestroy was just called") + } + callInfo := struct { + ComputeInstance nvml.ComputeInstance + }{ + ComputeInstance: computeInstance, + } + mock.lockComputeInstanceDestroy.Lock() + mock.calls.ComputeInstanceDestroy = append(mock.calls.ComputeInstanceDestroy, callInfo) + mock.lockComputeInstanceDestroy.Unlock() + return mock.ComputeInstanceDestroyFunc(computeInstance) +} + +// ComputeInstanceDestroyCalls gets all the calls that were made to ComputeInstanceDestroy. +// Check the length with: +// +// len(mockedInterface.ComputeInstanceDestroyCalls()) +func (mock *Interface) ComputeInstanceDestroyCalls() []struct { + ComputeInstance nvml.ComputeInstance +} { + var calls []struct { + ComputeInstance nvml.ComputeInstance + } + mock.lockComputeInstanceDestroy.RLock() + calls = mock.calls.ComputeInstanceDestroy + mock.lockComputeInstanceDestroy.RUnlock() + return calls +} + +// ComputeInstanceGetInfo calls ComputeInstanceGetInfoFunc. +func (mock *Interface) ComputeInstanceGetInfo(computeInstance nvml.ComputeInstance) (nvml.ComputeInstanceInfo, nvml.Return) { + if mock.ComputeInstanceGetInfoFunc == nil { + panic("Interface.ComputeInstanceGetInfoFunc: method is nil but Interface.ComputeInstanceGetInfo was just called") + } + callInfo := struct { + ComputeInstance nvml.ComputeInstance + }{ + ComputeInstance: computeInstance, + } + mock.lockComputeInstanceGetInfo.Lock() + mock.calls.ComputeInstanceGetInfo = append(mock.calls.ComputeInstanceGetInfo, callInfo) + mock.lockComputeInstanceGetInfo.Unlock() + return mock.ComputeInstanceGetInfoFunc(computeInstance) +} + +// ComputeInstanceGetInfoCalls gets all the calls that were made to ComputeInstanceGetInfo. +// Check the length with: +// +// len(mockedInterface.ComputeInstanceGetInfoCalls()) +func (mock *Interface) ComputeInstanceGetInfoCalls() []struct { + ComputeInstance nvml.ComputeInstance +} { + var calls []struct { + ComputeInstance nvml.ComputeInstance + } + mock.lockComputeInstanceGetInfo.RLock() + calls = mock.calls.ComputeInstanceGetInfo + mock.lockComputeInstanceGetInfo.RUnlock() + return calls +} + +// DeviceClearAccountingPids calls DeviceClearAccountingPidsFunc. +func (mock *Interface) DeviceClearAccountingPids(device nvml.Device) nvml.Return { + if mock.DeviceClearAccountingPidsFunc == nil { + panic("Interface.DeviceClearAccountingPidsFunc: method is nil but Interface.DeviceClearAccountingPids was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceClearAccountingPids.Lock() + mock.calls.DeviceClearAccountingPids = append(mock.calls.DeviceClearAccountingPids, callInfo) + mock.lockDeviceClearAccountingPids.Unlock() + return mock.DeviceClearAccountingPidsFunc(device) +} + +// DeviceClearAccountingPidsCalls gets all the calls that were made to DeviceClearAccountingPids. +// Check the length with: +// +// len(mockedInterface.DeviceClearAccountingPidsCalls()) +func (mock *Interface) DeviceClearAccountingPidsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceClearAccountingPids.RLock() + calls = mock.calls.DeviceClearAccountingPids + mock.lockDeviceClearAccountingPids.RUnlock() + return calls +} + +// DeviceClearCpuAffinity calls DeviceClearCpuAffinityFunc. +func (mock *Interface) DeviceClearCpuAffinity(device nvml.Device) nvml.Return { + if mock.DeviceClearCpuAffinityFunc == nil { + panic("Interface.DeviceClearCpuAffinityFunc: method is nil but Interface.DeviceClearCpuAffinity was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceClearCpuAffinity.Lock() + mock.calls.DeviceClearCpuAffinity = append(mock.calls.DeviceClearCpuAffinity, callInfo) + mock.lockDeviceClearCpuAffinity.Unlock() + return mock.DeviceClearCpuAffinityFunc(device) +} + +// DeviceClearCpuAffinityCalls gets all the calls that were made to DeviceClearCpuAffinity. +// Check the length with: +// +// len(mockedInterface.DeviceClearCpuAffinityCalls()) +func (mock *Interface) DeviceClearCpuAffinityCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceClearCpuAffinity.RLock() + calls = mock.calls.DeviceClearCpuAffinity + mock.lockDeviceClearCpuAffinity.RUnlock() + return calls +} + +// DeviceClearEccErrorCounts calls DeviceClearEccErrorCountsFunc. +func (mock *Interface) DeviceClearEccErrorCounts(device nvml.Device, eccCounterType nvml.EccCounterType) nvml.Return { + if mock.DeviceClearEccErrorCountsFunc == nil { + panic("Interface.DeviceClearEccErrorCountsFunc: method is nil but Interface.DeviceClearEccErrorCounts was just called") + } + callInfo := struct { + Device nvml.Device + EccCounterType nvml.EccCounterType + }{ + Device: device, + EccCounterType: eccCounterType, + } + mock.lockDeviceClearEccErrorCounts.Lock() + mock.calls.DeviceClearEccErrorCounts = append(mock.calls.DeviceClearEccErrorCounts, callInfo) + mock.lockDeviceClearEccErrorCounts.Unlock() + return mock.DeviceClearEccErrorCountsFunc(device, eccCounterType) +} + +// DeviceClearEccErrorCountsCalls gets all the calls that were made to DeviceClearEccErrorCounts. +// Check the length with: +// +// len(mockedInterface.DeviceClearEccErrorCountsCalls()) +func (mock *Interface) DeviceClearEccErrorCountsCalls() []struct { + Device nvml.Device + EccCounterType nvml.EccCounterType +} { + var calls []struct { + Device nvml.Device + EccCounterType nvml.EccCounterType + } + mock.lockDeviceClearEccErrorCounts.RLock() + calls = mock.calls.DeviceClearEccErrorCounts + mock.lockDeviceClearEccErrorCounts.RUnlock() + return calls +} + +// DeviceClearFieldValues calls DeviceClearFieldValuesFunc. +func (mock *Interface) DeviceClearFieldValues(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return { + if mock.DeviceClearFieldValuesFunc == nil { + panic("Interface.DeviceClearFieldValuesFunc: method is nil but Interface.DeviceClearFieldValues was just called") + } + callInfo := struct { + Device nvml.Device + FieldValues []nvml.FieldValue + }{ + Device: device, + FieldValues: fieldValues, + } + mock.lockDeviceClearFieldValues.Lock() + mock.calls.DeviceClearFieldValues = append(mock.calls.DeviceClearFieldValues, callInfo) + mock.lockDeviceClearFieldValues.Unlock() + return mock.DeviceClearFieldValuesFunc(device, fieldValues) +} + +// DeviceClearFieldValuesCalls gets all the calls that were made to DeviceClearFieldValues. +// Check the length with: +// +// len(mockedInterface.DeviceClearFieldValuesCalls()) +func (mock *Interface) DeviceClearFieldValuesCalls() []struct { + Device nvml.Device + FieldValues []nvml.FieldValue +} { + var calls []struct { + Device nvml.Device + FieldValues []nvml.FieldValue + } + mock.lockDeviceClearFieldValues.RLock() + calls = mock.calls.DeviceClearFieldValues + mock.lockDeviceClearFieldValues.RUnlock() + return calls +} + +// DeviceCreateGpuInstance calls DeviceCreateGpuInstanceFunc. +func (mock *Interface) DeviceCreateGpuInstance(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (nvml.GpuInstance, nvml.Return) { + if mock.DeviceCreateGpuInstanceFunc == nil { + panic("Interface.DeviceCreateGpuInstanceFunc: method is nil but Interface.DeviceCreateGpuInstance was just called") + } + callInfo := struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + Device: device, + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockDeviceCreateGpuInstance.Lock() + mock.calls.DeviceCreateGpuInstance = append(mock.calls.DeviceCreateGpuInstance, callInfo) + mock.lockDeviceCreateGpuInstance.Unlock() + return mock.DeviceCreateGpuInstanceFunc(device, gpuInstanceProfileInfo) +} + +// DeviceCreateGpuInstanceCalls gets all the calls that were made to DeviceCreateGpuInstance. +// Check the length with: +// +// len(mockedInterface.DeviceCreateGpuInstanceCalls()) +func (mock *Interface) DeviceCreateGpuInstanceCalls() []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockDeviceCreateGpuInstance.RLock() + calls = mock.calls.DeviceCreateGpuInstance + mock.lockDeviceCreateGpuInstance.RUnlock() + return calls +} + +// DeviceCreateGpuInstanceWithPlacement calls DeviceCreateGpuInstanceWithPlacementFunc. +func (mock *Interface) DeviceCreateGpuInstanceWithPlacement(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo, gpuInstancePlacement *nvml.GpuInstancePlacement) (nvml.GpuInstance, nvml.Return) { + if mock.DeviceCreateGpuInstanceWithPlacementFunc == nil { + panic("Interface.DeviceCreateGpuInstanceWithPlacementFunc: method is nil but Interface.DeviceCreateGpuInstanceWithPlacement was just called") + } + callInfo := struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement + }{ + Device: device, + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + GpuInstancePlacement: gpuInstancePlacement, + } + mock.lockDeviceCreateGpuInstanceWithPlacement.Lock() + mock.calls.DeviceCreateGpuInstanceWithPlacement = append(mock.calls.DeviceCreateGpuInstanceWithPlacement, callInfo) + mock.lockDeviceCreateGpuInstanceWithPlacement.Unlock() + return mock.DeviceCreateGpuInstanceWithPlacementFunc(device, gpuInstanceProfileInfo, gpuInstancePlacement) +} + +// DeviceCreateGpuInstanceWithPlacementCalls gets all the calls that were made to DeviceCreateGpuInstanceWithPlacement. +// Check the length with: +// +// len(mockedInterface.DeviceCreateGpuInstanceWithPlacementCalls()) +func (mock *Interface) DeviceCreateGpuInstanceWithPlacementCalls() []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement +} { + var calls []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + GpuInstancePlacement *nvml.GpuInstancePlacement + } + mock.lockDeviceCreateGpuInstanceWithPlacement.RLock() + calls = mock.calls.DeviceCreateGpuInstanceWithPlacement + mock.lockDeviceCreateGpuInstanceWithPlacement.RUnlock() + return calls +} + +// DeviceDiscoverGpus calls DeviceDiscoverGpusFunc. +func (mock *Interface) DeviceDiscoverGpus() (nvml.PciInfo, nvml.Return) { + if mock.DeviceDiscoverGpusFunc == nil { + panic("Interface.DeviceDiscoverGpusFunc: method is nil but Interface.DeviceDiscoverGpus was just called") + } + callInfo := struct { + }{} + mock.lockDeviceDiscoverGpus.Lock() + mock.calls.DeviceDiscoverGpus = append(mock.calls.DeviceDiscoverGpus, callInfo) + mock.lockDeviceDiscoverGpus.Unlock() + return mock.DeviceDiscoverGpusFunc() +} + +// DeviceDiscoverGpusCalls gets all the calls that were made to DeviceDiscoverGpus. +// Check the length with: +// +// len(mockedInterface.DeviceDiscoverGpusCalls()) +func (mock *Interface) DeviceDiscoverGpusCalls() []struct { +} { + var calls []struct { + } + mock.lockDeviceDiscoverGpus.RLock() + calls = mock.calls.DeviceDiscoverGpus + mock.lockDeviceDiscoverGpus.RUnlock() + return calls +} + +// DeviceFreezeNvLinkUtilizationCounter calls DeviceFreezeNvLinkUtilizationCounterFunc. +func (mock *Interface) DeviceFreezeNvLinkUtilizationCounter(device nvml.Device, n1 int, n2 int, enableState nvml.EnableState) nvml.Return { + if mock.DeviceFreezeNvLinkUtilizationCounterFunc == nil { + panic("Interface.DeviceFreezeNvLinkUtilizationCounterFunc: method is nil but Interface.DeviceFreezeNvLinkUtilizationCounter was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + EnableState nvml.EnableState + }{ + Device: device, + N1: n1, + N2: n2, + EnableState: enableState, + } + mock.lockDeviceFreezeNvLinkUtilizationCounter.Lock() + mock.calls.DeviceFreezeNvLinkUtilizationCounter = append(mock.calls.DeviceFreezeNvLinkUtilizationCounter, callInfo) + mock.lockDeviceFreezeNvLinkUtilizationCounter.Unlock() + return mock.DeviceFreezeNvLinkUtilizationCounterFunc(device, n1, n2, enableState) +} + +// DeviceFreezeNvLinkUtilizationCounterCalls gets all the calls that were made to DeviceFreezeNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedInterface.DeviceFreezeNvLinkUtilizationCounterCalls()) +func (mock *Interface) DeviceFreezeNvLinkUtilizationCounterCalls() []struct { + Device nvml.Device + N1 int + N2 int + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + EnableState nvml.EnableState + } + mock.lockDeviceFreezeNvLinkUtilizationCounter.RLock() + calls = mock.calls.DeviceFreezeNvLinkUtilizationCounter + mock.lockDeviceFreezeNvLinkUtilizationCounter.RUnlock() + return calls +} + +// DeviceGetAPIRestriction calls DeviceGetAPIRestrictionFunc. +func (mock *Interface) DeviceGetAPIRestriction(device nvml.Device, restrictedAPI nvml.RestrictedAPI) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetAPIRestrictionFunc == nil { + panic("Interface.DeviceGetAPIRestrictionFunc: method is nil but Interface.DeviceGetAPIRestriction was just called") + } + callInfo := struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI + }{ + Device: device, + RestrictedAPI: restrictedAPI, + } + mock.lockDeviceGetAPIRestriction.Lock() + mock.calls.DeviceGetAPIRestriction = append(mock.calls.DeviceGetAPIRestriction, callInfo) + mock.lockDeviceGetAPIRestriction.Unlock() + return mock.DeviceGetAPIRestrictionFunc(device, restrictedAPI) +} + +// DeviceGetAPIRestrictionCalls gets all the calls that were made to DeviceGetAPIRestriction. +// Check the length with: +// +// len(mockedInterface.DeviceGetAPIRestrictionCalls()) +func (mock *Interface) DeviceGetAPIRestrictionCalls() []struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI +} { + var calls []struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI + } + mock.lockDeviceGetAPIRestriction.RLock() + calls = mock.calls.DeviceGetAPIRestriction + mock.lockDeviceGetAPIRestriction.RUnlock() + return calls +} + +// DeviceGetAccountingBufferSize calls DeviceGetAccountingBufferSizeFunc. +func (mock *Interface) DeviceGetAccountingBufferSize(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetAccountingBufferSizeFunc == nil { + panic("Interface.DeviceGetAccountingBufferSizeFunc: method is nil but Interface.DeviceGetAccountingBufferSize was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAccountingBufferSize.Lock() + mock.calls.DeviceGetAccountingBufferSize = append(mock.calls.DeviceGetAccountingBufferSize, callInfo) + mock.lockDeviceGetAccountingBufferSize.Unlock() + return mock.DeviceGetAccountingBufferSizeFunc(device) +} + +// DeviceGetAccountingBufferSizeCalls gets all the calls that were made to DeviceGetAccountingBufferSize. +// Check the length with: +// +// len(mockedInterface.DeviceGetAccountingBufferSizeCalls()) +func (mock *Interface) DeviceGetAccountingBufferSizeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAccountingBufferSize.RLock() + calls = mock.calls.DeviceGetAccountingBufferSize + mock.lockDeviceGetAccountingBufferSize.RUnlock() + return calls +} + +// DeviceGetAccountingMode calls DeviceGetAccountingModeFunc. +func (mock *Interface) DeviceGetAccountingMode(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetAccountingModeFunc == nil { + panic("Interface.DeviceGetAccountingModeFunc: method is nil but Interface.DeviceGetAccountingMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAccountingMode.Lock() + mock.calls.DeviceGetAccountingMode = append(mock.calls.DeviceGetAccountingMode, callInfo) + mock.lockDeviceGetAccountingMode.Unlock() + return mock.DeviceGetAccountingModeFunc(device) +} + +// DeviceGetAccountingModeCalls gets all the calls that were made to DeviceGetAccountingMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetAccountingModeCalls()) +func (mock *Interface) DeviceGetAccountingModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAccountingMode.RLock() + calls = mock.calls.DeviceGetAccountingMode + mock.lockDeviceGetAccountingMode.RUnlock() + return calls +} + +// DeviceGetAccountingPids calls DeviceGetAccountingPidsFunc. +func (mock *Interface) DeviceGetAccountingPids(device nvml.Device) ([]int, nvml.Return) { + if mock.DeviceGetAccountingPidsFunc == nil { + panic("Interface.DeviceGetAccountingPidsFunc: method is nil but Interface.DeviceGetAccountingPids was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAccountingPids.Lock() + mock.calls.DeviceGetAccountingPids = append(mock.calls.DeviceGetAccountingPids, callInfo) + mock.lockDeviceGetAccountingPids.Unlock() + return mock.DeviceGetAccountingPidsFunc(device) +} + +// DeviceGetAccountingPidsCalls gets all the calls that were made to DeviceGetAccountingPids. +// Check the length with: +// +// len(mockedInterface.DeviceGetAccountingPidsCalls()) +func (mock *Interface) DeviceGetAccountingPidsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAccountingPids.RLock() + calls = mock.calls.DeviceGetAccountingPids + mock.lockDeviceGetAccountingPids.RUnlock() + return calls +} + +// DeviceGetAccountingStats calls DeviceGetAccountingStatsFunc. +func (mock *Interface) DeviceGetAccountingStats(device nvml.Device, v uint32) (nvml.AccountingStats, nvml.Return) { + if mock.DeviceGetAccountingStatsFunc == nil { + panic("Interface.DeviceGetAccountingStatsFunc: method is nil but Interface.DeviceGetAccountingStats was just called") + } + callInfo := struct { + Device nvml.Device + V uint32 + }{ + Device: device, + V: v, + } + mock.lockDeviceGetAccountingStats.Lock() + mock.calls.DeviceGetAccountingStats = append(mock.calls.DeviceGetAccountingStats, callInfo) + mock.lockDeviceGetAccountingStats.Unlock() + return mock.DeviceGetAccountingStatsFunc(device, v) +} + +// DeviceGetAccountingStatsCalls gets all the calls that were made to DeviceGetAccountingStats. +// Check the length with: +// +// len(mockedInterface.DeviceGetAccountingStatsCalls()) +func (mock *Interface) DeviceGetAccountingStatsCalls() []struct { + Device nvml.Device + V uint32 +} { + var calls []struct { + Device nvml.Device + V uint32 + } + mock.lockDeviceGetAccountingStats.RLock() + calls = mock.calls.DeviceGetAccountingStats + mock.lockDeviceGetAccountingStats.RUnlock() + return calls +} + +// DeviceGetActiveVgpus calls DeviceGetActiveVgpusFunc. +func (mock *Interface) DeviceGetActiveVgpus(device nvml.Device) ([]nvml.VgpuInstance, nvml.Return) { + if mock.DeviceGetActiveVgpusFunc == nil { + panic("Interface.DeviceGetActiveVgpusFunc: method is nil but Interface.DeviceGetActiveVgpus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetActiveVgpus.Lock() + mock.calls.DeviceGetActiveVgpus = append(mock.calls.DeviceGetActiveVgpus, callInfo) + mock.lockDeviceGetActiveVgpus.Unlock() + return mock.DeviceGetActiveVgpusFunc(device) +} + +// DeviceGetActiveVgpusCalls gets all the calls that were made to DeviceGetActiveVgpus. +// Check the length with: +// +// len(mockedInterface.DeviceGetActiveVgpusCalls()) +func (mock *Interface) DeviceGetActiveVgpusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetActiveVgpus.RLock() + calls = mock.calls.DeviceGetActiveVgpus + mock.lockDeviceGetActiveVgpus.RUnlock() + return calls +} + +// DeviceGetAdaptiveClockInfoStatus calls DeviceGetAdaptiveClockInfoStatusFunc. +func (mock *Interface) DeviceGetAdaptiveClockInfoStatus(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetAdaptiveClockInfoStatusFunc == nil { + panic("Interface.DeviceGetAdaptiveClockInfoStatusFunc: method is nil but Interface.DeviceGetAdaptiveClockInfoStatus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAdaptiveClockInfoStatus.Lock() + mock.calls.DeviceGetAdaptiveClockInfoStatus = append(mock.calls.DeviceGetAdaptiveClockInfoStatus, callInfo) + mock.lockDeviceGetAdaptiveClockInfoStatus.Unlock() + return mock.DeviceGetAdaptiveClockInfoStatusFunc(device) +} + +// DeviceGetAdaptiveClockInfoStatusCalls gets all the calls that were made to DeviceGetAdaptiveClockInfoStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetAdaptiveClockInfoStatusCalls()) +func (mock *Interface) DeviceGetAdaptiveClockInfoStatusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAdaptiveClockInfoStatus.RLock() + calls = mock.calls.DeviceGetAdaptiveClockInfoStatus + mock.lockDeviceGetAdaptiveClockInfoStatus.RUnlock() + return calls +} + +// DeviceGetAddressingMode calls DeviceGetAddressingModeFunc. +func (mock *Interface) DeviceGetAddressingMode(device nvml.Device) (nvml.DeviceAddressingMode, nvml.Return) { + if mock.DeviceGetAddressingModeFunc == nil { + panic("Interface.DeviceGetAddressingModeFunc: method is nil but Interface.DeviceGetAddressingMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAddressingMode.Lock() + mock.calls.DeviceGetAddressingMode = append(mock.calls.DeviceGetAddressingMode, callInfo) + mock.lockDeviceGetAddressingMode.Unlock() + return mock.DeviceGetAddressingModeFunc(device) +} + +// DeviceGetAddressingModeCalls gets all the calls that were made to DeviceGetAddressingMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetAddressingModeCalls()) +func (mock *Interface) DeviceGetAddressingModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAddressingMode.RLock() + calls = mock.calls.DeviceGetAddressingMode + mock.lockDeviceGetAddressingMode.RUnlock() + return calls +} + +// DeviceGetApplicationsClock calls DeviceGetApplicationsClockFunc. +func (mock *Interface) DeviceGetApplicationsClock(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.DeviceGetApplicationsClockFunc == nil { + panic("Interface.DeviceGetApplicationsClockFunc: method is nil but Interface.DeviceGetApplicationsClock was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + }{ + Device: device, + ClockType: clockType, + } + mock.lockDeviceGetApplicationsClock.Lock() + mock.calls.DeviceGetApplicationsClock = append(mock.calls.DeviceGetApplicationsClock, callInfo) + mock.lockDeviceGetApplicationsClock.Unlock() + return mock.DeviceGetApplicationsClockFunc(device, clockType) +} + +// DeviceGetApplicationsClockCalls gets all the calls that were made to DeviceGetApplicationsClock. +// Check the length with: +// +// len(mockedInterface.DeviceGetApplicationsClockCalls()) +func (mock *Interface) DeviceGetApplicationsClockCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + } + mock.lockDeviceGetApplicationsClock.RLock() + calls = mock.calls.DeviceGetApplicationsClock + mock.lockDeviceGetApplicationsClock.RUnlock() + return calls +} + +// DeviceGetArchitecture calls DeviceGetArchitectureFunc. +func (mock *Interface) DeviceGetArchitecture(device nvml.Device) (nvml.DeviceArchitecture, nvml.Return) { + if mock.DeviceGetArchitectureFunc == nil { + panic("Interface.DeviceGetArchitectureFunc: method is nil but Interface.DeviceGetArchitecture was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetArchitecture.Lock() + mock.calls.DeviceGetArchitecture = append(mock.calls.DeviceGetArchitecture, callInfo) + mock.lockDeviceGetArchitecture.Unlock() + return mock.DeviceGetArchitectureFunc(device) +} + +// DeviceGetArchitectureCalls gets all the calls that were made to DeviceGetArchitecture. +// Check the length with: +// +// len(mockedInterface.DeviceGetArchitectureCalls()) +func (mock *Interface) DeviceGetArchitectureCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetArchitecture.RLock() + calls = mock.calls.DeviceGetArchitecture + mock.lockDeviceGetArchitecture.RUnlock() + return calls +} + +// DeviceGetAttributes calls DeviceGetAttributesFunc. +func (mock *Interface) DeviceGetAttributes(device nvml.Device) (nvml.DeviceAttributes, nvml.Return) { + if mock.DeviceGetAttributesFunc == nil { + panic("Interface.DeviceGetAttributesFunc: method is nil but Interface.DeviceGetAttributes was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAttributes.Lock() + mock.calls.DeviceGetAttributes = append(mock.calls.DeviceGetAttributes, callInfo) + mock.lockDeviceGetAttributes.Unlock() + return mock.DeviceGetAttributesFunc(device) +} + +// DeviceGetAttributesCalls gets all the calls that were made to DeviceGetAttributes. +// Check the length with: +// +// len(mockedInterface.DeviceGetAttributesCalls()) +func (mock *Interface) DeviceGetAttributesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAttributes.RLock() + calls = mock.calls.DeviceGetAttributes + mock.lockDeviceGetAttributes.RUnlock() + return calls +} + +// DeviceGetAutoBoostedClocksEnabled calls DeviceGetAutoBoostedClocksEnabledFunc. +func (mock *Interface) DeviceGetAutoBoostedClocksEnabled(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) { + if mock.DeviceGetAutoBoostedClocksEnabledFunc == nil { + panic("Interface.DeviceGetAutoBoostedClocksEnabledFunc: method is nil but Interface.DeviceGetAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetAutoBoostedClocksEnabled.Lock() + mock.calls.DeviceGetAutoBoostedClocksEnabled = append(mock.calls.DeviceGetAutoBoostedClocksEnabled, callInfo) + mock.lockDeviceGetAutoBoostedClocksEnabled.Unlock() + return mock.DeviceGetAutoBoostedClocksEnabledFunc(device) +} + +// DeviceGetAutoBoostedClocksEnabledCalls gets all the calls that were made to DeviceGetAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedInterface.DeviceGetAutoBoostedClocksEnabledCalls()) +func (mock *Interface) DeviceGetAutoBoostedClocksEnabledCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetAutoBoostedClocksEnabled.RLock() + calls = mock.calls.DeviceGetAutoBoostedClocksEnabled + mock.lockDeviceGetAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// DeviceGetBAR1MemoryInfo calls DeviceGetBAR1MemoryInfoFunc. +func (mock *Interface) DeviceGetBAR1MemoryInfo(device nvml.Device) (nvml.BAR1Memory, nvml.Return) { + if mock.DeviceGetBAR1MemoryInfoFunc == nil { + panic("Interface.DeviceGetBAR1MemoryInfoFunc: method is nil but Interface.DeviceGetBAR1MemoryInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBAR1MemoryInfo.Lock() + mock.calls.DeviceGetBAR1MemoryInfo = append(mock.calls.DeviceGetBAR1MemoryInfo, callInfo) + mock.lockDeviceGetBAR1MemoryInfo.Unlock() + return mock.DeviceGetBAR1MemoryInfoFunc(device) +} + +// DeviceGetBAR1MemoryInfoCalls gets all the calls that were made to DeviceGetBAR1MemoryInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetBAR1MemoryInfoCalls()) +func (mock *Interface) DeviceGetBAR1MemoryInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBAR1MemoryInfo.RLock() + calls = mock.calls.DeviceGetBAR1MemoryInfo + mock.lockDeviceGetBAR1MemoryInfo.RUnlock() + return calls +} + +// DeviceGetBoardId calls DeviceGetBoardIdFunc. +func (mock *Interface) DeviceGetBoardId(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetBoardIdFunc == nil { + panic("Interface.DeviceGetBoardIdFunc: method is nil but Interface.DeviceGetBoardId was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBoardId.Lock() + mock.calls.DeviceGetBoardId = append(mock.calls.DeviceGetBoardId, callInfo) + mock.lockDeviceGetBoardId.Unlock() + return mock.DeviceGetBoardIdFunc(device) +} + +// DeviceGetBoardIdCalls gets all the calls that were made to DeviceGetBoardId. +// Check the length with: +// +// len(mockedInterface.DeviceGetBoardIdCalls()) +func (mock *Interface) DeviceGetBoardIdCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBoardId.RLock() + calls = mock.calls.DeviceGetBoardId + mock.lockDeviceGetBoardId.RUnlock() + return calls +} + +// DeviceGetBoardPartNumber calls DeviceGetBoardPartNumberFunc. +func (mock *Interface) DeviceGetBoardPartNumber(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetBoardPartNumberFunc == nil { + panic("Interface.DeviceGetBoardPartNumberFunc: method is nil but Interface.DeviceGetBoardPartNumber was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBoardPartNumber.Lock() + mock.calls.DeviceGetBoardPartNumber = append(mock.calls.DeviceGetBoardPartNumber, callInfo) + mock.lockDeviceGetBoardPartNumber.Unlock() + return mock.DeviceGetBoardPartNumberFunc(device) +} + +// DeviceGetBoardPartNumberCalls gets all the calls that were made to DeviceGetBoardPartNumber. +// Check the length with: +// +// len(mockedInterface.DeviceGetBoardPartNumberCalls()) +func (mock *Interface) DeviceGetBoardPartNumberCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBoardPartNumber.RLock() + calls = mock.calls.DeviceGetBoardPartNumber + mock.lockDeviceGetBoardPartNumber.RUnlock() + return calls +} + +// DeviceGetBrand calls DeviceGetBrandFunc. +func (mock *Interface) DeviceGetBrand(device nvml.Device) (nvml.BrandType, nvml.Return) { + if mock.DeviceGetBrandFunc == nil { + panic("Interface.DeviceGetBrandFunc: method is nil but Interface.DeviceGetBrand was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBrand.Lock() + mock.calls.DeviceGetBrand = append(mock.calls.DeviceGetBrand, callInfo) + mock.lockDeviceGetBrand.Unlock() + return mock.DeviceGetBrandFunc(device) +} + +// DeviceGetBrandCalls gets all the calls that were made to DeviceGetBrand. +// Check the length with: +// +// len(mockedInterface.DeviceGetBrandCalls()) +func (mock *Interface) DeviceGetBrandCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBrand.RLock() + calls = mock.calls.DeviceGetBrand + mock.lockDeviceGetBrand.RUnlock() + return calls +} + +// DeviceGetBridgeChipInfo calls DeviceGetBridgeChipInfoFunc. +func (mock *Interface) DeviceGetBridgeChipInfo(device nvml.Device) (nvml.BridgeChipHierarchy, nvml.Return) { + if mock.DeviceGetBridgeChipInfoFunc == nil { + panic("Interface.DeviceGetBridgeChipInfoFunc: method is nil but Interface.DeviceGetBridgeChipInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBridgeChipInfo.Lock() + mock.calls.DeviceGetBridgeChipInfo = append(mock.calls.DeviceGetBridgeChipInfo, callInfo) + mock.lockDeviceGetBridgeChipInfo.Unlock() + return mock.DeviceGetBridgeChipInfoFunc(device) +} + +// DeviceGetBridgeChipInfoCalls gets all the calls that were made to DeviceGetBridgeChipInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetBridgeChipInfoCalls()) +func (mock *Interface) DeviceGetBridgeChipInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBridgeChipInfo.RLock() + calls = mock.calls.DeviceGetBridgeChipInfo + mock.lockDeviceGetBridgeChipInfo.RUnlock() + return calls +} + +// DeviceGetBusType calls DeviceGetBusTypeFunc. +func (mock *Interface) DeviceGetBusType(device nvml.Device) (nvml.BusType, nvml.Return) { + if mock.DeviceGetBusTypeFunc == nil { + panic("Interface.DeviceGetBusTypeFunc: method is nil but Interface.DeviceGetBusType was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetBusType.Lock() + mock.calls.DeviceGetBusType = append(mock.calls.DeviceGetBusType, callInfo) + mock.lockDeviceGetBusType.Unlock() + return mock.DeviceGetBusTypeFunc(device) +} + +// DeviceGetBusTypeCalls gets all the calls that were made to DeviceGetBusType. +// Check the length with: +// +// len(mockedInterface.DeviceGetBusTypeCalls()) +func (mock *Interface) DeviceGetBusTypeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetBusType.RLock() + calls = mock.calls.DeviceGetBusType + mock.lockDeviceGetBusType.RUnlock() + return calls +} + +// DeviceGetC2cModeInfoV calls DeviceGetC2cModeInfoVFunc. +func (mock *Interface) DeviceGetC2cModeInfoV(device nvml.Device) nvml.C2cModeInfoHandler { + if mock.DeviceGetC2cModeInfoVFunc == nil { + panic("Interface.DeviceGetC2cModeInfoVFunc: method is nil but Interface.DeviceGetC2cModeInfoV was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetC2cModeInfoV.Lock() + mock.calls.DeviceGetC2cModeInfoV = append(mock.calls.DeviceGetC2cModeInfoV, callInfo) + mock.lockDeviceGetC2cModeInfoV.Unlock() + return mock.DeviceGetC2cModeInfoVFunc(device) +} + +// DeviceGetC2cModeInfoVCalls gets all the calls that were made to DeviceGetC2cModeInfoV. +// Check the length with: +// +// len(mockedInterface.DeviceGetC2cModeInfoVCalls()) +func (mock *Interface) DeviceGetC2cModeInfoVCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetC2cModeInfoV.RLock() + calls = mock.calls.DeviceGetC2cModeInfoV + mock.lockDeviceGetC2cModeInfoV.RUnlock() + return calls +} + +// DeviceGetCapabilities calls DeviceGetCapabilitiesFunc. +func (mock *Interface) DeviceGetCapabilities(device nvml.Device) (nvml.DeviceCapabilities, nvml.Return) { + if mock.DeviceGetCapabilitiesFunc == nil { + panic("Interface.DeviceGetCapabilitiesFunc: method is nil but Interface.DeviceGetCapabilities was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCapabilities.Lock() + mock.calls.DeviceGetCapabilities = append(mock.calls.DeviceGetCapabilities, callInfo) + mock.lockDeviceGetCapabilities.Unlock() + return mock.DeviceGetCapabilitiesFunc(device) +} + +// DeviceGetCapabilitiesCalls gets all the calls that were made to DeviceGetCapabilities. +// Check the length with: +// +// len(mockedInterface.DeviceGetCapabilitiesCalls()) +func (mock *Interface) DeviceGetCapabilitiesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCapabilities.RLock() + calls = mock.calls.DeviceGetCapabilities + mock.lockDeviceGetCapabilities.RUnlock() + return calls +} + +// DeviceGetClkMonStatus calls DeviceGetClkMonStatusFunc. +func (mock *Interface) DeviceGetClkMonStatus(device nvml.Device) (nvml.ClkMonStatus, nvml.Return) { + if mock.DeviceGetClkMonStatusFunc == nil { + panic("Interface.DeviceGetClkMonStatusFunc: method is nil but Interface.DeviceGetClkMonStatus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetClkMonStatus.Lock() + mock.calls.DeviceGetClkMonStatus = append(mock.calls.DeviceGetClkMonStatus, callInfo) + mock.lockDeviceGetClkMonStatus.Unlock() + return mock.DeviceGetClkMonStatusFunc(device) +} + +// DeviceGetClkMonStatusCalls gets all the calls that were made to DeviceGetClkMonStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetClkMonStatusCalls()) +func (mock *Interface) DeviceGetClkMonStatusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetClkMonStatus.RLock() + calls = mock.calls.DeviceGetClkMonStatus + mock.lockDeviceGetClkMonStatus.RUnlock() + return calls +} + +// DeviceGetClock calls DeviceGetClockFunc. +func (mock *Interface) DeviceGetClock(device nvml.Device, clockType nvml.ClockType, clockId nvml.ClockId) (uint32, nvml.Return) { + if mock.DeviceGetClockFunc == nil { + panic("Interface.DeviceGetClockFunc: method is nil but Interface.DeviceGetClock was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + ClockId nvml.ClockId + }{ + Device: device, + ClockType: clockType, + ClockId: clockId, + } + mock.lockDeviceGetClock.Lock() + mock.calls.DeviceGetClock = append(mock.calls.DeviceGetClock, callInfo) + mock.lockDeviceGetClock.Unlock() + return mock.DeviceGetClockFunc(device, clockType, clockId) +} + +// DeviceGetClockCalls gets all the calls that were made to DeviceGetClock. +// Check the length with: +// +// len(mockedInterface.DeviceGetClockCalls()) +func (mock *Interface) DeviceGetClockCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType + ClockId nvml.ClockId +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + ClockId nvml.ClockId + } + mock.lockDeviceGetClock.RLock() + calls = mock.calls.DeviceGetClock + mock.lockDeviceGetClock.RUnlock() + return calls +} + +// DeviceGetClockInfo calls DeviceGetClockInfoFunc. +func (mock *Interface) DeviceGetClockInfo(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.DeviceGetClockInfoFunc == nil { + panic("Interface.DeviceGetClockInfoFunc: method is nil but Interface.DeviceGetClockInfo was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + }{ + Device: device, + ClockType: clockType, + } + mock.lockDeviceGetClockInfo.Lock() + mock.calls.DeviceGetClockInfo = append(mock.calls.DeviceGetClockInfo, callInfo) + mock.lockDeviceGetClockInfo.Unlock() + return mock.DeviceGetClockInfoFunc(device, clockType) +} + +// DeviceGetClockInfoCalls gets all the calls that were made to DeviceGetClockInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetClockInfoCalls()) +func (mock *Interface) DeviceGetClockInfoCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + } + mock.lockDeviceGetClockInfo.RLock() + calls = mock.calls.DeviceGetClockInfo + mock.lockDeviceGetClockInfo.RUnlock() + return calls +} + +// DeviceGetClockOffsets calls DeviceGetClockOffsetsFunc. +func (mock *Interface) DeviceGetClockOffsets(device nvml.Device) (nvml.ClockOffset, nvml.Return) { + if mock.DeviceGetClockOffsetsFunc == nil { + panic("Interface.DeviceGetClockOffsetsFunc: method is nil but Interface.DeviceGetClockOffsets was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetClockOffsets.Lock() + mock.calls.DeviceGetClockOffsets = append(mock.calls.DeviceGetClockOffsets, callInfo) + mock.lockDeviceGetClockOffsets.Unlock() + return mock.DeviceGetClockOffsetsFunc(device) +} + +// DeviceGetClockOffsetsCalls gets all the calls that were made to DeviceGetClockOffsets. +// Check the length with: +// +// len(mockedInterface.DeviceGetClockOffsetsCalls()) +func (mock *Interface) DeviceGetClockOffsetsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetClockOffsets.RLock() + calls = mock.calls.DeviceGetClockOffsets + mock.lockDeviceGetClockOffsets.RUnlock() + return calls +} + +// DeviceGetComputeInstanceId calls DeviceGetComputeInstanceIdFunc. +func (mock *Interface) DeviceGetComputeInstanceId(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetComputeInstanceIdFunc == nil { + panic("Interface.DeviceGetComputeInstanceIdFunc: method is nil but Interface.DeviceGetComputeInstanceId was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetComputeInstanceId.Lock() + mock.calls.DeviceGetComputeInstanceId = append(mock.calls.DeviceGetComputeInstanceId, callInfo) + mock.lockDeviceGetComputeInstanceId.Unlock() + return mock.DeviceGetComputeInstanceIdFunc(device) +} + +// DeviceGetComputeInstanceIdCalls gets all the calls that were made to DeviceGetComputeInstanceId. +// Check the length with: +// +// len(mockedInterface.DeviceGetComputeInstanceIdCalls()) +func (mock *Interface) DeviceGetComputeInstanceIdCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetComputeInstanceId.RLock() + calls = mock.calls.DeviceGetComputeInstanceId + mock.lockDeviceGetComputeInstanceId.RUnlock() + return calls +} + +// DeviceGetComputeMode calls DeviceGetComputeModeFunc. +func (mock *Interface) DeviceGetComputeMode(device nvml.Device) (nvml.ComputeMode, nvml.Return) { + if mock.DeviceGetComputeModeFunc == nil { + panic("Interface.DeviceGetComputeModeFunc: method is nil but Interface.DeviceGetComputeMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetComputeMode.Lock() + mock.calls.DeviceGetComputeMode = append(mock.calls.DeviceGetComputeMode, callInfo) + mock.lockDeviceGetComputeMode.Unlock() + return mock.DeviceGetComputeModeFunc(device) +} + +// DeviceGetComputeModeCalls gets all the calls that were made to DeviceGetComputeMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetComputeModeCalls()) +func (mock *Interface) DeviceGetComputeModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetComputeMode.RLock() + calls = mock.calls.DeviceGetComputeMode + mock.lockDeviceGetComputeMode.RUnlock() + return calls +} + +// DeviceGetComputeRunningProcesses calls DeviceGetComputeRunningProcessesFunc. +func (mock *Interface) DeviceGetComputeRunningProcesses(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { + if mock.DeviceGetComputeRunningProcessesFunc == nil { + panic("Interface.DeviceGetComputeRunningProcessesFunc: method is nil but Interface.DeviceGetComputeRunningProcesses was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetComputeRunningProcesses.Lock() + mock.calls.DeviceGetComputeRunningProcesses = append(mock.calls.DeviceGetComputeRunningProcesses, callInfo) + mock.lockDeviceGetComputeRunningProcesses.Unlock() + return mock.DeviceGetComputeRunningProcessesFunc(device) +} + +// DeviceGetComputeRunningProcessesCalls gets all the calls that were made to DeviceGetComputeRunningProcesses. +// Check the length with: +// +// len(mockedInterface.DeviceGetComputeRunningProcessesCalls()) +func (mock *Interface) DeviceGetComputeRunningProcessesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetComputeRunningProcesses.RLock() + calls = mock.calls.DeviceGetComputeRunningProcesses + mock.lockDeviceGetComputeRunningProcesses.RUnlock() + return calls +} + +// DeviceGetConfComputeGpuAttestationReport calls DeviceGetConfComputeGpuAttestationReportFunc. +func (mock *Interface) DeviceGetConfComputeGpuAttestationReport(device nvml.Device, confComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport) nvml.Return { + if mock.DeviceGetConfComputeGpuAttestationReportFunc == nil { + panic("Interface.DeviceGetConfComputeGpuAttestationReportFunc: method is nil but Interface.DeviceGetConfComputeGpuAttestationReport was just called") + } + callInfo := struct { + Device nvml.Device + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + }{ + Device: device, + ConfComputeGpuAttestationReport: confComputeGpuAttestationReport, + } + mock.lockDeviceGetConfComputeGpuAttestationReport.Lock() + mock.calls.DeviceGetConfComputeGpuAttestationReport = append(mock.calls.DeviceGetConfComputeGpuAttestationReport, callInfo) + mock.lockDeviceGetConfComputeGpuAttestationReport.Unlock() + return mock.DeviceGetConfComputeGpuAttestationReportFunc(device, confComputeGpuAttestationReport) +} + +// DeviceGetConfComputeGpuAttestationReportCalls gets all the calls that were made to DeviceGetConfComputeGpuAttestationReport. +// Check the length with: +// +// len(mockedInterface.DeviceGetConfComputeGpuAttestationReportCalls()) +func (mock *Interface) DeviceGetConfComputeGpuAttestationReportCalls() []struct { + Device nvml.Device + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport +} { + var calls []struct { + Device nvml.Device + ConfComputeGpuAttestationReport *nvml.ConfComputeGpuAttestationReport + } + mock.lockDeviceGetConfComputeGpuAttestationReport.RLock() + calls = mock.calls.DeviceGetConfComputeGpuAttestationReport + mock.lockDeviceGetConfComputeGpuAttestationReport.RUnlock() + return calls +} + +// DeviceGetConfComputeGpuCertificate calls DeviceGetConfComputeGpuCertificateFunc. +func (mock *Interface) DeviceGetConfComputeGpuCertificate(device nvml.Device) (nvml.ConfComputeGpuCertificate, nvml.Return) { + if mock.DeviceGetConfComputeGpuCertificateFunc == nil { + panic("Interface.DeviceGetConfComputeGpuCertificateFunc: method is nil but Interface.DeviceGetConfComputeGpuCertificate was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetConfComputeGpuCertificate.Lock() + mock.calls.DeviceGetConfComputeGpuCertificate = append(mock.calls.DeviceGetConfComputeGpuCertificate, callInfo) + mock.lockDeviceGetConfComputeGpuCertificate.Unlock() + return mock.DeviceGetConfComputeGpuCertificateFunc(device) +} + +// DeviceGetConfComputeGpuCertificateCalls gets all the calls that were made to DeviceGetConfComputeGpuCertificate. +// Check the length with: +// +// len(mockedInterface.DeviceGetConfComputeGpuCertificateCalls()) +func (mock *Interface) DeviceGetConfComputeGpuCertificateCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetConfComputeGpuCertificate.RLock() + calls = mock.calls.DeviceGetConfComputeGpuCertificate + mock.lockDeviceGetConfComputeGpuCertificate.RUnlock() + return calls +} + +// DeviceGetConfComputeMemSizeInfo calls DeviceGetConfComputeMemSizeInfoFunc. +func (mock *Interface) DeviceGetConfComputeMemSizeInfo(device nvml.Device) (nvml.ConfComputeMemSizeInfo, nvml.Return) { + if mock.DeviceGetConfComputeMemSizeInfoFunc == nil { + panic("Interface.DeviceGetConfComputeMemSizeInfoFunc: method is nil but Interface.DeviceGetConfComputeMemSizeInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetConfComputeMemSizeInfo.Lock() + mock.calls.DeviceGetConfComputeMemSizeInfo = append(mock.calls.DeviceGetConfComputeMemSizeInfo, callInfo) + mock.lockDeviceGetConfComputeMemSizeInfo.Unlock() + return mock.DeviceGetConfComputeMemSizeInfoFunc(device) +} + +// DeviceGetConfComputeMemSizeInfoCalls gets all the calls that were made to DeviceGetConfComputeMemSizeInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetConfComputeMemSizeInfoCalls()) +func (mock *Interface) DeviceGetConfComputeMemSizeInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetConfComputeMemSizeInfo.RLock() + calls = mock.calls.DeviceGetConfComputeMemSizeInfo + mock.lockDeviceGetConfComputeMemSizeInfo.RUnlock() + return calls +} + +// DeviceGetConfComputeProtectedMemoryUsage calls DeviceGetConfComputeProtectedMemoryUsageFunc. +func (mock *Interface) DeviceGetConfComputeProtectedMemoryUsage(device nvml.Device) (nvml.Memory, nvml.Return) { + if mock.DeviceGetConfComputeProtectedMemoryUsageFunc == nil { + panic("Interface.DeviceGetConfComputeProtectedMemoryUsageFunc: method is nil but Interface.DeviceGetConfComputeProtectedMemoryUsage was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetConfComputeProtectedMemoryUsage.Lock() + mock.calls.DeviceGetConfComputeProtectedMemoryUsage = append(mock.calls.DeviceGetConfComputeProtectedMemoryUsage, callInfo) + mock.lockDeviceGetConfComputeProtectedMemoryUsage.Unlock() + return mock.DeviceGetConfComputeProtectedMemoryUsageFunc(device) +} + +// DeviceGetConfComputeProtectedMemoryUsageCalls gets all the calls that were made to DeviceGetConfComputeProtectedMemoryUsage. +// Check the length with: +// +// len(mockedInterface.DeviceGetConfComputeProtectedMemoryUsageCalls()) +func (mock *Interface) DeviceGetConfComputeProtectedMemoryUsageCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetConfComputeProtectedMemoryUsage.RLock() + calls = mock.calls.DeviceGetConfComputeProtectedMemoryUsage + mock.lockDeviceGetConfComputeProtectedMemoryUsage.RUnlock() + return calls +} + +// DeviceGetCoolerInfo calls DeviceGetCoolerInfoFunc. +func (mock *Interface) DeviceGetCoolerInfo(device nvml.Device) (nvml.CoolerInfo, nvml.Return) { + if mock.DeviceGetCoolerInfoFunc == nil { + panic("Interface.DeviceGetCoolerInfoFunc: method is nil but Interface.DeviceGetCoolerInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCoolerInfo.Lock() + mock.calls.DeviceGetCoolerInfo = append(mock.calls.DeviceGetCoolerInfo, callInfo) + mock.lockDeviceGetCoolerInfo.Unlock() + return mock.DeviceGetCoolerInfoFunc(device) +} + +// DeviceGetCoolerInfoCalls gets all the calls that were made to DeviceGetCoolerInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetCoolerInfoCalls()) +func (mock *Interface) DeviceGetCoolerInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCoolerInfo.RLock() + calls = mock.calls.DeviceGetCoolerInfo + mock.lockDeviceGetCoolerInfo.RUnlock() + return calls +} + +// DeviceGetCount calls DeviceGetCountFunc. +func (mock *Interface) DeviceGetCount() (int, nvml.Return) { + if mock.DeviceGetCountFunc == nil { + panic("Interface.DeviceGetCountFunc: method is nil but Interface.DeviceGetCount was just called") + } + callInfo := struct { + }{} + mock.lockDeviceGetCount.Lock() + mock.calls.DeviceGetCount = append(mock.calls.DeviceGetCount, callInfo) + mock.lockDeviceGetCount.Unlock() + return mock.DeviceGetCountFunc() +} + +// DeviceGetCountCalls gets all the calls that were made to DeviceGetCount. +// Check the length with: +// +// len(mockedInterface.DeviceGetCountCalls()) +func (mock *Interface) DeviceGetCountCalls() []struct { +} { + var calls []struct { + } + mock.lockDeviceGetCount.RLock() + calls = mock.calls.DeviceGetCount + mock.lockDeviceGetCount.RUnlock() + return calls +} + +// DeviceGetCpuAffinity calls DeviceGetCpuAffinityFunc. +func (mock *Interface) DeviceGetCpuAffinity(device nvml.Device, n int) ([]uint, nvml.Return) { + if mock.DeviceGetCpuAffinityFunc == nil { + panic("Interface.DeviceGetCpuAffinityFunc: method is nil but Interface.DeviceGetCpuAffinity was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetCpuAffinity.Lock() + mock.calls.DeviceGetCpuAffinity = append(mock.calls.DeviceGetCpuAffinity, callInfo) + mock.lockDeviceGetCpuAffinity.Unlock() + return mock.DeviceGetCpuAffinityFunc(device, n) +} + +// DeviceGetCpuAffinityCalls gets all the calls that were made to DeviceGetCpuAffinity. +// Check the length with: +// +// len(mockedInterface.DeviceGetCpuAffinityCalls()) +func (mock *Interface) DeviceGetCpuAffinityCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetCpuAffinity.RLock() + calls = mock.calls.DeviceGetCpuAffinity + mock.lockDeviceGetCpuAffinity.RUnlock() + return calls +} + +// DeviceGetCpuAffinityWithinScope calls DeviceGetCpuAffinityWithinScopeFunc. +func (mock *Interface) DeviceGetCpuAffinityWithinScope(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { + if mock.DeviceGetCpuAffinityWithinScopeFunc == nil { + panic("Interface.DeviceGetCpuAffinityWithinScopeFunc: method is nil but Interface.DeviceGetCpuAffinityWithinScope was just called") + } + callInfo := struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope + }{ + Device: device, + N: n, + AffinityScope: affinityScope, + } + mock.lockDeviceGetCpuAffinityWithinScope.Lock() + mock.calls.DeviceGetCpuAffinityWithinScope = append(mock.calls.DeviceGetCpuAffinityWithinScope, callInfo) + mock.lockDeviceGetCpuAffinityWithinScope.Unlock() + return mock.DeviceGetCpuAffinityWithinScopeFunc(device, n, affinityScope) +} + +// DeviceGetCpuAffinityWithinScopeCalls gets all the calls that were made to DeviceGetCpuAffinityWithinScope. +// Check the length with: +// +// len(mockedInterface.DeviceGetCpuAffinityWithinScopeCalls()) +func (mock *Interface) DeviceGetCpuAffinityWithinScopeCalls() []struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope +} { + var calls []struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope + } + mock.lockDeviceGetCpuAffinityWithinScope.RLock() + calls = mock.calls.DeviceGetCpuAffinityWithinScope + mock.lockDeviceGetCpuAffinityWithinScope.RUnlock() + return calls +} + +// DeviceGetCreatableVgpus calls DeviceGetCreatableVgpusFunc. +func (mock *Interface) DeviceGetCreatableVgpus(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) { + if mock.DeviceGetCreatableVgpusFunc == nil { + panic("Interface.DeviceGetCreatableVgpusFunc: method is nil but Interface.DeviceGetCreatableVgpus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCreatableVgpus.Lock() + mock.calls.DeviceGetCreatableVgpus = append(mock.calls.DeviceGetCreatableVgpus, callInfo) + mock.lockDeviceGetCreatableVgpus.Unlock() + return mock.DeviceGetCreatableVgpusFunc(device) +} + +// DeviceGetCreatableVgpusCalls gets all the calls that were made to DeviceGetCreatableVgpus. +// Check the length with: +// +// len(mockedInterface.DeviceGetCreatableVgpusCalls()) +func (mock *Interface) DeviceGetCreatableVgpusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCreatableVgpus.RLock() + calls = mock.calls.DeviceGetCreatableVgpus + mock.lockDeviceGetCreatableVgpus.RUnlock() + return calls +} + +// DeviceGetCudaComputeCapability calls DeviceGetCudaComputeCapabilityFunc. +func (mock *Interface) DeviceGetCudaComputeCapability(device nvml.Device) (int, int, nvml.Return) { + if mock.DeviceGetCudaComputeCapabilityFunc == nil { + panic("Interface.DeviceGetCudaComputeCapabilityFunc: method is nil but Interface.DeviceGetCudaComputeCapability was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCudaComputeCapability.Lock() + mock.calls.DeviceGetCudaComputeCapability = append(mock.calls.DeviceGetCudaComputeCapability, callInfo) + mock.lockDeviceGetCudaComputeCapability.Unlock() + return mock.DeviceGetCudaComputeCapabilityFunc(device) +} + +// DeviceGetCudaComputeCapabilityCalls gets all the calls that were made to DeviceGetCudaComputeCapability. +// Check the length with: +// +// len(mockedInterface.DeviceGetCudaComputeCapabilityCalls()) +func (mock *Interface) DeviceGetCudaComputeCapabilityCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCudaComputeCapability.RLock() + calls = mock.calls.DeviceGetCudaComputeCapability + mock.lockDeviceGetCudaComputeCapability.RUnlock() + return calls +} + +// DeviceGetCurrPcieLinkGeneration calls DeviceGetCurrPcieLinkGenerationFunc. +func (mock *Interface) DeviceGetCurrPcieLinkGeneration(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetCurrPcieLinkGenerationFunc == nil { + panic("Interface.DeviceGetCurrPcieLinkGenerationFunc: method is nil but Interface.DeviceGetCurrPcieLinkGeneration was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCurrPcieLinkGeneration.Lock() + mock.calls.DeviceGetCurrPcieLinkGeneration = append(mock.calls.DeviceGetCurrPcieLinkGeneration, callInfo) + mock.lockDeviceGetCurrPcieLinkGeneration.Unlock() + return mock.DeviceGetCurrPcieLinkGenerationFunc(device) +} + +// DeviceGetCurrPcieLinkGenerationCalls gets all the calls that were made to DeviceGetCurrPcieLinkGeneration. +// Check the length with: +// +// len(mockedInterface.DeviceGetCurrPcieLinkGenerationCalls()) +func (mock *Interface) DeviceGetCurrPcieLinkGenerationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCurrPcieLinkGeneration.RLock() + calls = mock.calls.DeviceGetCurrPcieLinkGeneration + mock.lockDeviceGetCurrPcieLinkGeneration.RUnlock() + return calls +} + +// DeviceGetCurrPcieLinkWidth calls DeviceGetCurrPcieLinkWidthFunc. +func (mock *Interface) DeviceGetCurrPcieLinkWidth(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetCurrPcieLinkWidthFunc == nil { + panic("Interface.DeviceGetCurrPcieLinkWidthFunc: method is nil but Interface.DeviceGetCurrPcieLinkWidth was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCurrPcieLinkWidth.Lock() + mock.calls.DeviceGetCurrPcieLinkWidth = append(mock.calls.DeviceGetCurrPcieLinkWidth, callInfo) + mock.lockDeviceGetCurrPcieLinkWidth.Unlock() + return mock.DeviceGetCurrPcieLinkWidthFunc(device) +} + +// DeviceGetCurrPcieLinkWidthCalls gets all the calls that were made to DeviceGetCurrPcieLinkWidth. +// Check the length with: +// +// len(mockedInterface.DeviceGetCurrPcieLinkWidthCalls()) +func (mock *Interface) DeviceGetCurrPcieLinkWidthCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCurrPcieLinkWidth.RLock() + calls = mock.calls.DeviceGetCurrPcieLinkWidth + mock.lockDeviceGetCurrPcieLinkWidth.RUnlock() + return calls +} + +// DeviceGetCurrentClockFreqs calls DeviceGetCurrentClockFreqsFunc. +func (mock *Interface) DeviceGetCurrentClockFreqs(device nvml.Device) (nvml.DeviceCurrentClockFreqs, nvml.Return) { + if mock.DeviceGetCurrentClockFreqsFunc == nil { + panic("Interface.DeviceGetCurrentClockFreqsFunc: method is nil but Interface.DeviceGetCurrentClockFreqs was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCurrentClockFreqs.Lock() + mock.calls.DeviceGetCurrentClockFreqs = append(mock.calls.DeviceGetCurrentClockFreqs, callInfo) + mock.lockDeviceGetCurrentClockFreqs.Unlock() + return mock.DeviceGetCurrentClockFreqsFunc(device) +} + +// DeviceGetCurrentClockFreqsCalls gets all the calls that were made to DeviceGetCurrentClockFreqs. +// Check the length with: +// +// len(mockedInterface.DeviceGetCurrentClockFreqsCalls()) +func (mock *Interface) DeviceGetCurrentClockFreqsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCurrentClockFreqs.RLock() + calls = mock.calls.DeviceGetCurrentClockFreqs + mock.lockDeviceGetCurrentClockFreqs.RUnlock() + return calls +} + +// DeviceGetCurrentClocksEventReasons calls DeviceGetCurrentClocksEventReasonsFunc. +func (mock *Interface) DeviceGetCurrentClocksEventReasons(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetCurrentClocksEventReasonsFunc == nil { + panic("Interface.DeviceGetCurrentClocksEventReasonsFunc: method is nil but Interface.DeviceGetCurrentClocksEventReasons was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCurrentClocksEventReasons.Lock() + mock.calls.DeviceGetCurrentClocksEventReasons = append(mock.calls.DeviceGetCurrentClocksEventReasons, callInfo) + mock.lockDeviceGetCurrentClocksEventReasons.Unlock() + return mock.DeviceGetCurrentClocksEventReasonsFunc(device) +} + +// DeviceGetCurrentClocksEventReasonsCalls gets all the calls that were made to DeviceGetCurrentClocksEventReasons. +// Check the length with: +// +// len(mockedInterface.DeviceGetCurrentClocksEventReasonsCalls()) +func (mock *Interface) DeviceGetCurrentClocksEventReasonsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCurrentClocksEventReasons.RLock() + calls = mock.calls.DeviceGetCurrentClocksEventReasons + mock.lockDeviceGetCurrentClocksEventReasons.RUnlock() + return calls +} + +// DeviceGetCurrentClocksThrottleReasons calls DeviceGetCurrentClocksThrottleReasonsFunc. +func (mock *Interface) DeviceGetCurrentClocksThrottleReasons(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetCurrentClocksThrottleReasonsFunc == nil { + panic("Interface.DeviceGetCurrentClocksThrottleReasonsFunc: method is nil but Interface.DeviceGetCurrentClocksThrottleReasons was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetCurrentClocksThrottleReasons.Lock() + mock.calls.DeviceGetCurrentClocksThrottleReasons = append(mock.calls.DeviceGetCurrentClocksThrottleReasons, callInfo) + mock.lockDeviceGetCurrentClocksThrottleReasons.Unlock() + return mock.DeviceGetCurrentClocksThrottleReasonsFunc(device) +} + +// DeviceGetCurrentClocksThrottleReasonsCalls gets all the calls that were made to DeviceGetCurrentClocksThrottleReasons. +// Check the length with: +// +// len(mockedInterface.DeviceGetCurrentClocksThrottleReasonsCalls()) +func (mock *Interface) DeviceGetCurrentClocksThrottleReasonsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetCurrentClocksThrottleReasons.RLock() + calls = mock.calls.DeviceGetCurrentClocksThrottleReasons + mock.lockDeviceGetCurrentClocksThrottleReasons.RUnlock() + return calls +} + +// DeviceGetDecoderUtilization calls DeviceGetDecoderUtilizationFunc. +func (mock *Interface) DeviceGetDecoderUtilization(device nvml.Device) (uint32, uint32, nvml.Return) { + if mock.DeviceGetDecoderUtilizationFunc == nil { + panic("Interface.DeviceGetDecoderUtilizationFunc: method is nil but Interface.DeviceGetDecoderUtilization was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDecoderUtilization.Lock() + mock.calls.DeviceGetDecoderUtilization = append(mock.calls.DeviceGetDecoderUtilization, callInfo) + mock.lockDeviceGetDecoderUtilization.Unlock() + return mock.DeviceGetDecoderUtilizationFunc(device) +} + +// DeviceGetDecoderUtilizationCalls gets all the calls that were made to DeviceGetDecoderUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetDecoderUtilizationCalls()) +func (mock *Interface) DeviceGetDecoderUtilizationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDecoderUtilization.RLock() + calls = mock.calls.DeviceGetDecoderUtilization + mock.lockDeviceGetDecoderUtilization.RUnlock() + return calls +} + +// DeviceGetDefaultApplicationsClock calls DeviceGetDefaultApplicationsClockFunc. +func (mock *Interface) DeviceGetDefaultApplicationsClock(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.DeviceGetDefaultApplicationsClockFunc == nil { + panic("Interface.DeviceGetDefaultApplicationsClockFunc: method is nil but Interface.DeviceGetDefaultApplicationsClock was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + }{ + Device: device, + ClockType: clockType, + } + mock.lockDeviceGetDefaultApplicationsClock.Lock() + mock.calls.DeviceGetDefaultApplicationsClock = append(mock.calls.DeviceGetDefaultApplicationsClock, callInfo) + mock.lockDeviceGetDefaultApplicationsClock.Unlock() + return mock.DeviceGetDefaultApplicationsClockFunc(device, clockType) +} + +// DeviceGetDefaultApplicationsClockCalls gets all the calls that were made to DeviceGetDefaultApplicationsClock. +// Check the length with: +// +// len(mockedInterface.DeviceGetDefaultApplicationsClockCalls()) +func (mock *Interface) DeviceGetDefaultApplicationsClockCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + } + mock.lockDeviceGetDefaultApplicationsClock.RLock() + calls = mock.calls.DeviceGetDefaultApplicationsClock + mock.lockDeviceGetDefaultApplicationsClock.RUnlock() + return calls +} + +// DeviceGetDefaultEccMode calls DeviceGetDefaultEccModeFunc. +func (mock *Interface) DeviceGetDefaultEccMode(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetDefaultEccModeFunc == nil { + panic("Interface.DeviceGetDefaultEccModeFunc: method is nil but Interface.DeviceGetDefaultEccMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDefaultEccMode.Lock() + mock.calls.DeviceGetDefaultEccMode = append(mock.calls.DeviceGetDefaultEccMode, callInfo) + mock.lockDeviceGetDefaultEccMode.Unlock() + return mock.DeviceGetDefaultEccModeFunc(device) +} + +// DeviceGetDefaultEccModeCalls gets all the calls that were made to DeviceGetDefaultEccMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetDefaultEccModeCalls()) +func (mock *Interface) DeviceGetDefaultEccModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDefaultEccMode.RLock() + calls = mock.calls.DeviceGetDefaultEccMode + mock.lockDeviceGetDefaultEccMode.RUnlock() + return calls +} + +// DeviceGetDetailedEccErrors calls DeviceGetDetailedEccErrorsFunc. +func (mock *Interface) DeviceGetDetailedEccErrors(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (nvml.EccErrorCounts, nvml.Return) { + if mock.DeviceGetDetailedEccErrorsFunc == nil { + panic("Interface.DeviceGetDetailedEccErrorsFunc: method is nil but Interface.DeviceGetDetailedEccErrors was just called") + } + callInfo := struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + }{ + Device: device, + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + } + mock.lockDeviceGetDetailedEccErrors.Lock() + mock.calls.DeviceGetDetailedEccErrors = append(mock.calls.DeviceGetDetailedEccErrors, callInfo) + mock.lockDeviceGetDetailedEccErrors.Unlock() + return mock.DeviceGetDetailedEccErrorsFunc(device, memoryErrorType, eccCounterType) +} + +// DeviceGetDetailedEccErrorsCalls gets all the calls that were made to DeviceGetDetailedEccErrors. +// Check the length with: +// +// len(mockedInterface.DeviceGetDetailedEccErrorsCalls()) +func (mock *Interface) DeviceGetDetailedEccErrorsCalls() []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType +} { + var calls []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + } + mock.lockDeviceGetDetailedEccErrors.RLock() + calls = mock.calls.DeviceGetDetailedEccErrors + mock.lockDeviceGetDetailedEccErrors.RUnlock() + return calls +} + +// DeviceGetDeviceHandleFromMigDeviceHandle calls DeviceGetDeviceHandleFromMigDeviceHandleFunc. +func (mock *Interface) DeviceGetDeviceHandleFromMigDeviceHandle(device nvml.Device) (nvml.Device, nvml.Return) { + if mock.DeviceGetDeviceHandleFromMigDeviceHandleFunc == nil { + panic("Interface.DeviceGetDeviceHandleFromMigDeviceHandleFunc: method is nil but Interface.DeviceGetDeviceHandleFromMigDeviceHandle was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDeviceHandleFromMigDeviceHandle.Lock() + mock.calls.DeviceGetDeviceHandleFromMigDeviceHandle = append(mock.calls.DeviceGetDeviceHandleFromMigDeviceHandle, callInfo) + mock.lockDeviceGetDeviceHandleFromMigDeviceHandle.Unlock() + return mock.DeviceGetDeviceHandleFromMigDeviceHandleFunc(device) +} + +// DeviceGetDeviceHandleFromMigDeviceHandleCalls gets all the calls that were made to DeviceGetDeviceHandleFromMigDeviceHandle. +// Check the length with: +// +// len(mockedInterface.DeviceGetDeviceHandleFromMigDeviceHandleCalls()) +func (mock *Interface) DeviceGetDeviceHandleFromMigDeviceHandleCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDeviceHandleFromMigDeviceHandle.RLock() + calls = mock.calls.DeviceGetDeviceHandleFromMigDeviceHandle + mock.lockDeviceGetDeviceHandleFromMigDeviceHandle.RUnlock() + return calls +} + +// DeviceGetDisplayActive calls DeviceGetDisplayActiveFunc. +func (mock *Interface) DeviceGetDisplayActive(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetDisplayActiveFunc == nil { + panic("Interface.DeviceGetDisplayActiveFunc: method is nil but Interface.DeviceGetDisplayActive was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDisplayActive.Lock() + mock.calls.DeviceGetDisplayActive = append(mock.calls.DeviceGetDisplayActive, callInfo) + mock.lockDeviceGetDisplayActive.Unlock() + return mock.DeviceGetDisplayActiveFunc(device) +} + +// DeviceGetDisplayActiveCalls gets all the calls that were made to DeviceGetDisplayActive. +// Check the length with: +// +// len(mockedInterface.DeviceGetDisplayActiveCalls()) +func (mock *Interface) DeviceGetDisplayActiveCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDisplayActive.RLock() + calls = mock.calls.DeviceGetDisplayActive + mock.lockDeviceGetDisplayActive.RUnlock() + return calls +} + +// DeviceGetDisplayMode calls DeviceGetDisplayModeFunc. +func (mock *Interface) DeviceGetDisplayMode(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetDisplayModeFunc == nil { + panic("Interface.DeviceGetDisplayModeFunc: method is nil but Interface.DeviceGetDisplayMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDisplayMode.Lock() + mock.calls.DeviceGetDisplayMode = append(mock.calls.DeviceGetDisplayMode, callInfo) + mock.lockDeviceGetDisplayMode.Unlock() + return mock.DeviceGetDisplayModeFunc(device) +} + +// DeviceGetDisplayModeCalls gets all the calls that were made to DeviceGetDisplayMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetDisplayModeCalls()) +func (mock *Interface) DeviceGetDisplayModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDisplayMode.RLock() + calls = mock.calls.DeviceGetDisplayMode + mock.lockDeviceGetDisplayMode.RUnlock() + return calls +} + +// DeviceGetDramEncryptionMode calls DeviceGetDramEncryptionModeFunc. +func (mock *Interface) DeviceGetDramEncryptionMode(device nvml.Device) (nvml.DramEncryptionInfo, nvml.DramEncryptionInfo, nvml.Return) { + if mock.DeviceGetDramEncryptionModeFunc == nil { + panic("Interface.DeviceGetDramEncryptionModeFunc: method is nil but Interface.DeviceGetDramEncryptionMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDramEncryptionMode.Lock() + mock.calls.DeviceGetDramEncryptionMode = append(mock.calls.DeviceGetDramEncryptionMode, callInfo) + mock.lockDeviceGetDramEncryptionMode.Unlock() + return mock.DeviceGetDramEncryptionModeFunc(device) +} + +// DeviceGetDramEncryptionModeCalls gets all the calls that were made to DeviceGetDramEncryptionMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetDramEncryptionModeCalls()) +func (mock *Interface) DeviceGetDramEncryptionModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDramEncryptionMode.RLock() + calls = mock.calls.DeviceGetDramEncryptionMode + mock.lockDeviceGetDramEncryptionMode.RUnlock() + return calls +} + +// DeviceGetDriverModel calls DeviceGetDriverModelFunc. +func (mock *Interface) DeviceGetDriverModel(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) { + if mock.DeviceGetDriverModelFunc == nil { + panic("Interface.DeviceGetDriverModelFunc: method is nil but Interface.DeviceGetDriverModel was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDriverModel.Lock() + mock.calls.DeviceGetDriverModel = append(mock.calls.DeviceGetDriverModel, callInfo) + mock.lockDeviceGetDriverModel.Unlock() + return mock.DeviceGetDriverModelFunc(device) +} + +// DeviceGetDriverModelCalls gets all the calls that were made to DeviceGetDriverModel. +// Check the length with: +// +// len(mockedInterface.DeviceGetDriverModelCalls()) +func (mock *Interface) DeviceGetDriverModelCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDriverModel.RLock() + calls = mock.calls.DeviceGetDriverModel + mock.lockDeviceGetDriverModel.RUnlock() + return calls +} + +// DeviceGetDriverModel_v2 calls DeviceGetDriverModel_v2Func. +func (mock *Interface) DeviceGetDriverModel_v2(device nvml.Device) (nvml.DriverModel, nvml.DriverModel, nvml.Return) { + if mock.DeviceGetDriverModel_v2Func == nil { + panic("Interface.DeviceGetDriverModel_v2Func: method is nil but Interface.DeviceGetDriverModel_v2 was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDriverModel_v2.Lock() + mock.calls.DeviceGetDriverModel_v2 = append(mock.calls.DeviceGetDriverModel_v2, callInfo) + mock.lockDeviceGetDriverModel_v2.Unlock() + return mock.DeviceGetDriverModel_v2Func(device) +} + +// DeviceGetDriverModel_v2Calls gets all the calls that were made to DeviceGetDriverModel_v2. +// Check the length with: +// +// len(mockedInterface.DeviceGetDriverModel_v2Calls()) +func (mock *Interface) DeviceGetDriverModel_v2Calls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDriverModel_v2.RLock() + calls = mock.calls.DeviceGetDriverModel_v2 + mock.lockDeviceGetDriverModel_v2.RUnlock() + return calls +} + +// DeviceGetDynamicPstatesInfo calls DeviceGetDynamicPstatesInfoFunc. +func (mock *Interface) DeviceGetDynamicPstatesInfo(device nvml.Device) (nvml.GpuDynamicPstatesInfo, nvml.Return) { + if mock.DeviceGetDynamicPstatesInfoFunc == nil { + panic("Interface.DeviceGetDynamicPstatesInfoFunc: method is nil but Interface.DeviceGetDynamicPstatesInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetDynamicPstatesInfo.Lock() + mock.calls.DeviceGetDynamicPstatesInfo = append(mock.calls.DeviceGetDynamicPstatesInfo, callInfo) + mock.lockDeviceGetDynamicPstatesInfo.Unlock() + return mock.DeviceGetDynamicPstatesInfoFunc(device) +} + +// DeviceGetDynamicPstatesInfoCalls gets all the calls that were made to DeviceGetDynamicPstatesInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetDynamicPstatesInfoCalls()) +func (mock *Interface) DeviceGetDynamicPstatesInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetDynamicPstatesInfo.RLock() + calls = mock.calls.DeviceGetDynamicPstatesInfo + mock.lockDeviceGetDynamicPstatesInfo.RUnlock() + return calls +} + +// DeviceGetEccMode calls DeviceGetEccModeFunc. +func (mock *Interface) DeviceGetEccMode(device nvml.Device) (nvml.EnableState, nvml.EnableState, nvml.Return) { + if mock.DeviceGetEccModeFunc == nil { + panic("Interface.DeviceGetEccModeFunc: method is nil but Interface.DeviceGetEccMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetEccMode.Lock() + mock.calls.DeviceGetEccMode = append(mock.calls.DeviceGetEccMode, callInfo) + mock.lockDeviceGetEccMode.Unlock() + return mock.DeviceGetEccModeFunc(device) +} + +// DeviceGetEccModeCalls gets all the calls that were made to DeviceGetEccMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetEccModeCalls()) +func (mock *Interface) DeviceGetEccModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetEccMode.RLock() + calls = mock.calls.DeviceGetEccMode + mock.lockDeviceGetEccMode.RUnlock() + return calls +} + +// DeviceGetEncoderCapacity calls DeviceGetEncoderCapacityFunc. +func (mock *Interface) DeviceGetEncoderCapacity(device nvml.Device, encoderType nvml.EncoderType) (int, nvml.Return) { + if mock.DeviceGetEncoderCapacityFunc == nil { + panic("Interface.DeviceGetEncoderCapacityFunc: method is nil but Interface.DeviceGetEncoderCapacity was just called") + } + callInfo := struct { + Device nvml.Device + EncoderType nvml.EncoderType + }{ + Device: device, + EncoderType: encoderType, + } + mock.lockDeviceGetEncoderCapacity.Lock() + mock.calls.DeviceGetEncoderCapacity = append(mock.calls.DeviceGetEncoderCapacity, callInfo) + mock.lockDeviceGetEncoderCapacity.Unlock() + return mock.DeviceGetEncoderCapacityFunc(device, encoderType) +} + +// DeviceGetEncoderCapacityCalls gets all the calls that were made to DeviceGetEncoderCapacity. +// Check the length with: +// +// len(mockedInterface.DeviceGetEncoderCapacityCalls()) +func (mock *Interface) DeviceGetEncoderCapacityCalls() []struct { + Device nvml.Device + EncoderType nvml.EncoderType +} { + var calls []struct { + Device nvml.Device + EncoderType nvml.EncoderType + } + mock.lockDeviceGetEncoderCapacity.RLock() + calls = mock.calls.DeviceGetEncoderCapacity + mock.lockDeviceGetEncoderCapacity.RUnlock() + return calls +} + +// DeviceGetEncoderSessions calls DeviceGetEncoderSessionsFunc. +func (mock *Interface) DeviceGetEncoderSessions(device nvml.Device) ([]nvml.EncoderSessionInfo, nvml.Return) { + if mock.DeviceGetEncoderSessionsFunc == nil { + panic("Interface.DeviceGetEncoderSessionsFunc: method is nil but Interface.DeviceGetEncoderSessions was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetEncoderSessions.Lock() + mock.calls.DeviceGetEncoderSessions = append(mock.calls.DeviceGetEncoderSessions, callInfo) + mock.lockDeviceGetEncoderSessions.Unlock() + return mock.DeviceGetEncoderSessionsFunc(device) +} + +// DeviceGetEncoderSessionsCalls gets all the calls that were made to DeviceGetEncoderSessions. +// Check the length with: +// +// len(mockedInterface.DeviceGetEncoderSessionsCalls()) +func (mock *Interface) DeviceGetEncoderSessionsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetEncoderSessions.RLock() + calls = mock.calls.DeviceGetEncoderSessions + mock.lockDeviceGetEncoderSessions.RUnlock() + return calls +} + +// DeviceGetEncoderStats calls DeviceGetEncoderStatsFunc. +func (mock *Interface) DeviceGetEncoderStats(device nvml.Device) (int, uint32, uint32, nvml.Return) { + if mock.DeviceGetEncoderStatsFunc == nil { + panic("Interface.DeviceGetEncoderStatsFunc: method is nil but Interface.DeviceGetEncoderStats was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetEncoderStats.Lock() + mock.calls.DeviceGetEncoderStats = append(mock.calls.DeviceGetEncoderStats, callInfo) + mock.lockDeviceGetEncoderStats.Unlock() + return mock.DeviceGetEncoderStatsFunc(device) +} + +// DeviceGetEncoderStatsCalls gets all the calls that were made to DeviceGetEncoderStats. +// Check the length with: +// +// len(mockedInterface.DeviceGetEncoderStatsCalls()) +func (mock *Interface) DeviceGetEncoderStatsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetEncoderStats.RLock() + calls = mock.calls.DeviceGetEncoderStats + mock.lockDeviceGetEncoderStats.RUnlock() + return calls +} + +// DeviceGetEncoderUtilization calls DeviceGetEncoderUtilizationFunc. +func (mock *Interface) DeviceGetEncoderUtilization(device nvml.Device) (uint32, uint32, nvml.Return) { + if mock.DeviceGetEncoderUtilizationFunc == nil { + panic("Interface.DeviceGetEncoderUtilizationFunc: method is nil but Interface.DeviceGetEncoderUtilization was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetEncoderUtilization.Lock() + mock.calls.DeviceGetEncoderUtilization = append(mock.calls.DeviceGetEncoderUtilization, callInfo) + mock.lockDeviceGetEncoderUtilization.Unlock() + return mock.DeviceGetEncoderUtilizationFunc(device) +} + +// DeviceGetEncoderUtilizationCalls gets all the calls that were made to DeviceGetEncoderUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetEncoderUtilizationCalls()) +func (mock *Interface) DeviceGetEncoderUtilizationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetEncoderUtilization.RLock() + calls = mock.calls.DeviceGetEncoderUtilization + mock.lockDeviceGetEncoderUtilization.RUnlock() + return calls +} + +// DeviceGetEnforcedPowerLimit calls DeviceGetEnforcedPowerLimitFunc. +func (mock *Interface) DeviceGetEnforcedPowerLimit(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetEnforcedPowerLimitFunc == nil { + panic("Interface.DeviceGetEnforcedPowerLimitFunc: method is nil but Interface.DeviceGetEnforcedPowerLimit was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetEnforcedPowerLimit.Lock() + mock.calls.DeviceGetEnforcedPowerLimit = append(mock.calls.DeviceGetEnforcedPowerLimit, callInfo) + mock.lockDeviceGetEnforcedPowerLimit.Unlock() + return mock.DeviceGetEnforcedPowerLimitFunc(device) +} + +// DeviceGetEnforcedPowerLimitCalls gets all the calls that were made to DeviceGetEnforcedPowerLimit. +// Check the length with: +// +// len(mockedInterface.DeviceGetEnforcedPowerLimitCalls()) +func (mock *Interface) DeviceGetEnforcedPowerLimitCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetEnforcedPowerLimit.RLock() + calls = mock.calls.DeviceGetEnforcedPowerLimit + mock.lockDeviceGetEnforcedPowerLimit.RUnlock() + return calls +} + +// DeviceGetFBCSessions calls DeviceGetFBCSessionsFunc. +func (mock *Interface) DeviceGetFBCSessions(device nvml.Device) ([]nvml.FBCSessionInfo, nvml.Return) { + if mock.DeviceGetFBCSessionsFunc == nil { + panic("Interface.DeviceGetFBCSessionsFunc: method is nil but Interface.DeviceGetFBCSessions was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetFBCSessions.Lock() + mock.calls.DeviceGetFBCSessions = append(mock.calls.DeviceGetFBCSessions, callInfo) + mock.lockDeviceGetFBCSessions.Unlock() + return mock.DeviceGetFBCSessionsFunc(device) +} + +// DeviceGetFBCSessionsCalls gets all the calls that were made to DeviceGetFBCSessions. +// Check the length with: +// +// len(mockedInterface.DeviceGetFBCSessionsCalls()) +func (mock *Interface) DeviceGetFBCSessionsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetFBCSessions.RLock() + calls = mock.calls.DeviceGetFBCSessions + mock.lockDeviceGetFBCSessions.RUnlock() + return calls +} + +// DeviceGetFBCStats calls DeviceGetFBCStatsFunc. +func (mock *Interface) DeviceGetFBCStats(device nvml.Device) (nvml.FBCStats, nvml.Return) { + if mock.DeviceGetFBCStatsFunc == nil { + panic("Interface.DeviceGetFBCStatsFunc: method is nil but Interface.DeviceGetFBCStats was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetFBCStats.Lock() + mock.calls.DeviceGetFBCStats = append(mock.calls.DeviceGetFBCStats, callInfo) + mock.lockDeviceGetFBCStats.Unlock() + return mock.DeviceGetFBCStatsFunc(device) +} + +// DeviceGetFBCStatsCalls gets all the calls that were made to DeviceGetFBCStats. +// Check the length with: +// +// len(mockedInterface.DeviceGetFBCStatsCalls()) +func (mock *Interface) DeviceGetFBCStatsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetFBCStats.RLock() + calls = mock.calls.DeviceGetFBCStats + mock.lockDeviceGetFBCStats.RUnlock() + return calls +} + +// DeviceGetFanControlPolicy_v2 calls DeviceGetFanControlPolicy_v2Func. +func (mock *Interface) DeviceGetFanControlPolicy_v2(device nvml.Device, n int) (nvml.FanControlPolicy, nvml.Return) { + if mock.DeviceGetFanControlPolicy_v2Func == nil { + panic("Interface.DeviceGetFanControlPolicy_v2Func: method is nil but Interface.DeviceGetFanControlPolicy_v2 was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetFanControlPolicy_v2.Lock() + mock.calls.DeviceGetFanControlPolicy_v2 = append(mock.calls.DeviceGetFanControlPolicy_v2, callInfo) + mock.lockDeviceGetFanControlPolicy_v2.Unlock() + return mock.DeviceGetFanControlPolicy_v2Func(device, n) +} + +// DeviceGetFanControlPolicy_v2Calls gets all the calls that were made to DeviceGetFanControlPolicy_v2. +// Check the length with: +// +// len(mockedInterface.DeviceGetFanControlPolicy_v2Calls()) +func (mock *Interface) DeviceGetFanControlPolicy_v2Calls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetFanControlPolicy_v2.RLock() + calls = mock.calls.DeviceGetFanControlPolicy_v2 + mock.lockDeviceGetFanControlPolicy_v2.RUnlock() + return calls +} + +// DeviceGetFanSpeed calls DeviceGetFanSpeedFunc. +func (mock *Interface) DeviceGetFanSpeed(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetFanSpeedFunc == nil { + panic("Interface.DeviceGetFanSpeedFunc: method is nil but Interface.DeviceGetFanSpeed was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetFanSpeed.Lock() + mock.calls.DeviceGetFanSpeed = append(mock.calls.DeviceGetFanSpeed, callInfo) + mock.lockDeviceGetFanSpeed.Unlock() + return mock.DeviceGetFanSpeedFunc(device) +} + +// DeviceGetFanSpeedCalls gets all the calls that were made to DeviceGetFanSpeed. +// Check the length with: +// +// len(mockedInterface.DeviceGetFanSpeedCalls()) +func (mock *Interface) DeviceGetFanSpeedCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetFanSpeed.RLock() + calls = mock.calls.DeviceGetFanSpeed + mock.lockDeviceGetFanSpeed.RUnlock() + return calls +} + +// DeviceGetFanSpeedRPM calls DeviceGetFanSpeedRPMFunc. +func (mock *Interface) DeviceGetFanSpeedRPM(device nvml.Device) (nvml.FanSpeedInfo, nvml.Return) { + if mock.DeviceGetFanSpeedRPMFunc == nil { + panic("Interface.DeviceGetFanSpeedRPMFunc: method is nil but Interface.DeviceGetFanSpeedRPM was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetFanSpeedRPM.Lock() + mock.calls.DeviceGetFanSpeedRPM = append(mock.calls.DeviceGetFanSpeedRPM, callInfo) + mock.lockDeviceGetFanSpeedRPM.Unlock() + return mock.DeviceGetFanSpeedRPMFunc(device) +} + +// DeviceGetFanSpeedRPMCalls gets all the calls that were made to DeviceGetFanSpeedRPM. +// Check the length with: +// +// len(mockedInterface.DeviceGetFanSpeedRPMCalls()) +func (mock *Interface) DeviceGetFanSpeedRPMCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetFanSpeedRPM.RLock() + calls = mock.calls.DeviceGetFanSpeedRPM + mock.lockDeviceGetFanSpeedRPM.RUnlock() + return calls +} + +// DeviceGetFanSpeed_v2 calls DeviceGetFanSpeed_v2Func. +func (mock *Interface) DeviceGetFanSpeed_v2(device nvml.Device, n int) (uint32, nvml.Return) { + if mock.DeviceGetFanSpeed_v2Func == nil { + panic("Interface.DeviceGetFanSpeed_v2Func: method is nil but Interface.DeviceGetFanSpeed_v2 was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetFanSpeed_v2.Lock() + mock.calls.DeviceGetFanSpeed_v2 = append(mock.calls.DeviceGetFanSpeed_v2, callInfo) + mock.lockDeviceGetFanSpeed_v2.Unlock() + return mock.DeviceGetFanSpeed_v2Func(device, n) +} + +// DeviceGetFanSpeed_v2Calls gets all the calls that were made to DeviceGetFanSpeed_v2. +// Check the length with: +// +// len(mockedInterface.DeviceGetFanSpeed_v2Calls()) +func (mock *Interface) DeviceGetFanSpeed_v2Calls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetFanSpeed_v2.RLock() + calls = mock.calls.DeviceGetFanSpeed_v2 + mock.lockDeviceGetFanSpeed_v2.RUnlock() + return calls +} + +// DeviceGetFieldValues calls DeviceGetFieldValuesFunc. +func (mock *Interface) DeviceGetFieldValues(device nvml.Device, fieldValues []nvml.FieldValue) nvml.Return { + if mock.DeviceGetFieldValuesFunc == nil { + panic("Interface.DeviceGetFieldValuesFunc: method is nil but Interface.DeviceGetFieldValues was just called") + } + callInfo := struct { + Device nvml.Device + FieldValues []nvml.FieldValue + }{ + Device: device, + FieldValues: fieldValues, + } + mock.lockDeviceGetFieldValues.Lock() + mock.calls.DeviceGetFieldValues = append(mock.calls.DeviceGetFieldValues, callInfo) + mock.lockDeviceGetFieldValues.Unlock() + return mock.DeviceGetFieldValuesFunc(device, fieldValues) +} + +// DeviceGetFieldValuesCalls gets all the calls that were made to DeviceGetFieldValues. +// Check the length with: +// +// len(mockedInterface.DeviceGetFieldValuesCalls()) +func (mock *Interface) DeviceGetFieldValuesCalls() []struct { + Device nvml.Device + FieldValues []nvml.FieldValue +} { + var calls []struct { + Device nvml.Device + FieldValues []nvml.FieldValue + } + mock.lockDeviceGetFieldValues.RLock() + calls = mock.calls.DeviceGetFieldValues + mock.lockDeviceGetFieldValues.RUnlock() + return calls +} + +// DeviceGetGpcClkMinMaxVfOffset calls DeviceGetGpcClkMinMaxVfOffsetFunc. +func (mock *Interface) DeviceGetGpcClkMinMaxVfOffset(device nvml.Device) (int, int, nvml.Return) { + if mock.DeviceGetGpcClkMinMaxVfOffsetFunc == nil { + panic("Interface.DeviceGetGpcClkMinMaxVfOffsetFunc: method is nil but Interface.DeviceGetGpcClkMinMaxVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpcClkMinMaxVfOffset.Lock() + mock.calls.DeviceGetGpcClkMinMaxVfOffset = append(mock.calls.DeviceGetGpcClkMinMaxVfOffset, callInfo) + mock.lockDeviceGetGpcClkMinMaxVfOffset.Unlock() + return mock.DeviceGetGpcClkMinMaxVfOffsetFunc(device) +} + +// DeviceGetGpcClkMinMaxVfOffsetCalls gets all the calls that were made to DeviceGetGpcClkMinMaxVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpcClkMinMaxVfOffsetCalls()) +func (mock *Interface) DeviceGetGpcClkMinMaxVfOffsetCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpcClkMinMaxVfOffset.RLock() + calls = mock.calls.DeviceGetGpcClkMinMaxVfOffset + mock.lockDeviceGetGpcClkMinMaxVfOffset.RUnlock() + return calls +} + +// DeviceGetGpcClkVfOffset calls DeviceGetGpcClkVfOffsetFunc. +func (mock *Interface) DeviceGetGpcClkVfOffset(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetGpcClkVfOffsetFunc == nil { + panic("Interface.DeviceGetGpcClkVfOffsetFunc: method is nil but Interface.DeviceGetGpcClkVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpcClkVfOffset.Lock() + mock.calls.DeviceGetGpcClkVfOffset = append(mock.calls.DeviceGetGpcClkVfOffset, callInfo) + mock.lockDeviceGetGpcClkVfOffset.Unlock() + return mock.DeviceGetGpcClkVfOffsetFunc(device) +} + +// DeviceGetGpcClkVfOffsetCalls gets all the calls that were made to DeviceGetGpcClkVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpcClkVfOffsetCalls()) +func (mock *Interface) DeviceGetGpcClkVfOffsetCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpcClkVfOffset.RLock() + calls = mock.calls.DeviceGetGpcClkVfOffset + mock.lockDeviceGetGpcClkVfOffset.RUnlock() + return calls +} + +// DeviceGetGpuFabricInfo calls DeviceGetGpuFabricInfoFunc. +func (mock *Interface) DeviceGetGpuFabricInfo(device nvml.Device) (nvml.GpuFabricInfo, nvml.Return) { + if mock.DeviceGetGpuFabricInfoFunc == nil { + panic("Interface.DeviceGetGpuFabricInfoFunc: method is nil but Interface.DeviceGetGpuFabricInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpuFabricInfo.Lock() + mock.calls.DeviceGetGpuFabricInfo = append(mock.calls.DeviceGetGpuFabricInfo, callInfo) + mock.lockDeviceGetGpuFabricInfo.Unlock() + return mock.DeviceGetGpuFabricInfoFunc(device) +} + +// DeviceGetGpuFabricInfoCalls gets all the calls that were made to DeviceGetGpuFabricInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuFabricInfoCalls()) +func (mock *Interface) DeviceGetGpuFabricInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpuFabricInfo.RLock() + calls = mock.calls.DeviceGetGpuFabricInfo + mock.lockDeviceGetGpuFabricInfo.RUnlock() + return calls +} + +// DeviceGetGpuFabricInfoV calls DeviceGetGpuFabricInfoVFunc. +func (mock *Interface) DeviceGetGpuFabricInfoV(device nvml.Device) nvml.GpuFabricInfoHandler { + if mock.DeviceGetGpuFabricInfoVFunc == nil { + panic("Interface.DeviceGetGpuFabricInfoVFunc: method is nil but Interface.DeviceGetGpuFabricInfoV was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpuFabricInfoV.Lock() + mock.calls.DeviceGetGpuFabricInfoV = append(mock.calls.DeviceGetGpuFabricInfoV, callInfo) + mock.lockDeviceGetGpuFabricInfoV.Unlock() + return mock.DeviceGetGpuFabricInfoVFunc(device) +} + +// DeviceGetGpuFabricInfoVCalls gets all the calls that were made to DeviceGetGpuFabricInfoV. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuFabricInfoVCalls()) +func (mock *Interface) DeviceGetGpuFabricInfoVCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpuFabricInfoV.RLock() + calls = mock.calls.DeviceGetGpuFabricInfoV + mock.lockDeviceGetGpuFabricInfoV.RUnlock() + return calls +} + +// DeviceGetGpuInstanceById calls DeviceGetGpuInstanceByIdFunc. +func (mock *Interface) DeviceGetGpuInstanceById(device nvml.Device, n int) (nvml.GpuInstance, nvml.Return) { + if mock.DeviceGetGpuInstanceByIdFunc == nil { + panic("Interface.DeviceGetGpuInstanceByIdFunc: method is nil but Interface.DeviceGetGpuInstanceById was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetGpuInstanceById.Lock() + mock.calls.DeviceGetGpuInstanceById = append(mock.calls.DeviceGetGpuInstanceById, callInfo) + mock.lockDeviceGetGpuInstanceById.Unlock() + return mock.DeviceGetGpuInstanceByIdFunc(device, n) +} + +// DeviceGetGpuInstanceByIdCalls gets all the calls that were made to DeviceGetGpuInstanceById. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceByIdCalls()) +func (mock *Interface) DeviceGetGpuInstanceByIdCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetGpuInstanceById.RLock() + calls = mock.calls.DeviceGetGpuInstanceById + mock.lockDeviceGetGpuInstanceById.RUnlock() + return calls +} + +// DeviceGetGpuInstanceId calls DeviceGetGpuInstanceIdFunc. +func (mock *Interface) DeviceGetGpuInstanceId(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetGpuInstanceIdFunc == nil { + panic("Interface.DeviceGetGpuInstanceIdFunc: method is nil but Interface.DeviceGetGpuInstanceId was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpuInstanceId.Lock() + mock.calls.DeviceGetGpuInstanceId = append(mock.calls.DeviceGetGpuInstanceId, callInfo) + mock.lockDeviceGetGpuInstanceId.Unlock() + return mock.DeviceGetGpuInstanceIdFunc(device) +} + +// DeviceGetGpuInstanceIdCalls gets all the calls that were made to DeviceGetGpuInstanceId. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceIdCalls()) +func (mock *Interface) DeviceGetGpuInstanceIdCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpuInstanceId.RLock() + calls = mock.calls.DeviceGetGpuInstanceId + mock.lockDeviceGetGpuInstanceId.RUnlock() + return calls +} + +// DeviceGetGpuInstancePossiblePlacements calls DeviceGetGpuInstancePossiblePlacementsFunc. +func (mock *Interface) DeviceGetGpuInstancePossiblePlacements(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstancePlacement, nvml.Return) { + if mock.DeviceGetGpuInstancePossiblePlacementsFunc == nil { + panic("Interface.DeviceGetGpuInstancePossiblePlacementsFunc: method is nil but Interface.DeviceGetGpuInstancePossiblePlacements was just called") + } + callInfo := struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + Device: device, + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockDeviceGetGpuInstancePossiblePlacements.Lock() + mock.calls.DeviceGetGpuInstancePossiblePlacements = append(mock.calls.DeviceGetGpuInstancePossiblePlacements, callInfo) + mock.lockDeviceGetGpuInstancePossiblePlacements.Unlock() + return mock.DeviceGetGpuInstancePossiblePlacementsFunc(device, gpuInstanceProfileInfo) +} + +// DeviceGetGpuInstancePossiblePlacementsCalls gets all the calls that were made to DeviceGetGpuInstancePossiblePlacements. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstancePossiblePlacementsCalls()) +func (mock *Interface) DeviceGetGpuInstancePossiblePlacementsCalls() []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockDeviceGetGpuInstancePossiblePlacements.RLock() + calls = mock.calls.DeviceGetGpuInstancePossiblePlacements + mock.lockDeviceGetGpuInstancePossiblePlacements.RUnlock() + return calls +} + +// DeviceGetGpuInstanceProfileInfo calls DeviceGetGpuInstanceProfileInfoFunc. +func (mock *Interface) DeviceGetGpuInstanceProfileInfo(device nvml.Device, n int) (nvml.GpuInstanceProfileInfo, nvml.Return) { + if mock.DeviceGetGpuInstanceProfileInfoFunc == nil { + panic("Interface.DeviceGetGpuInstanceProfileInfoFunc: method is nil but Interface.DeviceGetGpuInstanceProfileInfo was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetGpuInstanceProfileInfo.Lock() + mock.calls.DeviceGetGpuInstanceProfileInfo = append(mock.calls.DeviceGetGpuInstanceProfileInfo, callInfo) + mock.lockDeviceGetGpuInstanceProfileInfo.Unlock() + return mock.DeviceGetGpuInstanceProfileInfoFunc(device, n) +} + +// DeviceGetGpuInstanceProfileInfoCalls gets all the calls that were made to DeviceGetGpuInstanceProfileInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceProfileInfoCalls()) +func (mock *Interface) DeviceGetGpuInstanceProfileInfoCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetGpuInstanceProfileInfo.RLock() + calls = mock.calls.DeviceGetGpuInstanceProfileInfo + mock.lockDeviceGetGpuInstanceProfileInfo.RUnlock() + return calls +} + +// DeviceGetGpuInstanceProfileInfoByIdV calls DeviceGetGpuInstanceProfileInfoByIdVFunc. +func (mock *Interface) DeviceGetGpuInstanceProfileInfoByIdV(device nvml.Device, n int) nvml.GpuInstanceProfileInfoByIdHandler { + if mock.DeviceGetGpuInstanceProfileInfoByIdVFunc == nil { + panic("Interface.DeviceGetGpuInstanceProfileInfoByIdVFunc: method is nil but Interface.DeviceGetGpuInstanceProfileInfoByIdV was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetGpuInstanceProfileInfoByIdV.Lock() + mock.calls.DeviceGetGpuInstanceProfileInfoByIdV = append(mock.calls.DeviceGetGpuInstanceProfileInfoByIdV, callInfo) + mock.lockDeviceGetGpuInstanceProfileInfoByIdV.Unlock() + return mock.DeviceGetGpuInstanceProfileInfoByIdVFunc(device, n) +} + +// DeviceGetGpuInstanceProfileInfoByIdVCalls gets all the calls that were made to DeviceGetGpuInstanceProfileInfoByIdV. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceProfileInfoByIdVCalls()) +func (mock *Interface) DeviceGetGpuInstanceProfileInfoByIdVCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetGpuInstanceProfileInfoByIdV.RLock() + calls = mock.calls.DeviceGetGpuInstanceProfileInfoByIdV + mock.lockDeviceGetGpuInstanceProfileInfoByIdV.RUnlock() + return calls +} + +// DeviceGetGpuInstanceProfileInfoV calls DeviceGetGpuInstanceProfileInfoVFunc. +func (mock *Interface) DeviceGetGpuInstanceProfileInfoV(device nvml.Device, n int) nvml.GpuInstanceProfileInfoHandler { + if mock.DeviceGetGpuInstanceProfileInfoVFunc == nil { + panic("Interface.DeviceGetGpuInstanceProfileInfoVFunc: method is nil but Interface.DeviceGetGpuInstanceProfileInfoV was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetGpuInstanceProfileInfoV.Lock() + mock.calls.DeviceGetGpuInstanceProfileInfoV = append(mock.calls.DeviceGetGpuInstanceProfileInfoV, callInfo) + mock.lockDeviceGetGpuInstanceProfileInfoV.Unlock() + return mock.DeviceGetGpuInstanceProfileInfoVFunc(device, n) +} + +// DeviceGetGpuInstanceProfileInfoVCalls gets all the calls that were made to DeviceGetGpuInstanceProfileInfoV. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceProfileInfoVCalls()) +func (mock *Interface) DeviceGetGpuInstanceProfileInfoVCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetGpuInstanceProfileInfoV.RLock() + calls = mock.calls.DeviceGetGpuInstanceProfileInfoV + mock.lockDeviceGetGpuInstanceProfileInfoV.RUnlock() + return calls +} + +// DeviceGetGpuInstanceRemainingCapacity calls DeviceGetGpuInstanceRemainingCapacityFunc. +func (mock *Interface) DeviceGetGpuInstanceRemainingCapacity(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) (int, nvml.Return) { + if mock.DeviceGetGpuInstanceRemainingCapacityFunc == nil { + panic("Interface.DeviceGetGpuInstanceRemainingCapacityFunc: method is nil but Interface.DeviceGetGpuInstanceRemainingCapacity was just called") + } + callInfo := struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + Device: device, + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockDeviceGetGpuInstanceRemainingCapacity.Lock() + mock.calls.DeviceGetGpuInstanceRemainingCapacity = append(mock.calls.DeviceGetGpuInstanceRemainingCapacity, callInfo) + mock.lockDeviceGetGpuInstanceRemainingCapacity.Unlock() + return mock.DeviceGetGpuInstanceRemainingCapacityFunc(device, gpuInstanceProfileInfo) +} + +// DeviceGetGpuInstanceRemainingCapacityCalls gets all the calls that were made to DeviceGetGpuInstanceRemainingCapacity. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstanceRemainingCapacityCalls()) +func (mock *Interface) DeviceGetGpuInstanceRemainingCapacityCalls() []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockDeviceGetGpuInstanceRemainingCapacity.RLock() + calls = mock.calls.DeviceGetGpuInstanceRemainingCapacity + mock.lockDeviceGetGpuInstanceRemainingCapacity.RUnlock() + return calls +} + +// DeviceGetGpuInstances calls DeviceGetGpuInstancesFunc. +func (mock *Interface) DeviceGetGpuInstances(device nvml.Device, gpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo) ([]nvml.GpuInstance, nvml.Return) { + if mock.DeviceGetGpuInstancesFunc == nil { + panic("Interface.DeviceGetGpuInstancesFunc: method is nil but Interface.DeviceGetGpuInstances was just called") + } + callInfo := struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + }{ + Device: device, + GpuInstanceProfileInfo: gpuInstanceProfileInfo, + } + mock.lockDeviceGetGpuInstances.Lock() + mock.calls.DeviceGetGpuInstances = append(mock.calls.DeviceGetGpuInstances, callInfo) + mock.lockDeviceGetGpuInstances.Unlock() + return mock.DeviceGetGpuInstancesFunc(device, gpuInstanceProfileInfo) +} + +// DeviceGetGpuInstancesCalls gets all the calls that were made to DeviceGetGpuInstances. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuInstancesCalls()) +func (mock *Interface) DeviceGetGpuInstancesCalls() []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo +} { + var calls []struct { + Device nvml.Device + GpuInstanceProfileInfo *nvml.GpuInstanceProfileInfo + } + mock.lockDeviceGetGpuInstances.RLock() + calls = mock.calls.DeviceGetGpuInstances + mock.lockDeviceGetGpuInstances.RUnlock() + return calls +} + +// DeviceGetGpuMaxPcieLinkGeneration calls DeviceGetGpuMaxPcieLinkGenerationFunc. +func (mock *Interface) DeviceGetGpuMaxPcieLinkGeneration(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetGpuMaxPcieLinkGenerationFunc == nil { + panic("Interface.DeviceGetGpuMaxPcieLinkGenerationFunc: method is nil but Interface.DeviceGetGpuMaxPcieLinkGeneration was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpuMaxPcieLinkGeneration.Lock() + mock.calls.DeviceGetGpuMaxPcieLinkGeneration = append(mock.calls.DeviceGetGpuMaxPcieLinkGeneration, callInfo) + mock.lockDeviceGetGpuMaxPcieLinkGeneration.Unlock() + return mock.DeviceGetGpuMaxPcieLinkGenerationFunc(device) +} + +// DeviceGetGpuMaxPcieLinkGenerationCalls gets all the calls that were made to DeviceGetGpuMaxPcieLinkGeneration. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuMaxPcieLinkGenerationCalls()) +func (mock *Interface) DeviceGetGpuMaxPcieLinkGenerationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpuMaxPcieLinkGeneration.RLock() + calls = mock.calls.DeviceGetGpuMaxPcieLinkGeneration + mock.lockDeviceGetGpuMaxPcieLinkGeneration.RUnlock() + return calls +} + +// DeviceGetGpuOperationMode calls DeviceGetGpuOperationModeFunc. +func (mock *Interface) DeviceGetGpuOperationMode(device nvml.Device) (nvml.GpuOperationMode, nvml.GpuOperationMode, nvml.Return) { + if mock.DeviceGetGpuOperationModeFunc == nil { + panic("Interface.DeviceGetGpuOperationModeFunc: method is nil but Interface.DeviceGetGpuOperationMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGpuOperationMode.Lock() + mock.calls.DeviceGetGpuOperationMode = append(mock.calls.DeviceGetGpuOperationMode, callInfo) + mock.lockDeviceGetGpuOperationMode.Unlock() + return mock.DeviceGetGpuOperationModeFunc(device) +} + +// DeviceGetGpuOperationModeCalls gets all the calls that were made to DeviceGetGpuOperationMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetGpuOperationModeCalls()) +func (mock *Interface) DeviceGetGpuOperationModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGpuOperationMode.RLock() + calls = mock.calls.DeviceGetGpuOperationMode + mock.lockDeviceGetGpuOperationMode.RUnlock() + return calls +} + +// DeviceGetGraphicsRunningProcesses calls DeviceGetGraphicsRunningProcessesFunc. +func (mock *Interface) DeviceGetGraphicsRunningProcesses(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { + if mock.DeviceGetGraphicsRunningProcessesFunc == nil { + panic("Interface.DeviceGetGraphicsRunningProcessesFunc: method is nil but Interface.DeviceGetGraphicsRunningProcesses was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGraphicsRunningProcesses.Lock() + mock.calls.DeviceGetGraphicsRunningProcesses = append(mock.calls.DeviceGetGraphicsRunningProcesses, callInfo) + mock.lockDeviceGetGraphicsRunningProcesses.Unlock() + return mock.DeviceGetGraphicsRunningProcessesFunc(device) +} + +// DeviceGetGraphicsRunningProcessesCalls gets all the calls that were made to DeviceGetGraphicsRunningProcesses. +// Check the length with: +// +// len(mockedInterface.DeviceGetGraphicsRunningProcessesCalls()) +func (mock *Interface) DeviceGetGraphicsRunningProcessesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGraphicsRunningProcesses.RLock() + calls = mock.calls.DeviceGetGraphicsRunningProcesses + mock.lockDeviceGetGraphicsRunningProcesses.RUnlock() + return calls +} + +// DeviceGetGridLicensableFeatures calls DeviceGetGridLicensableFeaturesFunc. +func (mock *Interface) DeviceGetGridLicensableFeatures(device nvml.Device) (nvml.GridLicensableFeatures, nvml.Return) { + if mock.DeviceGetGridLicensableFeaturesFunc == nil { + panic("Interface.DeviceGetGridLicensableFeaturesFunc: method is nil but Interface.DeviceGetGridLicensableFeatures was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGridLicensableFeatures.Lock() + mock.calls.DeviceGetGridLicensableFeatures = append(mock.calls.DeviceGetGridLicensableFeatures, callInfo) + mock.lockDeviceGetGridLicensableFeatures.Unlock() + return mock.DeviceGetGridLicensableFeaturesFunc(device) +} + +// DeviceGetGridLicensableFeaturesCalls gets all the calls that were made to DeviceGetGridLicensableFeatures. +// Check the length with: +// +// len(mockedInterface.DeviceGetGridLicensableFeaturesCalls()) +func (mock *Interface) DeviceGetGridLicensableFeaturesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGridLicensableFeatures.RLock() + calls = mock.calls.DeviceGetGridLicensableFeatures + mock.lockDeviceGetGridLicensableFeatures.RUnlock() + return calls +} + +// DeviceGetGspFirmwareMode calls DeviceGetGspFirmwareModeFunc. +func (mock *Interface) DeviceGetGspFirmwareMode(device nvml.Device) (bool, bool, nvml.Return) { + if mock.DeviceGetGspFirmwareModeFunc == nil { + panic("Interface.DeviceGetGspFirmwareModeFunc: method is nil but Interface.DeviceGetGspFirmwareMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGspFirmwareMode.Lock() + mock.calls.DeviceGetGspFirmwareMode = append(mock.calls.DeviceGetGspFirmwareMode, callInfo) + mock.lockDeviceGetGspFirmwareMode.Unlock() + return mock.DeviceGetGspFirmwareModeFunc(device) +} + +// DeviceGetGspFirmwareModeCalls gets all the calls that were made to DeviceGetGspFirmwareMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetGspFirmwareModeCalls()) +func (mock *Interface) DeviceGetGspFirmwareModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGspFirmwareMode.RLock() + calls = mock.calls.DeviceGetGspFirmwareMode + mock.lockDeviceGetGspFirmwareMode.RUnlock() + return calls +} + +// DeviceGetGspFirmwareVersion calls DeviceGetGspFirmwareVersionFunc. +func (mock *Interface) DeviceGetGspFirmwareVersion(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetGspFirmwareVersionFunc == nil { + panic("Interface.DeviceGetGspFirmwareVersionFunc: method is nil but Interface.DeviceGetGspFirmwareVersion was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetGspFirmwareVersion.Lock() + mock.calls.DeviceGetGspFirmwareVersion = append(mock.calls.DeviceGetGspFirmwareVersion, callInfo) + mock.lockDeviceGetGspFirmwareVersion.Unlock() + return mock.DeviceGetGspFirmwareVersionFunc(device) +} + +// DeviceGetGspFirmwareVersionCalls gets all the calls that were made to DeviceGetGspFirmwareVersion. +// Check the length with: +// +// len(mockedInterface.DeviceGetGspFirmwareVersionCalls()) +func (mock *Interface) DeviceGetGspFirmwareVersionCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetGspFirmwareVersion.RLock() + calls = mock.calls.DeviceGetGspFirmwareVersion + mock.lockDeviceGetGspFirmwareVersion.RUnlock() + return calls +} + +// DeviceGetHandleByIndex calls DeviceGetHandleByIndexFunc. +func (mock *Interface) DeviceGetHandleByIndex(n int) (nvml.Device, nvml.Return) { + if mock.DeviceGetHandleByIndexFunc == nil { + panic("Interface.DeviceGetHandleByIndexFunc: method is nil but Interface.DeviceGetHandleByIndex was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockDeviceGetHandleByIndex.Lock() + mock.calls.DeviceGetHandleByIndex = append(mock.calls.DeviceGetHandleByIndex, callInfo) + mock.lockDeviceGetHandleByIndex.Unlock() + return mock.DeviceGetHandleByIndexFunc(n) +} + +// DeviceGetHandleByIndexCalls gets all the calls that were made to DeviceGetHandleByIndex. +// Check the length with: +// +// len(mockedInterface.DeviceGetHandleByIndexCalls()) +func (mock *Interface) DeviceGetHandleByIndexCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockDeviceGetHandleByIndex.RLock() + calls = mock.calls.DeviceGetHandleByIndex + mock.lockDeviceGetHandleByIndex.RUnlock() + return calls +} + +// DeviceGetHandleByPciBusId calls DeviceGetHandleByPciBusIdFunc. +func (mock *Interface) DeviceGetHandleByPciBusId(s string) (nvml.Device, nvml.Return) { + if mock.DeviceGetHandleByPciBusIdFunc == nil { + panic("Interface.DeviceGetHandleByPciBusIdFunc: method is nil but Interface.DeviceGetHandleByPciBusId was just called") + } + callInfo := struct { + S string + }{ + S: s, + } + mock.lockDeviceGetHandleByPciBusId.Lock() + mock.calls.DeviceGetHandleByPciBusId = append(mock.calls.DeviceGetHandleByPciBusId, callInfo) + mock.lockDeviceGetHandleByPciBusId.Unlock() + return mock.DeviceGetHandleByPciBusIdFunc(s) +} + +// DeviceGetHandleByPciBusIdCalls gets all the calls that were made to DeviceGetHandleByPciBusId. +// Check the length with: +// +// len(mockedInterface.DeviceGetHandleByPciBusIdCalls()) +func (mock *Interface) DeviceGetHandleByPciBusIdCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockDeviceGetHandleByPciBusId.RLock() + calls = mock.calls.DeviceGetHandleByPciBusId + mock.lockDeviceGetHandleByPciBusId.RUnlock() + return calls +} + +// DeviceGetHandleBySerial calls DeviceGetHandleBySerialFunc. +func (mock *Interface) DeviceGetHandleBySerial(s string) (nvml.Device, nvml.Return) { + if mock.DeviceGetHandleBySerialFunc == nil { + panic("Interface.DeviceGetHandleBySerialFunc: method is nil but Interface.DeviceGetHandleBySerial was just called") + } + callInfo := struct { + S string + }{ + S: s, + } + mock.lockDeviceGetHandleBySerial.Lock() + mock.calls.DeviceGetHandleBySerial = append(mock.calls.DeviceGetHandleBySerial, callInfo) + mock.lockDeviceGetHandleBySerial.Unlock() + return mock.DeviceGetHandleBySerialFunc(s) +} + +// DeviceGetHandleBySerialCalls gets all the calls that were made to DeviceGetHandleBySerial. +// Check the length with: +// +// len(mockedInterface.DeviceGetHandleBySerialCalls()) +func (mock *Interface) DeviceGetHandleBySerialCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockDeviceGetHandleBySerial.RLock() + calls = mock.calls.DeviceGetHandleBySerial + mock.lockDeviceGetHandleBySerial.RUnlock() + return calls +} + +// DeviceGetHandleByUUID calls DeviceGetHandleByUUIDFunc. +func (mock *Interface) DeviceGetHandleByUUID(s string) (nvml.Device, nvml.Return) { + if mock.DeviceGetHandleByUUIDFunc == nil { + panic("Interface.DeviceGetHandleByUUIDFunc: method is nil but Interface.DeviceGetHandleByUUID was just called") + } + callInfo := struct { + S string + }{ + S: s, + } + mock.lockDeviceGetHandleByUUID.Lock() + mock.calls.DeviceGetHandleByUUID = append(mock.calls.DeviceGetHandleByUUID, callInfo) + mock.lockDeviceGetHandleByUUID.Unlock() + return mock.DeviceGetHandleByUUIDFunc(s) +} + +// DeviceGetHandleByUUIDCalls gets all the calls that were made to DeviceGetHandleByUUID. +// Check the length with: +// +// len(mockedInterface.DeviceGetHandleByUUIDCalls()) +func (mock *Interface) DeviceGetHandleByUUIDCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockDeviceGetHandleByUUID.RLock() + calls = mock.calls.DeviceGetHandleByUUID + mock.lockDeviceGetHandleByUUID.RUnlock() + return calls +} + +// DeviceGetHandleByUUIDV calls DeviceGetHandleByUUIDVFunc. +func (mock *Interface) DeviceGetHandleByUUIDV(uUID *nvml.UUID) (nvml.Device, nvml.Return) { + if mock.DeviceGetHandleByUUIDVFunc == nil { + panic("Interface.DeviceGetHandleByUUIDVFunc: method is nil but Interface.DeviceGetHandleByUUIDV was just called") + } + callInfo := struct { + UUID *nvml.UUID + }{ + UUID: uUID, + } + mock.lockDeviceGetHandleByUUIDV.Lock() + mock.calls.DeviceGetHandleByUUIDV = append(mock.calls.DeviceGetHandleByUUIDV, callInfo) + mock.lockDeviceGetHandleByUUIDV.Unlock() + return mock.DeviceGetHandleByUUIDVFunc(uUID) +} + +// DeviceGetHandleByUUIDVCalls gets all the calls that were made to DeviceGetHandleByUUIDV. +// Check the length with: +// +// len(mockedInterface.DeviceGetHandleByUUIDVCalls()) +func (mock *Interface) DeviceGetHandleByUUIDVCalls() []struct { + UUID *nvml.UUID +} { + var calls []struct { + UUID *nvml.UUID + } + mock.lockDeviceGetHandleByUUIDV.RLock() + calls = mock.calls.DeviceGetHandleByUUIDV + mock.lockDeviceGetHandleByUUIDV.RUnlock() + return calls +} + +// DeviceGetHostVgpuMode calls DeviceGetHostVgpuModeFunc. +func (mock *Interface) DeviceGetHostVgpuMode(device nvml.Device) (nvml.HostVgpuMode, nvml.Return) { + if mock.DeviceGetHostVgpuModeFunc == nil { + panic("Interface.DeviceGetHostVgpuModeFunc: method is nil but Interface.DeviceGetHostVgpuMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetHostVgpuMode.Lock() + mock.calls.DeviceGetHostVgpuMode = append(mock.calls.DeviceGetHostVgpuMode, callInfo) + mock.lockDeviceGetHostVgpuMode.Unlock() + return mock.DeviceGetHostVgpuModeFunc(device) +} + +// DeviceGetHostVgpuModeCalls gets all the calls that were made to DeviceGetHostVgpuMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetHostVgpuModeCalls()) +func (mock *Interface) DeviceGetHostVgpuModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetHostVgpuMode.RLock() + calls = mock.calls.DeviceGetHostVgpuMode + mock.lockDeviceGetHostVgpuMode.RUnlock() + return calls +} + +// DeviceGetIndex calls DeviceGetIndexFunc. +func (mock *Interface) DeviceGetIndex(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetIndexFunc == nil { + panic("Interface.DeviceGetIndexFunc: method is nil but Interface.DeviceGetIndex was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetIndex.Lock() + mock.calls.DeviceGetIndex = append(mock.calls.DeviceGetIndex, callInfo) + mock.lockDeviceGetIndex.Unlock() + return mock.DeviceGetIndexFunc(device) +} + +// DeviceGetIndexCalls gets all the calls that were made to DeviceGetIndex. +// Check the length with: +// +// len(mockedInterface.DeviceGetIndexCalls()) +func (mock *Interface) DeviceGetIndexCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetIndex.RLock() + calls = mock.calls.DeviceGetIndex + mock.lockDeviceGetIndex.RUnlock() + return calls +} + +// DeviceGetInforomConfigurationChecksum calls DeviceGetInforomConfigurationChecksumFunc. +func (mock *Interface) DeviceGetInforomConfigurationChecksum(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetInforomConfigurationChecksumFunc == nil { + panic("Interface.DeviceGetInforomConfigurationChecksumFunc: method is nil but Interface.DeviceGetInforomConfigurationChecksum was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetInforomConfigurationChecksum.Lock() + mock.calls.DeviceGetInforomConfigurationChecksum = append(mock.calls.DeviceGetInforomConfigurationChecksum, callInfo) + mock.lockDeviceGetInforomConfigurationChecksum.Unlock() + return mock.DeviceGetInforomConfigurationChecksumFunc(device) +} + +// DeviceGetInforomConfigurationChecksumCalls gets all the calls that were made to DeviceGetInforomConfigurationChecksum. +// Check the length with: +// +// len(mockedInterface.DeviceGetInforomConfigurationChecksumCalls()) +func (mock *Interface) DeviceGetInforomConfigurationChecksumCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetInforomConfigurationChecksum.RLock() + calls = mock.calls.DeviceGetInforomConfigurationChecksum + mock.lockDeviceGetInforomConfigurationChecksum.RUnlock() + return calls +} + +// DeviceGetInforomImageVersion calls DeviceGetInforomImageVersionFunc. +func (mock *Interface) DeviceGetInforomImageVersion(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetInforomImageVersionFunc == nil { + panic("Interface.DeviceGetInforomImageVersionFunc: method is nil but Interface.DeviceGetInforomImageVersion was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetInforomImageVersion.Lock() + mock.calls.DeviceGetInforomImageVersion = append(mock.calls.DeviceGetInforomImageVersion, callInfo) + mock.lockDeviceGetInforomImageVersion.Unlock() + return mock.DeviceGetInforomImageVersionFunc(device) +} + +// DeviceGetInforomImageVersionCalls gets all the calls that were made to DeviceGetInforomImageVersion. +// Check the length with: +// +// len(mockedInterface.DeviceGetInforomImageVersionCalls()) +func (mock *Interface) DeviceGetInforomImageVersionCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetInforomImageVersion.RLock() + calls = mock.calls.DeviceGetInforomImageVersion + mock.lockDeviceGetInforomImageVersion.RUnlock() + return calls +} + +// DeviceGetInforomVersion calls DeviceGetInforomVersionFunc. +func (mock *Interface) DeviceGetInforomVersion(device nvml.Device, inforomObject nvml.InforomObject) (string, nvml.Return) { + if mock.DeviceGetInforomVersionFunc == nil { + panic("Interface.DeviceGetInforomVersionFunc: method is nil but Interface.DeviceGetInforomVersion was just called") + } + callInfo := struct { + Device nvml.Device + InforomObject nvml.InforomObject + }{ + Device: device, + InforomObject: inforomObject, + } + mock.lockDeviceGetInforomVersion.Lock() + mock.calls.DeviceGetInforomVersion = append(mock.calls.DeviceGetInforomVersion, callInfo) + mock.lockDeviceGetInforomVersion.Unlock() + return mock.DeviceGetInforomVersionFunc(device, inforomObject) +} + +// DeviceGetInforomVersionCalls gets all the calls that were made to DeviceGetInforomVersion. +// Check the length with: +// +// len(mockedInterface.DeviceGetInforomVersionCalls()) +func (mock *Interface) DeviceGetInforomVersionCalls() []struct { + Device nvml.Device + InforomObject nvml.InforomObject +} { + var calls []struct { + Device nvml.Device + InforomObject nvml.InforomObject + } + mock.lockDeviceGetInforomVersion.RLock() + calls = mock.calls.DeviceGetInforomVersion + mock.lockDeviceGetInforomVersion.RUnlock() + return calls +} + +// DeviceGetIrqNum calls DeviceGetIrqNumFunc. +func (mock *Interface) DeviceGetIrqNum(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetIrqNumFunc == nil { + panic("Interface.DeviceGetIrqNumFunc: method is nil but Interface.DeviceGetIrqNum was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetIrqNum.Lock() + mock.calls.DeviceGetIrqNum = append(mock.calls.DeviceGetIrqNum, callInfo) + mock.lockDeviceGetIrqNum.Unlock() + return mock.DeviceGetIrqNumFunc(device) +} + +// DeviceGetIrqNumCalls gets all the calls that were made to DeviceGetIrqNum. +// Check the length with: +// +// len(mockedInterface.DeviceGetIrqNumCalls()) +func (mock *Interface) DeviceGetIrqNumCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetIrqNum.RLock() + calls = mock.calls.DeviceGetIrqNum + mock.lockDeviceGetIrqNum.RUnlock() + return calls +} + +// DeviceGetJpgUtilization calls DeviceGetJpgUtilizationFunc. +func (mock *Interface) DeviceGetJpgUtilization(device nvml.Device) (uint32, uint32, nvml.Return) { + if mock.DeviceGetJpgUtilizationFunc == nil { + panic("Interface.DeviceGetJpgUtilizationFunc: method is nil but Interface.DeviceGetJpgUtilization was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetJpgUtilization.Lock() + mock.calls.DeviceGetJpgUtilization = append(mock.calls.DeviceGetJpgUtilization, callInfo) + mock.lockDeviceGetJpgUtilization.Unlock() + return mock.DeviceGetJpgUtilizationFunc(device) +} + +// DeviceGetJpgUtilizationCalls gets all the calls that were made to DeviceGetJpgUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetJpgUtilizationCalls()) +func (mock *Interface) DeviceGetJpgUtilizationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetJpgUtilization.RLock() + calls = mock.calls.DeviceGetJpgUtilization + mock.lockDeviceGetJpgUtilization.RUnlock() + return calls +} + +// DeviceGetLastBBXFlushTime calls DeviceGetLastBBXFlushTimeFunc. +func (mock *Interface) DeviceGetLastBBXFlushTime(device nvml.Device) (uint64, uint, nvml.Return) { + if mock.DeviceGetLastBBXFlushTimeFunc == nil { + panic("Interface.DeviceGetLastBBXFlushTimeFunc: method is nil but Interface.DeviceGetLastBBXFlushTime was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetLastBBXFlushTime.Lock() + mock.calls.DeviceGetLastBBXFlushTime = append(mock.calls.DeviceGetLastBBXFlushTime, callInfo) + mock.lockDeviceGetLastBBXFlushTime.Unlock() + return mock.DeviceGetLastBBXFlushTimeFunc(device) +} + +// DeviceGetLastBBXFlushTimeCalls gets all the calls that were made to DeviceGetLastBBXFlushTime. +// Check the length with: +// +// len(mockedInterface.DeviceGetLastBBXFlushTimeCalls()) +func (mock *Interface) DeviceGetLastBBXFlushTimeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetLastBBXFlushTime.RLock() + calls = mock.calls.DeviceGetLastBBXFlushTime + mock.lockDeviceGetLastBBXFlushTime.RUnlock() + return calls +} + +// DeviceGetMPSComputeRunningProcesses calls DeviceGetMPSComputeRunningProcessesFunc. +func (mock *Interface) DeviceGetMPSComputeRunningProcesses(device nvml.Device) ([]nvml.ProcessInfo, nvml.Return) { + if mock.DeviceGetMPSComputeRunningProcessesFunc == nil { + panic("Interface.DeviceGetMPSComputeRunningProcessesFunc: method is nil but Interface.DeviceGetMPSComputeRunningProcesses was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMPSComputeRunningProcesses.Lock() + mock.calls.DeviceGetMPSComputeRunningProcesses = append(mock.calls.DeviceGetMPSComputeRunningProcesses, callInfo) + mock.lockDeviceGetMPSComputeRunningProcesses.Unlock() + return mock.DeviceGetMPSComputeRunningProcessesFunc(device) +} + +// DeviceGetMPSComputeRunningProcessesCalls gets all the calls that were made to DeviceGetMPSComputeRunningProcesses. +// Check the length with: +// +// len(mockedInterface.DeviceGetMPSComputeRunningProcessesCalls()) +func (mock *Interface) DeviceGetMPSComputeRunningProcessesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMPSComputeRunningProcesses.RLock() + calls = mock.calls.DeviceGetMPSComputeRunningProcesses + mock.lockDeviceGetMPSComputeRunningProcesses.RUnlock() + return calls +} + +// DeviceGetMarginTemperature calls DeviceGetMarginTemperatureFunc. +func (mock *Interface) DeviceGetMarginTemperature(device nvml.Device) (nvml.MarginTemperature, nvml.Return) { + if mock.DeviceGetMarginTemperatureFunc == nil { + panic("Interface.DeviceGetMarginTemperatureFunc: method is nil but Interface.DeviceGetMarginTemperature was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMarginTemperature.Lock() + mock.calls.DeviceGetMarginTemperature = append(mock.calls.DeviceGetMarginTemperature, callInfo) + mock.lockDeviceGetMarginTemperature.Unlock() + return mock.DeviceGetMarginTemperatureFunc(device) +} + +// DeviceGetMarginTemperatureCalls gets all the calls that were made to DeviceGetMarginTemperature. +// Check the length with: +// +// len(mockedInterface.DeviceGetMarginTemperatureCalls()) +func (mock *Interface) DeviceGetMarginTemperatureCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMarginTemperature.RLock() + calls = mock.calls.DeviceGetMarginTemperature + mock.lockDeviceGetMarginTemperature.RUnlock() + return calls +} + +// DeviceGetMaxClockInfo calls DeviceGetMaxClockInfoFunc. +func (mock *Interface) DeviceGetMaxClockInfo(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.DeviceGetMaxClockInfoFunc == nil { + panic("Interface.DeviceGetMaxClockInfoFunc: method is nil but Interface.DeviceGetMaxClockInfo was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + }{ + Device: device, + ClockType: clockType, + } + mock.lockDeviceGetMaxClockInfo.Lock() + mock.calls.DeviceGetMaxClockInfo = append(mock.calls.DeviceGetMaxClockInfo, callInfo) + mock.lockDeviceGetMaxClockInfo.Unlock() + return mock.DeviceGetMaxClockInfoFunc(device, clockType) +} + +// DeviceGetMaxClockInfoCalls gets all the calls that were made to DeviceGetMaxClockInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetMaxClockInfoCalls()) +func (mock *Interface) DeviceGetMaxClockInfoCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + } + mock.lockDeviceGetMaxClockInfo.RLock() + calls = mock.calls.DeviceGetMaxClockInfo + mock.lockDeviceGetMaxClockInfo.RUnlock() + return calls +} + +// DeviceGetMaxCustomerBoostClock calls DeviceGetMaxCustomerBoostClockFunc. +func (mock *Interface) DeviceGetMaxCustomerBoostClock(device nvml.Device, clockType nvml.ClockType) (uint32, nvml.Return) { + if mock.DeviceGetMaxCustomerBoostClockFunc == nil { + panic("Interface.DeviceGetMaxCustomerBoostClockFunc: method is nil but Interface.DeviceGetMaxCustomerBoostClock was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + }{ + Device: device, + ClockType: clockType, + } + mock.lockDeviceGetMaxCustomerBoostClock.Lock() + mock.calls.DeviceGetMaxCustomerBoostClock = append(mock.calls.DeviceGetMaxCustomerBoostClock, callInfo) + mock.lockDeviceGetMaxCustomerBoostClock.Unlock() + return mock.DeviceGetMaxCustomerBoostClockFunc(device, clockType) +} + +// DeviceGetMaxCustomerBoostClockCalls gets all the calls that were made to DeviceGetMaxCustomerBoostClock. +// Check the length with: +// +// len(mockedInterface.DeviceGetMaxCustomerBoostClockCalls()) +func (mock *Interface) DeviceGetMaxCustomerBoostClockCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + } + mock.lockDeviceGetMaxCustomerBoostClock.RLock() + calls = mock.calls.DeviceGetMaxCustomerBoostClock + mock.lockDeviceGetMaxCustomerBoostClock.RUnlock() + return calls +} + +// DeviceGetMaxMigDeviceCount calls DeviceGetMaxMigDeviceCountFunc. +func (mock *Interface) DeviceGetMaxMigDeviceCount(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMaxMigDeviceCountFunc == nil { + panic("Interface.DeviceGetMaxMigDeviceCountFunc: method is nil but Interface.DeviceGetMaxMigDeviceCount was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMaxMigDeviceCount.Lock() + mock.calls.DeviceGetMaxMigDeviceCount = append(mock.calls.DeviceGetMaxMigDeviceCount, callInfo) + mock.lockDeviceGetMaxMigDeviceCount.Unlock() + return mock.DeviceGetMaxMigDeviceCountFunc(device) +} + +// DeviceGetMaxMigDeviceCountCalls gets all the calls that were made to DeviceGetMaxMigDeviceCount. +// Check the length with: +// +// len(mockedInterface.DeviceGetMaxMigDeviceCountCalls()) +func (mock *Interface) DeviceGetMaxMigDeviceCountCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMaxMigDeviceCount.RLock() + calls = mock.calls.DeviceGetMaxMigDeviceCount + mock.lockDeviceGetMaxMigDeviceCount.RUnlock() + return calls +} + +// DeviceGetMaxPcieLinkGeneration calls DeviceGetMaxPcieLinkGenerationFunc. +func (mock *Interface) DeviceGetMaxPcieLinkGeneration(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMaxPcieLinkGenerationFunc == nil { + panic("Interface.DeviceGetMaxPcieLinkGenerationFunc: method is nil but Interface.DeviceGetMaxPcieLinkGeneration was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMaxPcieLinkGeneration.Lock() + mock.calls.DeviceGetMaxPcieLinkGeneration = append(mock.calls.DeviceGetMaxPcieLinkGeneration, callInfo) + mock.lockDeviceGetMaxPcieLinkGeneration.Unlock() + return mock.DeviceGetMaxPcieLinkGenerationFunc(device) +} + +// DeviceGetMaxPcieLinkGenerationCalls gets all the calls that were made to DeviceGetMaxPcieLinkGeneration. +// Check the length with: +// +// len(mockedInterface.DeviceGetMaxPcieLinkGenerationCalls()) +func (mock *Interface) DeviceGetMaxPcieLinkGenerationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMaxPcieLinkGeneration.RLock() + calls = mock.calls.DeviceGetMaxPcieLinkGeneration + mock.lockDeviceGetMaxPcieLinkGeneration.RUnlock() + return calls +} + +// DeviceGetMaxPcieLinkWidth calls DeviceGetMaxPcieLinkWidthFunc. +func (mock *Interface) DeviceGetMaxPcieLinkWidth(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMaxPcieLinkWidthFunc == nil { + panic("Interface.DeviceGetMaxPcieLinkWidthFunc: method is nil but Interface.DeviceGetMaxPcieLinkWidth was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMaxPcieLinkWidth.Lock() + mock.calls.DeviceGetMaxPcieLinkWidth = append(mock.calls.DeviceGetMaxPcieLinkWidth, callInfo) + mock.lockDeviceGetMaxPcieLinkWidth.Unlock() + return mock.DeviceGetMaxPcieLinkWidthFunc(device) +} + +// DeviceGetMaxPcieLinkWidthCalls gets all the calls that were made to DeviceGetMaxPcieLinkWidth. +// Check the length with: +// +// len(mockedInterface.DeviceGetMaxPcieLinkWidthCalls()) +func (mock *Interface) DeviceGetMaxPcieLinkWidthCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMaxPcieLinkWidth.RLock() + calls = mock.calls.DeviceGetMaxPcieLinkWidth + mock.lockDeviceGetMaxPcieLinkWidth.RUnlock() + return calls +} + +// DeviceGetMemClkMinMaxVfOffset calls DeviceGetMemClkMinMaxVfOffsetFunc. +func (mock *Interface) DeviceGetMemClkMinMaxVfOffset(device nvml.Device) (int, int, nvml.Return) { + if mock.DeviceGetMemClkMinMaxVfOffsetFunc == nil { + panic("Interface.DeviceGetMemClkMinMaxVfOffsetFunc: method is nil but Interface.DeviceGetMemClkMinMaxVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMemClkMinMaxVfOffset.Lock() + mock.calls.DeviceGetMemClkMinMaxVfOffset = append(mock.calls.DeviceGetMemClkMinMaxVfOffset, callInfo) + mock.lockDeviceGetMemClkMinMaxVfOffset.Unlock() + return mock.DeviceGetMemClkMinMaxVfOffsetFunc(device) +} + +// DeviceGetMemClkMinMaxVfOffsetCalls gets all the calls that were made to DeviceGetMemClkMinMaxVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemClkMinMaxVfOffsetCalls()) +func (mock *Interface) DeviceGetMemClkMinMaxVfOffsetCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMemClkMinMaxVfOffset.RLock() + calls = mock.calls.DeviceGetMemClkMinMaxVfOffset + mock.lockDeviceGetMemClkMinMaxVfOffset.RUnlock() + return calls +} + +// DeviceGetMemClkVfOffset calls DeviceGetMemClkVfOffsetFunc. +func (mock *Interface) DeviceGetMemClkVfOffset(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMemClkVfOffsetFunc == nil { + panic("Interface.DeviceGetMemClkVfOffsetFunc: method is nil but Interface.DeviceGetMemClkVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMemClkVfOffset.Lock() + mock.calls.DeviceGetMemClkVfOffset = append(mock.calls.DeviceGetMemClkVfOffset, callInfo) + mock.lockDeviceGetMemClkVfOffset.Unlock() + return mock.DeviceGetMemClkVfOffsetFunc(device) +} + +// DeviceGetMemClkVfOffsetCalls gets all the calls that were made to DeviceGetMemClkVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemClkVfOffsetCalls()) +func (mock *Interface) DeviceGetMemClkVfOffsetCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMemClkVfOffset.RLock() + calls = mock.calls.DeviceGetMemClkVfOffset + mock.lockDeviceGetMemClkVfOffset.RUnlock() + return calls +} + +// DeviceGetMemoryAffinity calls DeviceGetMemoryAffinityFunc. +func (mock *Interface) DeviceGetMemoryAffinity(device nvml.Device, n int, affinityScope nvml.AffinityScope) ([]uint, nvml.Return) { + if mock.DeviceGetMemoryAffinityFunc == nil { + panic("Interface.DeviceGetMemoryAffinityFunc: method is nil but Interface.DeviceGetMemoryAffinity was just called") + } + callInfo := struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope + }{ + Device: device, + N: n, + AffinityScope: affinityScope, + } + mock.lockDeviceGetMemoryAffinity.Lock() + mock.calls.DeviceGetMemoryAffinity = append(mock.calls.DeviceGetMemoryAffinity, callInfo) + mock.lockDeviceGetMemoryAffinity.Unlock() + return mock.DeviceGetMemoryAffinityFunc(device, n, affinityScope) +} + +// DeviceGetMemoryAffinityCalls gets all the calls that were made to DeviceGetMemoryAffinity. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemoryAffinityCalls()) +func (mock *Interface) DeviceGetMemoryAffinityCalls() []struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope +} { + var calls []struct { + Device nvml.Device + N int + AffinityScope nvml.AffinityScope + } + mock.lockDeviceGetMemoryAffinity.RLock() + calls = mock.calls.DeviceGetMemoryAffinity + mock.lockDeviceGetMemoryAffinity.RUnlock() + return calls +} + +// DeviceGetMemoryBusWidth calls DeviceGetMemoryBusWidthFunc. +func (mock *Interface) DeviceGetMemoryBusWidth(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetMemoryBusWidthFunc == nil { + panic("Interface.DeviceGetMemoryBusWidthFunc: method is nil but Interface.DeviceGetMemoryBusWidth was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMemoryBusWidth.Lock() + mock.calls.DeviceGetMemoryBusWidth = append(mock.calls.DeviceGetMemoryBusWidth, callInfo) + mock.lockDeviceGetMemoryBusWidth.Unlock() + return mock.DeviceGetMemoryBusWidthFunc(device) +} + +// DeviceGetMemoryBusWidthCalls gets all the calls that were made to DeviceGetMemoryBusWidth. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemoryBusWidthCalls()) +func (mock *Interface) DeviceGetMemoryBusWidthCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMemoryBusWidth.RLock() + calls = mock.calls.DeviceGetMemoryBusWidth + mock.lockDeviceGetMemoryBusWidth.RUnlock() + return calls +} + +// DeviceGetMemoryErrorCounter calls DeviceGetMemoryErrorCounterFunc. +func (mock *Interface) DeviceGetMemoryErrorCounter(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType, memoryLocation nvml.MemoryLocation) (uint64, nvml.Return) { + if mock.DeviceGetMemoryErrorCounterFunc == nil { + panic("Interface.DeviceGetMemoryErrorCounterFunc: method is nil but Interface.DeviceGetMemoryErrorCounter was just called") + } + callInfo := struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation + }{ + Device: device, + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + MemoryLocation: memoryLocation, + } + mock.lockDeviceGetMemoryErrorCounter.Lock() + mock.calls.DeviceGetMemoryErrorCounter = append(mock.calls.DeviceGetMemoryErrorCounter, callInfo) + mock.lockDeviceGetMemoryErrorCounter.Unlock() + return mock.DeviceGetMemoryErrorCounterFunc(device, memoryErrorType, eccCounterType, memoryLocation) +} + +// DeviceGetMemoryErrorCounterCalls gets all the calls that were made to DeviceGetMemoryErrorCounter. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemoryErrorCounterCalls()) +func (mock *Interface) DeviceGetMemoryErrorCounterCalls() []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation +} { + var calls []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + MemoryLocation nvml.MemoryLocation + } + mock.lockDeviceGetMemoryErrorCounter.RLock() + calls = mock.calls.DeviceGetMemoryErrorCounter + mock.lockDeviceGetMemoryErrorCounter.RUnlock() + return calls +} + +// DeviceGetMemoryInfo calls DeviceGetMemoryInfoFunc. +func (mock *Interface) DeviceGetMemoryInfo(device nvml.Device) (nvml.Memory, nvml.Return) { + if mock.DeviceGetMemoryInfoFunc == nil { + panic("Interface.DeviceGetMemoryInfoFunc: method is nil but Interface.DeviceGetMemoryInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMemoryInfo.Lock() + mock.calls.DeviceGetMemoryInfo = append(mock.calls.DeviceGetMemoryInfo, callInfo) + mock.lockDeviceGetMemoryInfo.Unlock() + return mock.DeviceGetMemoryInfoFunc(device) +} + +// DeviceGetMemoryInfoCalls gets all the calls that were made to DeviceGetMemoryInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemoryInfoCalls()) +func (mock *Interface) DeviceGetMemoryInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMemoryInfo.RLock() + calls = mock.calls.DeviceGetMemoryInfo + mock.lockDeviceGetMemoryInfo.RUnlock() + return calls +} + +// DeviceGetMemoryInfo_v2 calls DeviceGetMemoryInfo_v2Func. +func (mock *Interface) DeviceGetMemoryInfo_v2(device nvml.Device) (nvml.Memory_v2, nvml.Return) { + if mock.DeviceGetMemoryInfo_v2Func == nil { + panic("Interface.DeviceGetMemoryInfo_v2Func: method is nil but Interface.DeviceGetMemoryInfo_v2 was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMemoryInfo_v2.Lock() + mock.calls.DeviceGetMemoryInfo_v2 = append(mock.calls.DeviceGetMemoryInfo_v2, callInfo) + mock.lockDeviceGetMemoryInfo_v2.Unlock() + return mock.DeviceGetMemoryInfo_v2Func(device) +} + +// DeviceGetMemoryInfo_v2Calls gets all the calls that were made to DeviceGetMemoryInfo_v2. +// Check the length with: +// +// len(mockedInterface.DeviceGetMemoryInfo_v2Calls()) +func (mock *Interface) DeviceGetMemoryInfo_v2Calls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMemoryInfo_v2.RLock() + calls = mock.calls.DeviceGetMemoryInfo_v2 + mock.lockDeviceGetMemoryInfo_v2.RUnlock() + return calls +} + +// DeviceGetMigDeviceHandleByIndex calls DeviceGetMigDeviceHandleByIndexFunc. +func (mock *Interface) DeviceGetMigDeviceHandleByIndex(device nvml.Device, n int) (nvml.Device, nvml.Return) { + if mock.DeviceGetMigDeviceHandleByIndexFunc == nil { + panic("Interface.DeviceGetMigDeviceHandleByIndexFunc: method is nil but Interface.DeviceGetMigDeviceHandleByIndex was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetMigDeviceHandleByIndex.Lock() + mock.calls.DeviceGetMigDeviceHandleByIndex = append(mock.calls.DeviceGetMigDeviceHandleByIndex, callInfo) + mock.lockDeviceGetMigDeviceHandleByIndex.Unlock() + return mock.DeviceGetMigDeviceHandleByIndexFunc(device, n) +} + +// DeviceGetMigDeviceHandleByIndexCalls gets all the calls that were made to DeviceGetMigDeviceHandleByIndex. +// Check the length with: +// +// len(mockedInterface.DeviceGetMigDeviceHandleByIndexCalls()) +func (mock *Interface) DeviceGetMigDeviceHandleByIndexCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetMigDeviceHandleByIndex.RLock() + calls = mock.calls.DeviceGetMigDeviceHandleByIndex + mock.lockDeviceGetMigDeviceHandleByIndex.RUnlock() + return calls +} + +// DeviceGetMigMode calls DeviceGetMigModeFunc. +func (mock *Interface) DeviceGetMigMode(device nvml.Device) (int, int, nvml.Return) { + if mock.DeviceGetMigModeFunc == nil { + panic("Interface.DeviceGetMigModeFunc: method is nil but Interface.DeviceGetMigMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMigMode.Lock() + mock.calls.DeviceGetMigMode = append(mock.calls.DeviceGetMigMode, callInfo) + mock.lockDeviceGetMigMode.Unlock() + return mock.DeviceGetMigModeFunc(device) +} + +// DeviceGetMigModeCalls gets all the calls that were made to DeviceGetMigMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetMigModeCalls()) +func (mock *Interface) DeviceGetMigModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMigMode.RLock() + calls = mock.calls.DeviceGetMigMode + mock.lockDeviceGetMigMode.RUnlock() + return calls +} + +// DeviceGetMinMaxClockOfPState calls DeviceGetMinMaxClockOfPStateFunc. +func (mock *Interface) DeviceGetMinMaxClockOfPState(device nvml.Device, clockType nvml.ClockType, pstates nvml.Pstates) (uint32, uint32, nvml.Return) { + if mock.DeviceGetMinMaxClockOfPStateFunc == nil { + panic("Interface.DeviceGetMinMaxClockOfPStateFunc: method is nil but Interface.DeviceGetMinMaxClockOfPState was just called") + } + callInfo := struct { + Device nvml.Device + ClockType nvml.ClockType + Pstates nvml.Pstates + }{ + Device: device, + ClockType: clockType, + Pstates: pstates, + } + mock.lockDeviceGetMinMaxClockOfPState.Lock() + mock.calls.DeviceGetMinMaxClockOfPState = append(mock.calls.DeviceGetMinMaxClockOfPState, callInfo) + mock.lockDeviceGetMinMaxClockOfPState.Unlock() + return mock.DeviceGetMinMaxClockOfPStateFunc(device, clockType, pstates) +} + +// DeviceGetMinMaxClockOfPStateCalls gets all the calls that were made to DeviceGetMinMaxClockOfPState. +// Check the length with: +// +// len(mockedInterface.DeviceGetMinMaxClockOfPStateCalls()) +func (mock *Interface) DeviceGetMinMaxClockOfPStateCalls() []struct { + Device nvml.Device + ClockType nvml.ClockType + Pstates nvml.Pstates +} { + var calls []struct { + Device nvml.Device + ClockType nvml.ClockType + Pstates nvml.Pstates + } + mock.lockDeviceGetMinMaxClockOfPState.RLock() + calls = mock.calls.DeviceGetMinMaxClockOfPState + mock.lockDeviceGetMinMaxClockOfPState.RUnlock() + return calls +} + +// DeviceGetMinMaxFanSpeed calls DeviceGetMinMaxFanSpeedFunc. +func (mock *Interface) DeviceGetMinMaxFanSpeed(device nvml.Device) (int, int, nvml.Return) { + if mock.DeviceGetMinMaxFanSpeedFunc == nil { + panic("Interface.DeviceGetMinMaxFanSpeedFunc: method is nil but Interface.DeviceGetMinMaxFanSpeed was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMinMaxFanSpeed.Lock() + mock.calls.DeviceGetMinMaxFanSpeed = append(mock.calls.DeviceGetMinMaxFanSpeed, callInfo) + mock.lockDeviceGetMinMaxFanSpeed.Unlock() + return mock.DeviceGetMinMaxFanSpeedFunc(device) +} + +// DeviceGetMinMaxFanSpeedCalls gets all the calls that were made to DeviceGetMinMaxFanSpeed. +// Check the length with: +// +// len(mockedInterface.DeviceGetMinMaxFanSpeedCalls()) +func (mock *Interface) DeviceGetMinMaxFanSpeedCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMinMaxFanSpeed.RLock() + calls = mock.calls.DeviceGetMinMaxFanSpeed + mock.lockDeviceGetMinMaxFanSpeed.RUnlock() + return calls +} + +// DeviceGetMinorNumber calls DeviceGetMinorNumberFunc. +func (mock *Interface) DeviceGetMinorNumber(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMinorNumberFunc == nil { + panic("Interface.DeviceGetMinorNumberFunc: method is nil but Interface.DeviceGetMinorNumber was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMinorNumber.Lock() + mock.calls.DeviceGetMinorNumber = append(mock.calls.DeviceGetMinorNumber, callInfo) + mock.lockDeviceGetMinorNumber.Unlock() + return mock.DeviceGetMinorNumberFunc(device) +} + +// DeviceGetMinorNumberCalls gets all the calls that were made to DeviceGetMinorNumber. +// Check the length with: +// +// len(mockedInterface.DeviceGetMinorNumberCalls()) +func (mock *Interface) DeviceGetMinorNumberCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMinorNumber.RLock() + calls = mock.calls.DeviceGetMinorNumber + mock.lockDeviceGetMinorNumber.RUnlock() + return calls +} + +// DeviceGetModuleId calls DeviceGetModuleIdFunc. +func (mock *Interface) DeviceGetModuleId(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetModuleIdFunc == nil { + panic("Interface.DeviceGetModuleIdFunc: method is nil but Interface.DeviceGetModuleId was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetModuleId.Lock() + mock.calls.DeviceGetModuleId = append(mock.calls.DeviceGetModuleId, callInfo) + mock.lockDeviceGetModuleId.Unlock() + return mock.DeviceGetModuleIdFunc(device) +} + +// DeviceGetModuleIdCalls gets all the calls that were made to DeviceGetModuleId. +// Check the length with: +// +// len(mockedInterface.DeviceGetModuleIdCalls()) +func (mock *Interface) DeviceGetModuleIdCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetModuleId.RLock() + calls = mock.calls.DeviceGetModuleId + mock.lockDeviceGetModuleId.RUnlock() + return calls +} + +// DeviceGetMultiGpuBoard calls DeviceGetMultiGpuBoardFunc. +func (mock *Interface) DeviceGetMultiGpuBoard(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetMultiGpuBoardFunc == nil { + panic("Interface.DeviceGetMultiGpuBoardFunc: method is nil but Interface.DeviceGetMultiGpuBoard was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetMultiGpuBoard.Lock() + mock.calls.DeviceGetMultiGpuBoard = append(mock.calls.DeviceGetMultiGpuBoard, callInfo) + mock.lockDeviceGetMultiGpuBoard.Unlock() + return mock.DeviceGetMultiGpuBoardFunc(device) +} + +// DeviceGetMultiGpuBoardCalls gets all the calls that were made to DeviceGetMultiGpuBoard. +// Check the length with: +// +// len(mockedInterface.DeviceGetMultiGpuBoardCalls()) +func (mock *Interface) DeviceGetMultiGpuBoardCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetMultiGpuBoard.RLock() + calls = mock.calls.DeviceGetMultiGpuBoard + mock.lockDeviceGetMultiGpuBoard.RUnlock() + return calls +} + +// DeviceGetName calls DeviceGetNameFunc. +func (mock *Interface) DeviceGetName(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetNameFunc == nil { + panic("Interface.DeviceGetNameFunc: method is nil but Interface.DeviceGetName was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetName.Lock() + mock.calls.DeviceGetName = append(mock.calls.DeviceGetName, callInfo) + mock.lockDeviceGetName.Unlock() + return mock.DeviceGetNameFunc(device) +} + +// DeviceGetNameCalls gets all the calls that were made to DeviceGetName. +// Check the length with: +// +// len(mockedInterface.DeviceGetNameCalls()) +func (mock *Interface) DeviceGetNameCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetName.RLock() + calls = mock.calls.DeviceGetName + mock.lockDeviceGetName.RUnlock() + return calls +} + +// DeviceGetNumFans calls DeviceGetNumFansFunc. +func (mock *Interface) DeviceGetNumFans(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetNumFansFunc == nil { + panic("Interface.DeviceGetNumFansFunc: method is nil but Interface.DeviceGetNumFans was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNumFans.Lock() + mock.calls.DeviceGetNumFans = append(mock.calls.DeviceGetNumFans, callInfo) + mock.lockDeviceGetNumFans.Unlock() + return mock.DeviceGetNumFansFunc(device) +} + +// DeviceGetNumFansCalls gets all the calls that were made to DeviceGetNumFans. +// Check the length with: +// +// len(mockedInterface.DeviceGetNumFansCalls()) +func (mock *Interface) DeviceGetNumFansCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNumFans.RLock() + calls = mock.calls.DeviceGetNumFans + mock.lockDeviceGetNumFans.RUnlock() + return calls +} + +// DeviceGetNumGpuCores calls DeviceGetNumGpuCoresFunc. +func (mock *Interface) DeviceGetNumGpuCores(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetNumGpuCoresFunc == nil { + panic("Interface.DeviceGetNumGpuCoresFunc: method is nil but Interface.DeviceGetNumGpuCores was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNumGpuCores.Lock() + mock.calls.DeviceGetNumGpuCores = append(mock.calls.DeviceGetNumGpuCores, callInfo) + mock.lockDeviceGetNumGpuCores.Unlock() + return mock.DeviceGetNumGpuCoresFunc(device) +} + +// DeviceGetNumGpuCoresCalls gets all the calls that were made to DeviceGetNumGpuCores. +// Check the length with: +// +// len(mockedInterface.DeviceGetNumGpuCoresCalls()) +func (mock *Interface) DeviceGetNumGpuCoresCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNumGpuCores.RLock() + calls = mock.calls.DeviceGetNumGpuCores + mock.lockDeviceGetNumGpuCores.RUnlock() + return calls +} + +// DeviceGetNumaNodeId calls DeviceGetNumaNodeIdFunc. +func (mock *Interface) DeviceGetNumaNodeId(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetNumaNodeIdFunc == nil { + panic("Interface.DeviceGetNumaNodeIdFunc: method is nil but Interface.DeviceGetNumaNodeId was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNumaNodeId.Lock() + mock.calls.DeviceGetNumaNodeId = append(mock.calls.DeviceGetNumaNodeId, callInfo) + mock.lockDeviceGetNumaNodeId.Unlock() + return mock.DeviceGetNumaNodeIdFunc(device) +} + +// DeviceGetNumaNodeIdCalls gets all the calls that were made to DeviceGetNumaNodeId. +// Check the length with: +// +// len(mockedInterface.DeviceGetNumaNodeIdCalls()) +func (mock *Interface) DeviceGetNumaNodeIdCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNumaNodeId.RLock() + calls = mock.calls.DeviceGetNumaNodeId + mock.lockDeviceGetNumaNodeId.RUnlock() + return calls +} + +// DeviceGetNvLinkCapability calls DeviceGetNvLinkCapabilityFunc. +func (mock *Interface) DeviceGetNvLinkCapability(device nvml.Device, n int, nvLinkCapability nvml.NvLinkCapability) (uint32, nvml.Return) { + if mock.DeviceGetNvLinkCapabilityFunc == nil { + panic("Interface.DeviceGetNvLinkCapabilityFunc: method is nil but Interface.DeviceGetNvLinkCapability was just called") + } + callInfo := struct { + Device nvml.Device + N int + NvLinkCapability nvml.NvLinkCapability + }{ + Device: device, + N: n, + NvLinkCapability: nvLinkCapability, + } + mock.lockDeviceGetNvLinkCapability.Lock() + mock.calls.DeviceGetNvLinkCapability = append(mock.calls.DeviceGetNvLinkCapability, callInfo) + mock.lockDeviceGetNvLinkCapability.Unlock() + return mock.DeviceGetNvLinkCapabilityFunc(device, n, nvLinkCapability) +} + +// DeviceGetNvLinkCapabilityCalls gets all the calls that were made to DeviceGetNvLinkCapability. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkCapabilityCalls()) +func (mock *Interface) DeviceGetNvLinkCapabilityCalls() []struct { + Device nvml.Device + N int + NvLinkCapability nvml.NvLinkCapability +} { + var calls []struct { + Device nvml.Device + N int + NvLinkCapability nvml.NvLinkCapability + } + mock.lockDeviceGetNvLinkCapability.RLock() + calls = mock.calls.DeviceGetNvLinkCapability + mock.lockDeviceGetNvLinkCapability.RUnlock() + return calls +} + +// DeviceGetNvLinkErrorCounter calls DeviceGetNvLinkErrorCounterFunc. +func (mock *Interface) DeviceGetNvLinkErrorCounter(device nvml.Device, n int, nvLinkErrorCounter nvml.NvLinkErrorCounter) (uint64, nvml.Return) { + if mock.DeviceGetNvLinkErrorCounterFunc == nil { + panic("Interface.DeviceGetNvLinkErrorCounterFunc: method is nil but Interface.DeviceGetNvLinkErrorCounter was just called") + } + callInfo := struct { + Device nvml.Device + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter + }{ + Device: device, + N: n, + NvLinkErrorCounter: nvLinkErrorCounter, + } + mock.lockDeviceGetNvLinkErrorCounter.Lock() + mock.calls.DeviceGetNvLinkErrorCounter = append(mock.calls.DeviceGetNvLinkErrorCounter, callInfo) + mock.lockDeviceGetNvLinkErrorCounter.Unlock() + return mock.DeviceGetNvLinkErrorCounterFunc(device, n, nvLinkErrorCounter) +} + +// DeviceGetNvLinkErrorCounterCalls gets all the calls that were made to DeviceGetNvLinkErrorCounter. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkErrorCounterCalls()) +func (mock *Interface) DeviceGetNvLinkErrorCounterCalls() []struct { + Device nvml.Device + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter +} { + var calls []struct { + Device nvml.Device + N int + NvLinkErrorCounter nvml.NvLinkErrorCounter + } + mock.lockDeviceGetNvLinkErrorCounter.RLock() + calls = mock.calls.DeviceGetNvLinkErrorCounter + mock.lockDeviceGetNvLinkErrorCounter.RUnlock() + return calls +} + +// DeviceGetNvLinkInfo calls DeviceGetNvLinkInfoFunc. +func (mock *Interface) DeviceGetNvLinkInfo(device nvml.Device) nvml.NvLinkInfoHandler { + if mock.DeviceGetNvLinkInfoFunc == nil { + panic("Interface.DeviceGetNvLinkInfoFunc: method is nil but Interface.DeviceGetNvLinkInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNvLinkInfo.Lock() + mock.calls.DeviceGetNvLinkInfo = append(mock.calls.DeviceGetNvLinkInfo, callInfo) + mock.lockDeviceGetNvLinkInfo.Unlock() + return mock.DeviceGetNvLinkInfoFunc(device) +} + +// DeviceGetNvLinkInfoCalls gets all the calls that were made to DeviceGetNvLinkInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkInfoCalls()) +func (mock *Interface) DeviceGetNvLinkInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNvLinkInfo.RLock() + calls = mock.calls.DeviceGetNvLinkInfo + mock.lockDeviceGetNvLinkInfo.RUnlock() + return calls +} + +// DeviceGetNvLinkRemoteDeviceType calls DeviceGetNvLinkRemoteDeviceTypeFunc. +func (mock *Interface) DeviceGetNvLinkRemoteDeviceType(device nvml.Device, n int) (nvml.IntNvLinkDeviceType, nvml.Return) { + if mock.DeviceGetNvLinkRemoteDeviceTypeFunc == nil { + panic("Interface.DeviceGetNvLinkRemoteDeviceTypeFunc: method is nil but Interface.DeviceGetNvLinkRemoteDeviceType was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetNvLinkRemoteDeviceType.Lock() + mock.calls.DeviceGetNvLinkRemoteDeviceType = append(mock.calls.DeviceGetNvLinkRemoteDeviceType, callInfo) + mock.lockDeviceGetNvLinkRemoteDeviceType.Unlock() + return mock.DeviceGetNvLinkRemoteDeviceTypeFunc(device, n) +} + +// DeviceGetNvLinkRemoteDeviceTypeCalls gets all the calls that were made to DeviceGetNvLinkRemoteDeviceType. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkRemoteDeviceTypeCalls()) +func (mock *Interface) DeviceGetNvLinkRemoteDeviceTypeCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetNvLinkRemoteDeviceType.RLock() + calls = mock.calls.DeviceGetNvLinkRemoteDeviceType + mock.lockDeviceGetNvLinkRemoteDeviceType.RUnlock() + return calls +} + +// DeviceGetNvLinkRemotePciInfo calls DeviceGetNvLinkRemotePciInfoFunc. +func (mock *Interface) DeviceGetNvLinkRemotePciInfo(device nvml.Device, n int) (nvml.PciInfo, nvml.Return) { + if mock.DeviceGetNvLinkRemotePciInfoFunc == nil { + panic("Interface.DeviceGetNvLinkRemotePciInfoFunc: method is nil but Interface.DeviceGetNvLinkRemotePciInfo was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetNvLinkRemotePciInfo.Lock() + mock.calls.DeviceGetNvLinkRemotePciInfo = append(mock.calls.DeviceGetNvLinkRemotePciInfo, callInfo) + mock.lockDeviceGetNvLinkRemotePciInfo.Unlock() + return mock.DeviceGetNvLinkRemotePciInfoFunc(device, n) +} + +// DeviceGetNvLinkRemotePciInfoCalls gets all the calls that were made to DeviceGetNvLinkRemotePciInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkRemotePciInfoCalls()) +func (mock *Interface) DeviceGetNvLinkRemotePciInfoCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetNvLinkRemotePciInfo.RLock() + calls = mock.calls.DeviceGetNvLinkRemotePciInfo + mock.lockDeviceGetNvLinkRemotePciInfo.RUnlock() + return calls +} + +// DeviceGetNvLinkState calls DeviceGetNvLinkStateFunc. +func (mock *Interface) DeviceGetNvLinkState(device nvml.Device, n int) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetNvLinkStateFunc == nil { + panic("Interface.DeviceGetNvLinkStateFunc: method is nil but Interface.DeviceGetNvLinkState was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetNvLinkState.Lock() + mock.calls.DeviceGetNvLinkState = append(mock.calls.DeviceGetNvLinkState, callInfo) + mock.lockDeviceGetNvLinkState.Unlock() + return mock.DeviceGetNvLinkStateFunc(device, n) +} + +// DeviceGetNvLinkStateCalls gets all the calls that were made to DeviceGetNvLinkState. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkStateCalls()) +func (mock *Interface) DeviceGetNvLinkStateCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetNvLinkState.RLock() + calls = mock.calls.DeviceGetNvLinkState + mock.lockDeviceGetNvLinkState.RUnlock() + return calls +} + +// DeviceGetNvLinkUtilizationControl calls DeviceGetNvLinkUtilizationControlFunc. +func (mock *Interface) DeviceGetNvLinkUtilizationControl(device nvml.Device, n1 int, n2 int) (nvml.NvLinkUtilizationControl, nvml.Return) { + if mock.DeviceGetNvLinkUtilizationControlFunc == nil { + panic("Interface.DeviceGetNvLinkUtilizationControlFunc: method is nil but Interface.DeviceGetNvLinkUtilizationControl was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + }{ + Device: device, + N1: n1, + N2: n2, + } + mock.lockDeviceGetNvLinkUtilizationControl.Lock() + mock.calls.DeviceGetNvLinkUtilizationControl = append(mock.calls.DeviceGetNvLinkUtilizationControl, callInfo) + mock.lockDeviceGetNvLinkUtilizationControl.Unlock() + return mock.DeviceGetNvLinkUtilizationControlFunc(device, n1, n2) +} + +// DeviceGetNvLinkUtilizationControlCalls gets all the calls that were made to DeviceGetNvLinkUtilizationControl. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkUtilizationControlCalls()) +func (mock *Interface) DeviceGetNvLinkUtilizationControlCalls() []struct { + Device nvml.Device + N1 int + N2 int +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + } + mock.lockDeviceGetNvLinkUtilizationControl.RLock() + calls = mock.calls.DeviceGetNvLinkUtilizationControl + mock.lockDeviceGetNvLinkUtilizationControl.RUnlock() + return calls +} + +// DeviceGetNvLinkUtilizationCounter calls DeviceGetNvLinkUtilizationCounterFunc. +func (mock *Interface) DeviceGetNvLinkUtilizationCounter(device nvml.Device, n1 int, n2 int) (uint64, uint64, nvml.Return) { + if mock.DeviceGetNvLinkUtilizationCounterFunc == nil { + panic("Interface.DeviceGetNvLinkUtilizationCounterFunc: method is nil but Interface.DeviceGetNvLinkUtilizationCounter was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + }{ + Device: device, + N1: n1, + N2: n2, + } + mock.lockDeviceGetNvLinkUtilizationCounter.Lock() + mock.calls.DeviceGetNvLinkUtilizationCounter = append(mock.calls.DeviceGetNvLinkUtilizationCounter, callInfo) + mock.lockDeviceGetNvLinkUtilizationCounter.Unlock() + return mock.DeviceGetNvLinkUtilizationCounterFunc(device, n1, n2) +} + +// DeviceGetNvLinkUtilizationCounterCalls gets all the calls that were made to DeviceGetNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkUtilizationCounterCalls()) +func (mock *Interface) DeviceGetNvLinkUtilizationCounterCalls() []struct { + Device nvml.Device + N1 int + N2 int +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + } + mock.lockDeviceGetNvLinkUtilizationCounter.RLock() + calls = mock.calls.DeviceGetNvLinkUtilizationCounter + mock.lockDeviceGetNvLinkUtilizationCounter.RUnlock() + return calls +} + +// DeviceGetNvLinkVersion calls DeviceGetNvLinkVersionFunc. +func (mock *Interface) DeviceGetNvLinkVersion(device nvml.Device, n int) (uint32, nvml.Return) { + if mock.DeviceGetNvLinkVersionFunc == nil { + panic("Interface.DeviceGetNvLinkVersionFunc: method is nil but Interface.DeviceGetNvLinkVersion was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetNvLinkVersion.Lock() + mock.calls.DeviceGetNvLinkVersion = append(mock.calls.DeviceGetNvLinkVersion, callInfo) + mock.lockDeviceGetNvLinkVersion.Unlock() + return mock.DeviceGetNvLinkVersionFunc(device, n) +} + +// DeviceGetNvLinkVersionCalls gets all the calls that were made to DeviceGetNvLinkVersion. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvLinkVersionCalls()) +func (mock *Interface) DeviceGetNvLinkVersionCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetNvLinkVersion.RLock() + calls = mock.calls.DeviceGetNvLinkVersion + mock.lockDeviceGetNvLinkVersion.RUnlock() + return calls +} + +// DeviceGetNvlinkBwMode calls DeviceGetNvlinkBwModeFunc. +func (mock *Interface) DeviceGetNvlinkBwMode(device nvml.Device) (nvml.NvlinkGetBwMode, nvml.Return) { + if mock.DeviceGetNvlinkBwModeFunc == nil { + panic("Interface.DeviceGetNvlinkBwModeFunc: method is nil but Interface.DeviceGetNvlinkBwMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNvlinkBwMode.Lock() + mock.calls.DeviceGetNvlinkBwMode = append(mock.calls.DeviceGetNvlinkBwMode, callInfo) + mock.lockDeviceGetNvlinkBwMode.Unlock() + return mock.DeviceGetNvlinkBwModeFunc(device) +} + +// DeviceGetNvlinkBwModeCalls gets all the calls that were made to DeviceGetNvlinkBwMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvlinkBwModeCalls()) +func (mock *Interface) DeviceGetNvlinkBwModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNvlinkBwMode.RLock() + calls = mock.calls.DeviceGetNvlinkBwMode + mock.lockDeviceGetNvlinkBwMode.RUnlock() + return calls +} + +// DeviceGetNvlinkSupportedBwModes calls DeviceGetNvlinkSupportedBwModesFunc. +func (mock *Interface) DeviceGetNvlinkSupportedBwModes(device nvml.Device) (nvml.NvlinkSupportedBwModes, nvml.Return) { + if mock.DeviceGetNvlinkSupportedBwModesFunc == nil { + panic("Interface.DeviceGetNvlinkSupportedBwModesFunc: method is nil but Interface.DeviceGetNvlinkSupportedBwModes was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetNvlinkSupportedBwModes.Lock() + mock.calls.DeviceGetNvlinkSupportedBwModes = append(mock.calls.DeviceGetNvlinkSupportedBwModes, callInfo) + mock.lockDeviceGetNvlinkSupportedBwModes.Unlock() + return mock.DeviceGetNvlinkSupportedBwModesFunc(device) +} + +// DeviceGetNvlinkSupportedBwModesCalls gets all the calls that were made to DeviceGetNvlinkSupportedBwModes. +// Check the length with: +// +// len(mockedInterface.DeviceGetNvlinkSupportedBwModesCalls()) +func (mock *Interface) DeviceGetNvlinkSupportedBwModesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetNvlinkSupportedBwModes.RLock() + calls = mock.calls.DeviceGetNvlinkSupportedBwModes + mock.lockDeviceGetNvlinkSupportedBwModes.RUnlock() + return calls +} + +// DeviceGetOfaUtilization calls DeviceGetOfaUtilizationFunc. +func (mock *Interface) DeviceGetOfaUtilization(device nvml.Device) (uint32, uint32, nvml.Return) { + if mock.DeviceGetOfaUtilizationFunc == nil { + panic("Interface.DeviceGetOfaUtilizationFunc: method is nil but Interface.DeviceGetOfaUtilization was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetOfaUtilization.Lock() + mock.calls.DeviceGetOfaUtilization = append(mock.calls.DeviceGetOfaUtilization, callInfo) + mock.lockDeviceGetOfaUtilization.Unlock() + return mock.DeviceGetOfaUtilizationFunc(device) +} + +// DeviceGetOfaUtilizationCalls gets all the calls that were made to DeviceGetOfaUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetOfaUtilizationCalls()) +func (mock *Interface) DeviceGetOfaUtilizationCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetOfaUtilization.RLock() + calls = mock.calls.DeviceGetOfaUtilization + mock.lockDeviceGetOfaUtilization.RUnlock() + return calls +} + +// DeviceGetP2PStatus calls DeviceGetP2PStatusFunc. +func (mock *Interface) DeviceGetP2PStatus(device1 nvml.Device, device2 nvml.Device, gpuP2PCapsIndex nvml.GpuP2PCapsIndex) (nvml.GpuP2PStatus, nvml.Return) { + if mock.DeviceGetP2PStatusFunc == nil { + panic("Interface.DeviceGetP2PStatusFunc: method is nil but Interface.DeviceGetP2PStatus was just called") + } + callInfo := struct { + Device1 nvml.Device + Device2 nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + }{ + Device1: device1, + Device2: device2, + GpuP2PCapsIndex: gpuP2PCapsIndex, + } + mock.lockDeviceGetP2PStatus.Lock() + mock.calls.DeviceGetP2PStatus = append(mock.calls.DeviceGetP2PStatus, callInfo) + mock.lockDeviceGetP2PStatus.Unlock() + return mock.DeviceGetP2PStatusFunc(device1, device2, gpuP2PCapsIndex) +} + +// DeviceGetP2PStatusCalls gets all the calls that were made to DeviceGetP2PStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetP2PStatusCalls()) +func (mock *Interface) DeviceGetP2PStatusCalls() []struct { + Device1 nvml.Device + Device2 nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex +} { + var calls []struct { + Device1 nvml.Device + Device2 nvml.Device + GpuP2PCapsIndex nvml.GpuP2PCapsIndex + } + mock.lockDeviceGetP2PStatus.RLock() + calls = mock.calls.DeviceGetP2PStatus + mock.lockDeviceGetP2PStatus.RUnlock() + return calls +} + +// DeviceGetPciInfo calls DeviceGetPciInfoFunc. +func (mock *Interface) DeviceGetPciInfo(device nvml.Device) (nvml.PciInfo, nvml.Return) { + if mock.DeviceGetPciInfoFunc == nil { + panic("Interface.DeviceGetPciInfoFunc: method is nil but Interface.DeviceGetPciInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPciInfo.Lock() + mock.calls.DeviceGetPciInfo = append(mock.calls.DeviceGetPciInfo, callInfo) + mock.lockDeviceGetPciInfo.Unlock() + return mock.DeviceGetPciInfoFunc(device) +} + +// DeviceGetPciInfoCalls gets all the calls that were made to DeviceGetPciInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetPciInfoCalls()) +func (mock *Interface) DeviceGetPciInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPciInfo.RLock() + calls = mock.calls.DeviceGetPciInfo + mock.lockDeviceGetPciInfo.RUnlock() + return calls +} + +// DeviceGetPciInfoExt calls DeviceGetPciInfoExtFunc. +func (mock *Interface) DeviceGetPciInfoExt(device nvml.Device) (nvml.PciInfoExt, nvml.Return) { + if mock.DeviceGetPciInfoExtFunc == nil { + panic("Interface.DeviceGetPciInfoExtFunc: method is nil but Interface.DeviceGetPciInfoExt was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPciInfoExt.Lock() + mock.calls.DeviceGetPciInfoExt = append(mock.calls.DeviceGetPciInfoExt, callInfo) + mock.lockDeviceGetPciInfoExt.Unlock() + return mock.DeviceGetPciInfoExtFunc(device) +} + +// DeviceGetPciInfoExtCalls gets all the calls that were made to DeviceGetPciInfoExt. +// Check the length with: +// +// len(mockedInterface.DeviceGetPciInfoExtCalls()) +func (mock *Interface) DeviceGetPciInfoExtCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPciInfoExt.RLock() + calls = mock.calls.DeviceGetPciInfoExt + mock.lockDeviceGetPciInfoExt.RUnlock() + return calls +} + +// DeviceGetPcieLinkMaxSpeed calls DeviceGetPcieLinkMaxSpeedFunc. +func (mock *Interface) DeviceGetPcieLinkMaxSpeed(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetPcieLinkMaxSpeedFunc == nil { + panic("Interface.DeviceGetPcieLinkMaxSpeedFunc: method is nil but Interface.DeviceGetPcieLinkMaxSpeed was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPcieLinkMaxSpeed.Lock() + mock.calls.DeviceGetPcieLinkMaxSpeed = append(mock.calls.DeviceGetPcieLinkMaxSpeed, callInfo) + mock.lockDeviceGetPcieLinkMaxSpeed.Unlock() + return mock.DeviceGetPcieLinkMaxSpeedFunc(device) +} + +// DeviceGetPcieLinkMaxSpeedCalls gets all the calls that were made to DeviceGetPcieLinkMaxSpeed. +// Check the length with: +// +// len(mockedInterface.DeviceGetPcieLinkMaxSpeedCalls()) +func (mock *Interface) DeviceGetPcieLinkMaxSpeedCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPcieLinkMaxSpeed.RLock() + calls = mock.calls.DeviceGetPcieLinkMaxSpeed + mock.lockDeviceGetPcieLinkMaxSpeed.RUnlock() + return calls +} + +// DeviceGetPcieReplayCounter calls DeviceGetPcieReplayCounterFunc. +func (mock *Interface) DeviceGetPcieReplayCounter(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetPcieReplayCounterFunc == nil { + panic("Interface.DeviceGetPcieReplayCounterFunc: method is nil but Interface.DeviceGetPcieReplayCounter was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPcieReplayCounter.Lock() + mock.calls.DeviceGetPcieReplayCounter = append(mock.calls.DeviceGetPcieReplayCounter, callInfo) + mock.lockDeviceGetPcieReplayCounter.Unlock() + return mock.DeviceGetPcieReplayCounterFunc(device) +} + +// DeviceGetPcieReplayCounterCalls gets all the calls that were made to DeviceGetPcieReplayCounter. +// Check the length with: +// +// len(mockedInterface.DeviceGetPcieReplayCounterCalls()) +func (mock *Interface) DeviceGetPcieReplayCounterCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPcieReplayCounter.RLock() + calls = mock.calls.DeviceGetPcieReplayCounter + mock.lockDeviceGetPcieReplayCounter.RUnlock() + return calls +} + +// DeviceGetPcieSpeed calls DeviceGetPcieSpeedFunc. +func (mock *Interface) DeviceGetPcieSpeed(device nvml.Device) (int, nvml.Return) { + if mock.DeviceGetPcieSpeedFunc == nil { + panic("Interface.DeviceGetPcieSpeedFunc: method is nil but Interface.DeviceGetPcieSpeed was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPcieSpeed.Lock() + mock.calls.DeviceGetPcieSpeed = append(mock.calls.DeviceGetPcieSpeed, callInfo) + mock.lockDeviceGetPcieSpeed.Unlock() + return mock.DeviceGetPcieSpeedFunc(device) +} + +// DeviceGetPcieSpeedCalls gets all the calls that were made to DeviceGetPcieSpeed. +// Check the length with: +// +// len(mockedInterface.DeviceGetPcieSpeedCalls()) +func (mock *Interface) DeviceGetPcieSpeedCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPcieSpeed.RLock() + calls = mock.calls.DeviceGetPcieSpeed + mock.lockDeviceGetPcieSpeed.RUnlock() + return calls +} + +// DeviceGetPcieThroughput calls DeviceGetPcieThroughputFunc. +func (mock *Interface) DeviceGetPcieThroughput(device nvml.Device, pcieUtilCounter nvml.PcieUtilCounter) (uint32, nvml.Return) { + if mock.DeviceGetPcieThroughputFunc == nil { + panic("Interface.DeviceGetPcieThroughputFunc: method is nil but Interface.DeviceGetPcieThroughput was just called") + } + callInfo := struct { + Device nvml.Device + PcieUtilCounter nvml.PcieUtilCounter + }{ + Device: device, + PcieUtilCounter: pcieUtilCounter, + } + mock.lockDeviceGetPcieThroughput.Lock() + mock.calls.DeviceGetPcieThroughput = append(mock.calls.DeviceGetPcieThroughput, callInfo) + mock.lockDeviceGetPcieThroughput.Unlock() + return mock.DeviceGetPcieThroughputFunc(device, pcieUtilCounter) +} + +// DeviceGetPcieThroughputCalls gets all the calls that were made to DeviceGetPcieThroughput. +// Check the length with: +// +// len(mockedInterface.DeviceGetPcieThroughputCalls()) +func (mock *Interface) DeviceGetPcieThroughputCalls() []struct { + Device nvml.Device + PcieUtilCounter nvml.PcieUtilCounter +} { + var calls []struct { + Device nvml.Device + PcieUtilCounter nvml.PcieUtilCounter + } + mock.lockDeviceGetPcieThroughput.RLock() + calls = mock.calls.DeviceGetPcieThroughput + mock.lockDeviceGetPcieThroughput.RUnlock() + return calls +} + +// DeviceGetPdi calls DeviceGetPdiFunc. +func (mock *Interface) DeviceGetPdi(device nvml.Device) (nvml.Pdi, nvml.Return) { + if mock.DeviceGetPdiFunc == nil { + panic("Interface.DeviceGetPdiFunc: method is nil but Interface.DeviceGetPdi was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPdi.Lock() + mock.calls.DeviceGetPdi = append(mock.calls.DeviceGetPdi, callInfo) + mock.lockDeviceGetPdi.Unlock() + return mock.DeviceGetPdiFunc(device) +} + +// DeviceGetPdiCalls gets all the calls that were made to DeviceGetPdi. +// Check the length with: +// +// len(mockedInterface.DeviceGetPdiCalls()) +func (mock *Interface) DeviceGetPdiCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPdi.RLock() + calls = mock.calls.DeviceGetPdi + mock.lockDeviceGetPdi.RUnlock() + return calls +} + +// DeviceGetPerformanceModes calls DeviceGetPerformanceModesFunc. +func (mock *Interface) DeviceGetPerformanceModes(device nvml.Device) (nvml.DevicePerfModes, nvml.Return) { + if mock.DeviceGetPerformanceModesFunc == nil { + panic("Interface.DeviceGetPerformanceModesFunc: method is nil but Interface.DeviceGetPerformanceModes was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPerformanceModes.Lock() + mock.calls.DeviceGetPerformanceModes = append(mock.calls.DeviceGetPerformanceModes, callInfo) + mock.lockDeviceGetPerformanceModes.Unlock() + return mock.DeviceGetPerformanceModesFunc(device) +} + +// DeviceGetPerformanceModesCalls gets all the calls that were made to DeviceGetPerformanceModes. +// Check the length with: +// +// len(mockedInterface.DeviceGetPerformanceModesCalls()) +func (mock *Interface) DeviceGetPerformanceModesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPerformanceModes.RLock() + calls = mock.calls.DeviceGetPerformanceModes + mock.lockDeviceGetPerformanceModes.RUnlock() + return calls +} + +// DeviceGetPerformanceState calls DeviceGetPerformanceStateFunc. +func (mock *Interface) DeviceGetPerformanceState(device nvml.Device) (nvml.Pstates, nvml.Return) { + if mock.DeviceGetPerformanceStateFunc == nil { + panic("Interface.DeviceGetPerformanceStateFunc: method is nil but Interface.DeviceGetPerformanceState was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPerformanceState.Lock() + mock.calls.DeviceGetPerformanceState = append(mock.calls.DeviceGetPerformanceState, callInfo) + mock.lockDeviceGetPerformanceState.Unlock() + return mock.DeviceGetPerformanceStateFunc(device) +} + +// DeviceGetPerformanceStateCalls gets all the calls that were made to DeviceGetPerformanceState. +// Check the length with: +// +// len(mockedInterface.DeviceGetPerformanceStateCalls()) +func (mock *Interface) DeviceGetPerformanceStateCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPerformanceState.RLock() + calls = mock.calls.DeviceGetPerformanceState + mock.lockDeviceGetPerformanceState.RUnlock() + return calls +} + +// DeviceGetPersistenceMode calls DeviceGetPersistenceModeFunc. +func (mock *Interface) DeviceGetPersistenceMode(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetPersistenceModeFunc == nil { + panic("Interface.DeviceGetPersistenceModeFunc: method is nil but Interface.DeviceGetPersistenceMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPersistenceMode.Lock() + mock.calls.DeviceGetPersistenceMode = append(mock.calls.DeviceGetPersistenceMode, callInfo) + mock.lockDeviceGetPersistenceMode.Unlock() + return mock.DeviceGetPersistenceModeFunc(device) +} + +// DeviceGetPersistenceModeCalls gets all the calls that were made to DeviceGetPersistenceMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetPersistenceModeCalls()) +func (mock *Interface) DeviceGetPersistenceModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPersistenceMode.RLock() + calls = mock.calls.DeviceGetPersistenceMode + mock.lockDeviceGetPersistenceMode.RUnlock() + return calls +} + +// DeviceGetPgpuMetadataString calls DeviceGetPgpuMetadataStringFunc. +func (mock *Interface) DeviceGetPgpuMetadataString(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetPgpuMetadataStringFunc == nil { + panic("Interface.DeviceGetPgpuMetadataStringFunc: method is nil but Interface.DeviceGetPgpuMetadataString was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPgpuMetadataString.Lock() + mock.calls.DeviceGetPgpuMetadataString = append(mock.calls.DeviceGetPgpuMetadataString, callInfo) + mock.lockDeviceGetPgpuMetadataString.Unlock() + return mock.DeviceGetPgpuMetadataStringFunc(device) +} + +// DeviceGetPgpuMetadataStringCalls gets all the calls that were made to DeviceGetPgpuMetadataString. +// Check the length with: +// +// len(mockedInterface.DeviceGetPgpuMetadataStringCalls()) +func (mock *Interface) DeviceGetPgpuMetadataStringCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPgpuMetadataString.RLock() + calls = mock.calls.DeviceGetPgpuMetadataString + mock.lockDeviceGetPgpuMetadataString.RUnlock() + return calls +} + +// DeviceGetPlatformInfo calls DeviceGetPlatformInfoFunc. +func (mock *Interface) DeviceGetPlatformInfo(device nvml.Device) (nvml.PlatformInfo, nvml.Return) { + if mock.DeviceGetPlatformInfoFunc == nil { + panic("Interface.DeviceGetPlatformInfoFunc: method is nil but Interface.DeviceGetPlatformInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPlatformInfo.Lock() + mock.calls.DeviceGetPlatformInfo = append(mock.calls.DeviceGetPlatformInfo, callInfo) + mock.lockDeviceGetPlatformInfo.Unlock() + return mock.DeviceGetPlatformInfoFunc(device) +} + +// DeviceGetPlatformInfoCalls gets all the calls that were made to DeviceGetPlatformInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetPlatformInfoCalls()) +func (mock *Interface) DeviceGetPlatformInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPlatformInfo.RLock() + calls = mock.calls.DeviceGetPlatformInfo + mock.lockDeviceGetPlatformInfo.RUnlock() + return calls +} + +// DeviceGetPowerManagementDefaultLimit calls DeviceGetPowerManagementDefaultLimitFunc. +func (mock *Interface) DeviceGetPowerManagementDefaultLimit(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetPowerManagementDefaultLimitFunc == nil { + panic("Interface.DeviceGetPowerManagementDefaultLimitFunc: method is nil but Interface.DeviceGetPowerManagementDefaultLimit was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerManagementDefaultLimit.Lock() + mock.calls.DeviceGetPowerManagementDefaultLimit = append(mock.calls.DeviceGetPowerManagementDefaultLimit, callInfo) + mock.lockDeviceGetPowerManagementDefaultLimit.Unlock() + return mock.DeviceGetPowerManagementDefaultLimitFunc(device) +} + +// DeviceGetPowerManagementDefaultLimitCalls gets all the calls that were made to DeviceGetPowerManagementDefaultLimit. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerManagementDefaultLimitCalls()) +func (mock *Interface) DeviceGetPowerManagementDefaultLimitCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerManagementDefaultLimit.RLock() + calls = mock.calls.DeviceGetPowerManagementDefaultLimit + mock.lockDeviceGetPowerManagementDefaultLimit.RUnlock() + return calls +} + +// DeviceGetPowerManagementLimit calls DeviceGetPowerManagementLimitFunc. +func (mock *Interface) DeviceGetPowerManagementLimit(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetPowerManagementLimitFunc == nil { + panic("Interface.DeviceGetPowerManagementLimitFunc: method is nil but Interface.DeviceGetPowerManagementLimit was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerManagementLimit.Lock() + mock.calls.DeviceGetPowerManagementLimit = append(mock.calls.DeviceGetPowerManagementLimit, callInfo) + mock.lockDeviceGetPowerManagementLimit.Unlock() + return mock.DeviceGetPowerManagementLimitFunc(device) +} + +// DeviceGetPowerManagementLimitCalls gets all the calls that were made to DeviceGetPowerManagementLimit. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerManagementLimitCalls()) +func (mock *Interface) DeviceGetPowerManagementLimitCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerManagementLimit.RLock() + calls = mock.calls.DeviceGetPowerManagementLimit + mock.lockDeviceGetPowerManagementLimit.RUnlock() + return calls +} + +// DeviceGetPowerManagementLimitConstraints calls DeviceGetPowerManagementLimitConstraintsFunc. +func (mock *Interface) DeviceGetPowerManagementLimitConstraints(device nvml.Device) (uint32, uint32, nvml.Return) { + if mock.DeviceGetPowerManagementLimitConstraintsFunc == nil { + panic("Interface.DeviceGetPowerManagementLimitConstraintsFunc: method is nil but Interface.DeviceGetPowerManagementLimitConstraints was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerManagementLimitConstraints.Lock() + mock.calls.DeviceGetPowerManagementLimitConstraints = append(mock.calls.DeviceGetPowerManagementLimitConstraints, callInfo) + mock.lockDeviceGetPowerManagementLimitConstraints.Unlock() + return mock.DeviceGetPowerManagementLimitConstraintsFunc(device) +} + +// DeviceGetPowerManagementLimitConstraintsCalls gets all the calls that were made to DeviceGetPowerManagementLimitConstraints. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerManagementLimitConstraintsCalls()) +func (mock *Interface) DeviceGetPowerManagementLimitConstraintsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerManagementLimitConstraints.RLock() + calls = mock.calls.DeviceGetPowerManagementLimitConstraints + mock.lockDeviceGetPowerManagementLimitConstraints.RUnlock() + return calls +} + +// DeviceGetPowerManagementMode calls DeviceGetPowerManagementModeFunc. +func (mock *Interface) DeviceGetPowerManagementMode(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetPowerManagementModeFunc == nil { + panic("Interface.DeviceGetPowerManagementModeFunc: method is nil but Interface.DeviceGetPowerManagementMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerManagementMode.Lock() + mock.calls.DeviceGetPowerManagementMode = append(mock.calls.DeviceGetPowerManagementMode, callInfo) + mock.lockDeviceGetPowerManagementMode.Unlock() + return mock.DeviceGetPowerManagementModeFunc(device) +} + +// DeviceGetPowerManagementModeCalls gets all the calls that were made to DeviceGetPowerManagementMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerManagementModeCalls()) +func (mock *Interface) DeviceGetPowerManagementModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerManagementMode.RLock() + calls = mock.calls.DeviceGetPowerManagementMode + mock.lockDeviceGetPowerManagementMode.RUnlock() + return calls +} + +// DeviceGetPowerMizerMode_v1 calls DeviceGetPowerMizerMode_v1Func. +func (mock *Interface) DeviceGetPowerMizerMode_v1(device nvml.Device) (nvml.DevicePowerMizerModes_v1, nvml.Return) { + if mock.DeviceGetPowerMizerMode_v1Func == nil { + panic("Interface.DeviceGetPowerMizerMode_v1Func: method is nil but Interface.DeviceGetPowerMizerMode_v1 was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerMizerMode_v1.Lock() + mock.calls.DeviceGetPowerMizerMode_v1 = append(mock.calls.DeviceGetPowerMizerMode_v1, callInfo) + mock.lockDeviceGetPowerMizerMode_v1.Unlock() + return mock.DeviceGetPowerMizerMode_v1Func(device) +} + +// DeviceGetPowerMizerMode_v1Calls gets all the calls that were made to DeviceGetPowerMizerMode_v1. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerMizerMode_v1Calls()) +func (mock *Interface) DeviceGetPowerMizerMode_v1Calls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerMizerMode_v1.RLock() + calls = mock.calls.DeviceGetPowerMizerMode_v1 + mock.lockDeviceGetPowerMizerMode_v1.RUnlock() + return calls +} + +// DeviceGetPowerSource calls DeviceGetPowerSourceFunc. +func (mock *Interface) DeviceGetPowerSource(device nvml.Device) (nvml.PowerSource, nvml.Return) { + if mock.DeviceGetPowerSourceFunc == nil { + panic("Interface.DeviceGetPowerSourceFunc: method is nil but Interface.DeviceGetPowerSource was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerSource.Lock() + mock.calls.DeviceGetPowerSource = append(mock.calls.DeviceGetPowerSource, callInfo) + mock.lockDeviceGetPowerSource.Unlock() + return mock.DeviceGetPowerSourceFunc(device) +} + +// DeviceGetPowerSourceCalls gets all the calls that were made to DeviceGetPowerSource. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerSourceCalls()) +func (mock *Interface) DeviceGetPowerSourceCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerSource.RLock() + calls = mock.calls.DeviceGetPowerSource + mock.lockDeviceGetPowerSource.RUnlock() + return calls +} + +// DeviceGetPowerState calls DeviceGetPowerStateFunc. +func (mock *Interface) DeviceGetPowerState(device nvml.Device) (nvml.Pstates, nvml.Return) { + if mock.DeviceGetPowerStateFunc == nil { + panic("Interface.DeviceGetPowerStateFunc: method is nil but Interface.DeviceGetPowerState was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerState.Lock() + mock.calls.DeviceGetPowerState = append(mock.calls.DeviceGetPowerState, callInfo) + mock.lockDeviceGetPowerState.Unlock() + return mock.DeviceGetPowerStateFunc(device) +} + +// DeviceGetPowerStateCalls gets all the calls that were made to DeviceGetPowerState. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerStateCalls()) +func (mock *Interface) DeviceGetPowerStateCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerState.RLock() + calls = mock.calls.DeviceGetPowerState + mock.lockDeviceGetPowerState.RUnlock() + return calls +} + +// DeviceGetPowerUsage calls DeviceGetPowerUsageFunc. +func (mock *Interface) DeviceGetPowerUsage(device nvml.Device) (uint32, nvml.Return) { + if mock.DeviceGetPowerUsageFunc == nil { + panic("Interface.DeviceGetPowerUsageFunc: method is nil but Interface.DeviceGetPowerUsage was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetPowerUsage.Lock() + mock.calls.DeviceGetPowerUsage = append(mock.calls.DeviceGetPowerUsage, callInfo) + mock.lockDeviceGetPowerUsage.Unlock() + return mock.DeviceGetPowerUsageFunc(device) +} + +// DeviceGetPowerUsageCalls gets all the calls that were made to DeviceGetPowerUsage. +// Check the length with: +// +// len(mockedInterface.DeviceGetPowerUsageCalls()) +func (mock *Interface) DeviceGetPowerUsageCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetPowerUsage.RLock() + calls = mock.calls.DeviceGetPowerUsage + mock.lockDeviceGetPowerUsage.RUnlock() + return calls +} + +// DeviceGetProcessUtilization calls DeviceGetProcessUtilizationFunc. +func (mock *Interface) DeviceGetProcessUtilization(device nvml.Device, v uint64) ([]nvml.ProcessUtilizationSample, nvml.Return) { + if mock.DeviceGetProcessUtilizationFunc == nil { + panic("Interface.DeviceGetProcessUtilizationFunc: method is nil but Interface.DeviceGetProcessUtilization was just called") + } + callInfo := struct { + Device nvml.Device + V uint64 + }{ + Device: device, + V: v, + } + mock.lockDeviceGetProcessUtilization.Lock() + mock.calls.DeviceGetProcessUtilization = append(mock.calls.DeviceGetProcessUtilization, callInfo) + mock.lockDeviceGetProcessUtilization.Unlock() + return mock.DeviceGetProcessUtilizationFunc(device, v) +} + +// DeviceGetProcessUtilizationCalls gets all the calls that were made to DeviceGetProcessUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetProcessUtilizationCalls()) +func (mock *Interface) DeviceGetProcessUtilizationCalls() []struct { + Device nvml.Device + V uint64 +} { + var calls []struct { + Device nvml.Device + V uint64 + } + mock.lockDeviceGetProcessUtilization.RLock() + calls = mock.calls.DeviceGetProcessUtilization + mock.lockDeviceGetProcessUtilization.RUnlock() + return calls +} + +// DeviceGetProcessesUtilizationInfo calls DeviceGetProcessesUtilizationInfoFunc. +func (mock *Interface) DeviceGetProcessesUtilizationInfo(device nvml.Device) (nvml.ProcessesUtilizationInfo, nvml.Return) { + if mock.DeviceGetProcessesUtilizationInfoFunc == nil { + panic("Interface.DeviceGetProcessesUtilizationInfoFunc: method is nil but Interface.DeviceGetProcessesUtilizationInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetProcessesUtilizationInfo.Lock() + mock.calls.DeviceGetProcessesUtilizationInfo = append(mock.calls.DeviceGetProcessesUtilizationInfo, callInfo) + mock.lockDeviceGetProcessesUtilizationInfo.Unlock() + return mock.DeviceGetProcessesUtilizationInfoFunc(device) +} + +// DeviceGetProcessesUtilizationInfoCalls gets all the calls that were made to DeviceGetProcessesUtilizationInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetProcessesUtilizationInfoCalls()) +func (mock *Interface) DeviceGetProcessesUtilizationInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetProcessesUtilizationInfo.RLock() + calls = mock.calls.DeviceGetProcessesUtilizationInfo + mock.lockDeviceGetProcessesUtilizationInfo.RUnlock() + return calls +} + +// DeviceGetRemappedRows calls DeviceGetRemappedRowsFunc. +func (mock *Interface) DeviceGetRemappedRows(device nvml.Device) (int, int, bool, bool, nvml.Return) { + if mock.DeviceGetRemappedRowsFunc == nil { + panic("Interface.DeviceGetRemappedRowsFunc: method is nil but Interface.DeviceGetRemappedRows was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetRemappedRows.Lock() + mock.calls.DeviceGetRemappedRows = append(mock.calls.DeviceGetRemappedRows, callInfo) + mock.lockDeviceGetRemappedRows.Unlock() + return mock.DeviceGetRemappedRowsFunc(device) +} + +// DeviceGetRemappedRowsCalls gets all the calls that were made to DeviceGetRemappedRows. +// Check the length with: +// +// len(mockedInterface.DeviceGetRemappedRowsCalls()) +func (mock *Interface) DeviceGetRemappedRowsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetRemappedRows.RLock() + calls = mock.calls.DeviceGetRemappedRows + mock.lockDeviceGetRemappedRows.RUnlock() + return calls +} + +// DeviceGetRepairStatus calls DeviceGetRepairStatusFunc. +func (mock *Interface) DeviceGetRepairStatus(device nvml.Device) (nvml.RepairStatus, nvml.Return) { + if mock.DeviceGetRepairStatusFunc == nil { + panic("Interface.DeviceGetRepairStatusFunc: method is nil but Interface.DeviceGetRepairStatus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetRepairStatus.Lock() + mock.calls.DeviceGetRepairStatus = append(mock.calls.DeviceGetRepairStatus, callInfo) + mock.lockDeviceGetRepairStatus.Unlock() + return mock.DeviceGetRepairStatusFunc(device) +} + +// DeviceGetRepairStatusCalls gets all the calls that were made to DeviceGetRepairStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetRepairStatusCalls()) +func (mock *Interface) DeviceGetRepairStatusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetRepairStatus.RLock() + calls = mock.calls.DeviceGetRepairStatus + mock.lockDeviceGetRepairStatus.RUnlock() + return calls +} + +// DeviceGetRetiredPages calls DeviceGetRetiredPagesFunc. +func (mock *Interface) DeviceGetRetiredPages(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, nvml.Return) { + if mock.DeviceGetRetiredPagesFunc == nil { + panic("Interface.DeviceGetRetiredPagesFunc: method is nil but Interface.DeviceGetRetiredPages was just called") + } + callInfo := struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause + }{ + Device: device, + PageRetirementCause: pageRetirementCause, + } + mock.lockDeviceGetRetiredPages.Lock() + mock.calls.DeviceGetRetiredPages = append(mock.calls.DeviceGetRetiredPages, callInfo) + mock.lockDeviceGetRetiredPages.Unlock() + return mock.DeviceGetRetiredPagesFunc(device, pageRetirementCause) +} + +// DeviceGetRetiredPagesCalls gets all the calls that were made to DeviceGetRetiredPages. +// Check the length with: +// +// len(mockedInterface.DeviceGetRetiredPagesCalls()) +func (mock *Interface) DeviceGetRetiredPagesCalls() []struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause +} { + var calls []struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause + } + mock.lockDeviceGetRetiredPages.RLock() + calls = mock.calls.DeviceGetRetiredPages + mock.lockDeviceGetRetiredPages.RUnlock() + return calls +} + +// DeviceGetRetiredPagesPendingStatus calls DeviceGetRetiredPagesPendingStatusFunc. +func (mock *Interface) DeviceGetRetiredPagesPendingStatus(device nvml.Device) (nvml.EnableState, nvml.Return) { + if mock.DeviceGetRetiredPagesPendingStatusFunc == nil { + panic("Interface.DeviceGetRetiredPagesPendingStatusFunc: method is nil but Interface.DeviceGetRetiredPagesPendingStatus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetRetiredPagesPendingStatus.Lock() + mock.calls.DeviceGetRetiredPagesPendingStatus = append(mock.calls.DeviceGetRetiredPagesPendingStatus, callInfo) + mock.lockDeviceGetRetiredPagesPendingStatus.Unlock() + return mock.DeviceGetRetiredPagesPendingStatusFunc(device) +} + +// DeviceGetRetiredPagesPendingStatusCalls gets all the calls that were made to DeviceGetRetiredPagesPendingStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetRetiredPagesPendingStatusCalls()) +func (mock *Interface) DeviceGetRetiredPagesPendingStatusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetRetiredPagesPendingStatus.RLock() + calls = mock.calls.DeviceGetRetiredPagesPendingStatus + mock.lockDeviceGetRetiredPagesPendingStatus.RUnlock() + return calls +} + +// DeviceGetRetiredPages_v2 calls DeviceGetRetiredPages_v2Func. +func (mock *Interface) DeviceGetRetiredPages_v2(device nvml.Device, pageRetirementCause nvml.PageRetirementCause) ([]uint64, []uint64, nvml.Return) { + if mock.DeviceGetRetiredPages_v2Func == nil { + panic("Interface.DeviceGetRetiredPages_v2Func: method is nil but Interface.DeviceGetRetiredPages_v2 was just called") + } + callInfo := struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause + }{ + Device: device, + PageRetirementCause: pageRetirementCause, + } + mock.lockDeviceGetRetiredPages_v2.Lock() + mock.calls.DeviceGetRetiredPages_v2 = append(mock.calls.DeviceGetRetiredPages_v2, callInfo) + mock.lockDeviceGetRetiredPages_v2.Unlock() + return mock.DeviceGetRetiredPages_v2Func(device, pageRetirementCause) +} + +// DeviceGetRetiredPages_v2Calls gets all the calls that were made to DeviceGetRetiredPages_v2. +// Check the length with: +// +// len(mockedInterface.DeviceGetRetiredPages_v2Calls()) +func (mock *Interface) DeviceGetRetiredPages_v2Calls() []struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause +} { + var calls []struct { + Device nvml.Device + PageRetirementCause nvml.PageRetirementCause + } + mock.lockDeviceGetRetiredPages_v2.RLock() + calls = mock.calls.DeviceGetRetiredPages_v2 + mock.lockDeviceGetRetiredPages_v2.RUnlock() + return calls +} + +// DeviceGetRowRemapperHistogram calls DeviceGetRowRemapperHistogramFunc. +func (mock *Interface) DeviceGetRowRemapperHistogram(device nvml.Device) (nvml.RowRemapperHistogramValues, nvml.Return) { + if mock.DeviceGetRowRemapperHistogramFunc == nil { + panic("Interface.DeviceGetRowRemapperHistogramFunc: method is nil but Interface.DeviceGetRowRemapperHistogram was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetRowRemapperHistogram.Lock() + mock.calls.DeviceGetRowRemapperHistogram = append(mock.calls.DeviceGetRowRemapperHistogram, callInfo) + mock.lockDeviceGetRowRemapperHistogram.Unlock() + return mock.DeviceGetRowRemapperHistogramFunc(device) +} + +// DeviceGetRowRemapperHistogramCalls gets all the calls that were made to DeviceGetRowRemapperHistogram. +// Check the length with: +// +// len(mockedInterface.DeviceGetRowRemapperHistogramCalls()) +func (mock *Interface) DeviceGetRowRemapperHistogramCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetRowRemapperHistogram.RLock() + calls = mock.calls.DeviceGetRowRemapperHistogram + mock.lockDeviceGetRowRemapperHistogram.RUnlock() + return calls +} + +// DeviceGetRunningProcessDetailList calls DeviceGetRunningProcessDetailListFunc. +func (mock *Interface) DeviceGetRunningProcessDetailList(device nvml.Device) (nvml.ProcessDetailList, nvml.Return) { + if mock.DeviceGetRunningProcessDetailListFunc == nil { + panic("Interface.DeviceGetRunningProcessDetailListFunc: method is nil but Interface.DeviceGetRunningProcessDetailList was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetRunningProcessDetailList.Lock() + mock.calls.DeviceGetRunningProcessDetailList = append(mock.calls.DeviceGetRunningProcessDetailList, callInfo) + mock.lockDeviceGetRunningProcessDetailList.Unlock() + return mock.DeviceGetRunningProcessDetailListFunc(device) +} + +// DeviceGetRunningProcessDetailListCalls gets all the calls that were made to DeviceGetRunningProcessDetailList. +// Check the length with: +// +// len(mockedInterface.DeviceGetRunningProcessDetailListCalls()) +func (mock *Interface) DeviceGetRunningProcessDetailListCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetRunningProcessDetailList.RLock() + calls = mock.calls.DeviceGetRunningProcessDetailList + mock.lockDeviceGetRunningProcessDetailList.RUnlock() + return calls +} + +// DeviceGetSamples calls DeviceGetSamplesFunc. +func (mock *Interface) DeviceGetSamples(device nvml.Device, samplingType nvml.SamplingType, v uint64) (nvml.ValueType, []nvml.Sample, nvml.Return) { + if mock.DeviceGetSamplesFunc == nil { + panic("Interface.DeviceGetSamplesFunc: method is nil but Interface.DeviceGetSamples was just called") + } + callInfo := struct { + Device nvml.Device + SamplingType nvml.SamplingType + V uint64 + }{ + Device: device, + SamplingType: samplingType, + V: v, + } + mock.lockDeviceGetSamples.Lock() + mock.calls.DeviceGetSamples = append(mock.calls.DeviceGetSamples, callInfo) + mock.lockDeviceGetSamples.Unlock() + return mock.DeviceGetSamplesFunc(device, samplingType, v) +} + +// DeviceGetSamplesCalls gets all the calls that were made to DeviceGetSamples. +// Check the length with: +// +// len(mockedInterface.DeviceGetSamplesCalls()) +func (mock *Interface) DeviceGetSamplesCalls() []struct { + Device nvml.Device + SamplingType nvml.SamplingType + V uint64 +} { + var calls []struct { + Device nvml.Device + SamplingType nvml.SamplingType + V uint64 + } + mock.lockDeviceGetSamples.RLock() + calls = mock.calls.DeviceGetSamples + mock.lockDeviceGetSamples.RUnlock() + return calls +} + +// DeviceGetSerial calls DeviceGetSerialFunc. +func (mock *Interface) DeviceGetSerial(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetSerialFunc == nil { + panic("Interface.DeviceGetSerialFunc: method is nil but Interface.DeviceGetSerial was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSerial.Lock() + mock.calls.DeviceGetSerial = append(mock.calls.DeviceGetSerial, callInfo) + mock.lockDeviceGetSerial.Unlock() + return mock.DeviceGetSerialFunc(device) +} + +// DeviceGetSerialCalls gets all the calls that were made to DeviceGetSerial. +// Check the length with: +// +// len(mockedInterface.DeviceGetSerialCalls()) +func (mock *Interface) DeviceGetSerialCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSerial.RLock() + calls = mock.calls.DeviceGetSerial + mock.lockDeviceGetSerial.RUnlock() + return calls +} + +// DeviceGetSramEccErrorStatus calls DeviceGetSramEccErrorStatusFunc. +func (mock *Interface) DeviceGetSramEccErrorStatus(device nvml.Device) (nvml.EccSramErrorStatus, nvml.Return) { + if mock.DeviceGetSramEccErrorStatusFunc == nil { + panic("Interface.DeviceGetSramEccErrorStatusFunc: method is nil but Interface.DeviceGetSramEccErrorStatus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSramEccErrorStatus.Lock() + mock.calls.DeviceGetSramEccErrorStatus = append(mock.calls.DeviceGetSramEccErrorStatus, callInfo) + mock.lockDeviceGetSramEccErrorStatus.Unlock() + return mock.DeviceGetSramEccErrorStatusFunc(device) +} + +// DeviceGetSramEccErrorStatusCalls gets all the calls that were made to DeviceGetSramEccErrorStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetSramEccErrorStatusCalls()) +func (mock *Interface) DeviceGetSramEccErrorStatusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSramEccErrorStatus.RLock() + calls = mock.calls.DeviceGetSramEccErrorStatus + mock.lockDeviceGetSramEccErrorStatus.RUnlock() + return calls +} + +// DeviceGetSramUniqueUncorrectedEccErrorCounts calls DeviceGetSramUniqueUncorrectedEccErrorCountsFunc. +func (mock *Interface) DeviceGetSramUniqueUncorrectedEccErrorCounts(device nvml.Device, eccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts) nvml.Return { + if mock.DeviceGetSramUniqueUncorrectedEccErrorCountsFunc == nil { + panic("Interface.DeviceGetSramUniqueUncorrectedEccErrorCountsFunc: method is nil but Interface.DeviceGetSramUniqueUncorrectedEccErrorCounts was just called") + } + callInfo := struct { + Device nvml.Device + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + }{ + Device: device, + EccSramUniqueUncorrectedErrorCounts: eccSramUniqueUncorrectedErrorCounts, + } + mock.lockDeviceGetSramUniqueUncorrectedEccErrorCounts.Lock() + mock.calls.DeviceGetSramUniqueUncorrectedEccErrorCounts = append(mock.calls.DeviceGetSramUniqueUncorrectedEccErrorCounts, callInfo) + mock.lockDeviceGetSramUniqueUncorrectedEccErrorCounts.Unlock() + return mock.DeviceGetSramUniqueUncorrectedEccErrorCountsFunc(device, eccSramUniqueUncorrectedErrorCounts) +} + +// DeviceGetSramUniqueUncorrectedEccErrorCountsCalls gets all the calls that were made to DeviceGetSramUniqueUncorrectedEccErrorCounts. +// Check the length with: +// +// len(mockedInterface.DeviceGetSramUniqueUncorrectedEccErrorCountsCalls()) +func (mock *Interface) DeviceGetSramUniqueUncorrectedEccErrorCountsCalls() []struct { + Device nvml.Device + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts +} { + var calls []struct { + Device nvml.Device + EccSramUniqueUncorrectedErrorCounts *nvml.EccSramUniqueUncorrectedErrorCounts + } + mock.lockDeviceGetSramUniqueUncorrectedEccErrorCounts.RLock() + calls = mock.calls.DeviceGetSramUniqueUncorrectedEccErrorCounts + mock.lockDeviceGetSramUniqueUncorrectedEccErrorCounts.RUnlock() + return calls +} + +// DeviceGetSupportedClocksEventReasons calls DeviceGetSupportedClocksEventReasonsFunc. +func (mock *Interface) DeviceGetSupportedClocksEventReasons(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetSupportedClocksEventReasonsFunc == nil { + panic("Interface.DeviceGetSupportedClocksEventReasonsFunc: method is nil but Interface.DeviceGetSupportedClocksEventReasons was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedClocksEventReasons.Lock() + mock.calls.DeviceGetSupportedClocksEventReasons = append(mock.calls.DeviceGetSupportedClocksEventReasons, callInfo) + mock.lockDeviceGetSupportedClocksEventReasons.Unlock() + return mock.DeviceGetSupportedClocksEventReasonsFunc(device) +} + +// DeviceGetSupportedClocksEventReasonsCalls gets all the calls that were made to DeviceGetSupportedClocksEventReasons. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedClocksEventReasonsCalls()) +func (mock *Interface) DeviceGetSupportedClocksEventReasonsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedClocksEventReasons.RLock() + calls = mock.calls.DeviceGetSupportedClocksEventReasons + mock.lockDeviceGetSupportedClocksEventReasons.RUnlock() + return calls +} + +// DeviceGetSupportedClocksThrottleReasons calls DeviceGetSupportedClocksThrottleReasonsFunc. +func (mock *Interface) DeviceGetSupportedClocksThrottleReasons(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetSupportedClocksThrottleReasonsFunc == nil { + panic("Interface.DeviceGetSupportedClocksThrottleReasonsFunc: method is nil but Interface.DeviceGetSupportedClocksThrottleReasons was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedClocksThrottleReasons.Lock() + mock.calls.DeviceGetSupportedClocksThrottleReasons = append(mock.calls.DeviceGetSupportedClocksThrottleReasons, callInfo) + mock.lockDeviceGetSupportedClocksThrottleReasons.Unlock() + return mock.DeviceGetSupportedClocksThrottleReasonsFunc(device) +} + +// DeviceGetSupportedClocksThrottleReasonsCalls gets all the calls that were made to DeviceGetSupportedClocksThrottleReasons. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedClocksThrottleReasonsCalls()) +func (mock *Interface) DeviceGetSupportedClocksThrottleReasonsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedClocksThrottleReasons.RLock() + calls = mock.calls.DeviceGetSupportedClocksThrottleReasons + mock.lockDeviceGetSupportedClocksThrottleReasons.RUnlock() + return calls +} + +// DeviceGetSupportedEventTypes calls DeviceGetSupportedEventTypesFunc. +func (mock *Interface) DeviceGetSupportedEventTypes(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetSupportedEventTypesFunc == nil { + panic("Interface.DeviceGetSupportedEventTypesFunc: method is nil but Interface.DeviceGetSupportedEventTypes was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedEventTypes.Lock() + mock.calls.DeviceGetSupportedEventTypes = append(mock.calls.DeviceGetSupportedEventTypes, callInfo) + mock.lockDeviceGetSupportedEventTypes.Unlock() + return mock.DeviceGetSupportedEventTypesFunc(device) +} + +// DeviceGetSupportedEventTypesCalls gets all the calls that were made to DeviceGetSupportedEventTypes. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedEventTypesCalls()) +func (mock *Interface) DeviceGetSupportedEventTypesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedEventTypes.RLock() + calls = mock.calls.DeviceGetSupportedEventTypes + mock.lockDeviceGetSupportedEventTypes.RUnlock() + return calls +} + +// DeviceGetSupportedGraphicsClocks calls DeviceGetSupportedGraphicsClocksFunc. +func (mock *Interface) DeviceGetSupportedGraphicsClocks(device nvml.Device, n int) (int, uint32, nvml.Return) { + if mock.DeviceGetSupportedGraphicsClocksFunc == nil { + panic("Interface.DeviceGetSupportedGraphicsClocksFunc: method is nil but Interface.DeviceGetSupportedGraphicsClocks was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetSupportedGraphicsClocks.Lock() + mock.calls.DeviceGetSupportedGraphicsClocks = append(mock.calls.DeviceGetSupportedGraphicsClocks, callInfo) + mock.lockDeviceGetSupportedGraphicsClocks.Unlock() + return mock.DeviceGetSupportedGraphicsClocksFunc(device, n) +} + +// DeviceGetSupportedGraphicsClocksCalls gets all the calls that were made to DeviceGetSupportedGraphicsClocks. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedGraphicsClocksCalls()) +func (mock *Interface) DeviceGetSupportedGraphicsClocksCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetSupportedGraphicsClocks.RLock() + calls = mock.calls.DeviceGetSupportedGraphicsClocks + mock.lockDeviceGetSupportedGraphicsClocks.RUnlock() + return calls +} + +// DeviceGetSupportedMemoryClocks calls DeviceGetSupportedMemoryClocksFunc. +func (mock *Interface) DeviceGetSupportedMemoryClocks(device nvml.Device) (int, uint32, nvml.Return) { + if mock.DeviceGetSupportedMemoryClocksFunc == nil { + panic("Interface.DeviceGetSupportedMemoryClocksFunc: method is nil but Interface.DeviceGetSupportedMemoryClocks was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedMemoryClocks.Lock() + mock.calls.DeviceGetSupportedMemoryClocks = append(mock.calls.DeviceGetSupportedMemoryClocks, callInfo) + mock.lockDeviceGetSupportedMemoryClocks.Unlock() + return mock.DeviceGetSupportedMemoryClocksFunc(device) +} + +// DeviceGetSupportedMemoryClocksCalls gets all the calls that were made to DeviceGetSupportedMemoryClocks. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedMemoryClocksCalls()) +func (mock *Interface) DeviceGetSupportedMemoryClocksCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedMemoryClocks.RLock() + calls = mock.calls.DeviceGetSupportedMemoryClocks + mock.lockDeviceGetSupportedMemoryClocks.RUnlock() + return calls +} + +// DeviceGetSupportedPerformanceStates calls DeviceGetSupportedPerformanceStatesFunc. +func (mock *Interface) DeviceGetSupportedPerformanceStates(device nvml.Device) ([]nvml.Pstates, nvml.Return) { + if mock.DeviceGetSupportedPerformanceStatesFunc == nil { + panic("Interface.DeviceGetSupportedPerformanceStatesFunc: method is nil but Interface.DeviceGetSupportedPerformanceStates was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedPerformanceStates.Lock() + mock.calls.DeviceGetSupportedPerformanceStates = append(mock.calls.DeviceGetSupportedPerformanceStates, callInfo) + mock.lockDeviceGetSupportedPerformanceStates.Unlock() + return mock.DeviceGetSupportedPerformanceStatesFunc(device) +} + +// DeviceGetSupportedPerformanceStatesCalls gets all the calls that were made to DeviceGetSupportedPerformanceStates. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedPerformanceStatesCalls()) +func (mock *Interface) DeviceGetSupportedPerformanceStatesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedPerformanceStates.RLock() + calls = mock.calls.DeviceGetSupportedPerformanceStates + mock.lockDeviceGetSupportedPerformanceStates.RUnlock() + return calls +} + +// DeviceGetSupportedVgpus calls DeviceGetSupportedVgpusFunc. +func (mock *Interface) DeviceGetSupportedVgpus(device nvml.Device) ([]nvml.VgpuTypeId, nvml.Return) { + if mock.DeviceGetSupportedVgpusFunc == nil { + panic("Interface.DeviceGetSupportedVgpusFunc: method is nil but Interface.DeviceGetSupportedVgpus was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetSupportedVgpus.Lock() + mock.calls.DeviceGetSupportedVgpus = append(mock.calls.DeviceGetSupportedVgpus, callInfo) + mock.lockDeviceGetSupportedVgpus.Unlock() + return mock.DeviceGetSupportedVgpusFunc(device) +} + +// DeviceGetSupportedVgpusCalls gets all the calls that were made to DeviceGetSupportedVgpus. +// Check the length with: +// +// len(mockedInterface.DeviceGetSupportedVgpusCalls()) +func (mock *Interface) DeviceGetSupportedVgpusCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetSupportedVgpus.RLock() + calls = mock.calls.DeviceGetSupportedVgpus + mock.lockDeviceGetSupportedVgpus.RUnlock() + return calls +} + +// DeviceGetTargetFanSpeed calls DeviceGetTargetFanSpeedFunc. +func (mock *Interface) DeviceGetTargetFanSpeed(device nvml.Device, n int) (int, nvml.Return) { + if mock.DeviceGetTargetFanSpeedFunc == nil { + panic("Interface.DeviceGetTargetFanSpeedFunc: method is nil but Interface.DeviceGetTargetFanSpeed was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceGetTargetFanSpeed.Lock() + mock.calls.DeviceGetTargetFanSpeed = append(mock.calls.DeviceGetTargetFanSpeed, callInfo) + mock.lockDeviceGetTargetFanSpeed.Unlock() + return mock.DeviceGetTargetFanSpeedFunc(device, n) +} + +// DeviceGetTargetFanSpeedCalls gets all the calls that were made to DeviceGetTargetFanSpeed. +// Check the length with: +// +// len(mockedInterface.DeviceGetTargetFanSpeedCalls()) +func (mock *Interface) DeviceGetTargetFanSpeedCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceGetTargetFanSpeed.RLock() + calls = mock.calls.DeviceGetTargetFanSpeed + mock.lockDeviceGetTargetFanSpeed.RUnlock() + return calls +} + +// DeviceGetTemperature calls DeviceGetTemperatureFunc. +func (mock *Interface) DeviceGetTemperature(device nvml.Device, temperatureSensors nvml.TemperatureSensors) (uint32, nvml.Return) { + if mock.DeviceGetTemperatureFunc == nil { + panic("Interface.DeviceGetTemperatureFunc: method is nil but Interface.DeviceGetTemperature was just called") + } + callInfo := struct { + Device nvml.Device + TemperatureSensors nvml.TemperatureSensors + }{ + Device: device, + TemperatureSensors: temperatureSensors, + } + mock.lockDeviceGetTemperature.Lock() + mock.calls.DeviceGetTemperature = append(mock.calls.DeviceGetTemperature, callInfo) + mock.lockDeviceGetTemperature.Unlock() + return mock.DeviceGetTemperatureFunc(device, temperatureSensors) +} + +// DeviceGetTemperatureCalls gets all the calls that were made to DeviceGetTemperature. +// Check the length with: +// +// len(mockedInterface.DeviceGetTemperatureCalls()) +func (mock *Interface) DeviceGetTemperatureCalls() []struct { + Device nvml.Device + TemperatureSensors nvml.TemperatureSensors +} { + var calls []struct { + Device nvml.Device + TemperatureSensors nvml.TemperatureSensors + } + mock.lockDeviceGetTemperature.RLock() + calls = mock.calls.DeviceGetTemperature + mock.lockDeviceGetTemperature.RUnlock() + return calls +} + +// DeviceGetTemperatureThreshold calls DeviceGetTemperatureThresholdFunc. +func (mock *Interface) DeviceGetTemperatureThreshold(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds) (uint32, nvml.Return) { + if mock.DeviceGetTemperatureThresholdFunc == nil { + panic("Interface.DeviceGetTemperatureThresholdFunc: method is nil but Interface.DeviceGetTemperatureThreshold was just called") + } + callInfo := struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds + }{ + Device: device, + TemperatureThresholds: temperatureThresholds, + } + mock.lockDeviceGetTemperatureThreshold.Lock() + mock.calls.DeviceGetTemperatureThreshold = append(mock.calls.DeviceGetTemperatureThreshold, callInfo) + mock.lockDeviceGetTemperatureThreshold.Unlock() + return mock.DeviceGetTemperatureThresholdFunc(device, temperatureThresholds) +} + +// DeviceGetTemperatureThresholdCalls gets all the calls that were made to DeviceGetTemperatureThreshold. +// Check the length with: +// +// len(mockedInterface.DeviceGetTemperatureThresholdCalls()) +func (mock *Interface) DeviceGetTemperatureThresholdCalls() []struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds +} { + var calls []struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds + } + mock.lockDeviceGetTemperatureThreshold.RLock() + calls = mock.calls.DeviceGetTemperatureThreshold + mock.lockDeviceGetTemperatureThreshold.RUnlock() + return calls +} + +// DeviceGetTemperatureV calls DeviceGetTemperatureVFunc. +func (mock *Interface) DeviceGetTemperatureV(device nvml.Device) nvml.TemperatureHandler { + if mock.DeviceGetTemperatureVFunc == nil { + panic("Interface.DeviceGetTemperatureVFunc: method is nil but Interface.DeviceGetTemperatureV was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetTemperatureV.Lock() + mock.calls.DeviceGetTemperatureV = append(mock.calls.DeviceGetTemperatureV, callInfo) + mock.lockDeviceGetTemperatureV.Unlock() + return mock.DeviceGetTemperatureVFunc(device) +} + +// DeviceGetTemperatureVCalls gets all the calls that were made to DeviceGetTemperatureV. +// Check the length with: +// +// len(mockedInterface.DeviceGetTemperatureVCalls()) +func (mock *Interface) DeviceGetTemperatureVCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetTemperatureV.RLock() + calls = mock.calls.DeviceGetTemperatureV + mock.lockDeviceGetTemperatureV.RUnlock() + return calls +} + +// DeviceGetThermalSettings calls DeviceGetThermalSettingsFunc. +func (mock *Interface) DeviceGetThermalSettings(device nvml.Device, v uint32) (nvml.GpuThermalSettings, nvml.Return) { + if mock.DeviceGetThermalSettingsFunc == nil { + panic("Interface.DeviceGetThermalSettingsFunc: method is nil but Interface.DeviceGetThermalSettings was just called") + } + callInfo := struct { + Device nvml.Device + V uint32 + }{ + Device: device, + V: v, + } + mock.lockDeviceGetThermalSettings.Lock() + mock.calls.DeviceGetThermalSettings = append(mock.calls.DeviceGetThermalSettings, callInfo) + mock.lockDeviceGetThermalSettings.Unlock() + return mock.DeviceGetThermalSettingsFunc(device, v) +} + +// DeviceGetThermalSettingsCalls gets all the calls that were made to DeviceGetThermalSettings. +// Check the length with: +// +// len(mockedInterface.DeviceGetThermalSettingsCalls()) +func (mock *Interface) DeviceGetThermalSettingsCalls() []struct { + Device nvml.Device + V uint32 +} { + var calls []struct { + Device nvml.Device + V uint32 + } + mock.lockDeviceGetThermalSettings.RLock() + calls = mock.calls.DeviceGetThermalSettings + mock.lockDeviceGetThermalSettings.RUnlock() + return calls +} + +// DeviceGetTopologyCommonAncestor calls DeviceGetTopologyCommonAncestorFunc. +func (mock *Interface) DeviceGetTopologyCommonAncestor(device1 nvml.Device, device2 nvml.Device) (nvml.GpuTopologyLevel, nvml.Return) { + if mock.DeviceGetTopologyCommonAncestorFunc == nil { + panic("Interface.DeviceGetTopologyCommonAncestorFunc: method is nil but Interface.DeviceGetTopologyCommonAncestor was just called") + } + callInfo := struct { + Device1 nvml.Device + Device2 nvml.Device + }{ + Device1: device1, + Device2: device2, + } + mock.lockDeviceGetTopologyCommonAncestor.Lock() + mock.calls.DeviceGetTopologyCommonAncestor = append(mock.calls.DeviceGetTopologyCommonAncestor, callInfo) + mock.lockDeviceGetTopologyCommonAncestor.Unlock() + return mock.DeviceGetTopologyCommonAncestorFunc(device1, device2) +} + +// DeviceGetTopologyCommonAncestorCalls gets all the calls that were made to DeviceGetTopologyCommonAncestor. +// Check the length with: +// +// len(mockedInterface.DeviceGetTopologyCommonAncestorCalls()) +func (mock *Interface) DeviceGetTopologyCommonAncestorCalls() []struct { + Device1 nvml.Device + Device2 nvml.Device +} { + var calls []struct { + Device1 nvml.Device + Device2 nvml.Device + } + mock.lockDeviceGetTopologyCommonAncestor.RLock() + calls = mock.calls.DeviceGetTopologyCommonAncestor + mock.lockDeviceGetTopologyCommonAncestor.RUnlock() + return calls +} + +// DeviceGetTopologyNearestGpus calls DeviceGetTopologyNearestGpusFunc. +func (mock *Interface) DeviceGetTopologyNearestGpus(device nvml.Device, gpuTopologyLevel nvml.GpuTopologyLevel) ([]nvml.Device, nvml.Return) { + if mock.DeviceGetTopologyNearestGpusFunc == nil { + panic("Interface.DeviceGetTopologyNearestGpusFunc: method is nil but Interface.DeviceGetTopologyNearestGpus was just called") + } + callInfo := struct { + Device nvml.Device + GpuTopologyLevel nvml.GpuTopologyLevel + }{ + Device: device, + GpuTopologyLevel: gpuTopologyLevel, + } + mock.lockDeviceGetTopologyNearestGpus.Lock() + mock.calls.DeviceGetTopologyNearestGpus = append(mock.calls.DeviceGetTopologyNearestGpus, callInfo) + mock.lockDeviceGetTopologyNearestGpus.Unlock() + return mock.DeviceGetTopologyNearestGpusFunc(device, gpuTopologyLevel) +} + +// DeviceGetTopologyNearestGpusCalls gets all the calls that were made to DeviceGetTopologyNearestGpus. +// Check the length with: +// +// len(mockedInterface.DeviceGetTopologyNearestGpusCalls()) +func (mock *Interface) DeviceGetTopologyNearestGpusCalls() []struct { + Device nvml.Device + GpuTopologyLevel nvml.GpuTopologyLevel +} { + var calls []struct { + Device nvml.Device + GpuTopologyLevel nvml.GpuTopologyLevel + } + mock.lockDeviceGetTopologyNearestGpus.RLock() + calls = mock.calls.DeviceGetTopologyNearestGpus + mock.lockDeviceGetTopologyNearestGpus.RUnlock() + return calls +} + +// DeviceGetTotalEccErrors calls DeviceGetTotalEccErrorsFunc. +func (mock *Interface) DeviceGetTotalEccErrors(device nvml.Device, memoryErrorType nvml.MemoryErrorType, eccCounterType nvml.EccCounterType) (uint64, nvml.Return) { + if mock.DeviceGetTotalEccErrorsFunc == nil { + panic("Interface.DeviceGetTotalEccErrorsFunc: method is nil but Interface.DeviceGetTotalEccErrors was just called") + } + callInfo := struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + }{ + Device: device, + MemoryErrorType: memoryErrorType, + EccCounterType: eccCounterType, + } + mock.lockDeviceGetTotalEccErrors.Lock() + mock.calls.DeviceGetTotalEccErrors = append(mock.calls.DeviceGetTotalEccErrors, callInfo) + mock.lockDeviceGetTotalEccErrors.Unlock() + return mock.DeviceGetTotalEccErrorsFunc(device, memoryErrorType, eccCounterType) +} + +// DeviceGetTotalEccErrorsCalls gets all the calls that were made to DeviceGetTotalEccErrors. +// Check the length with: +// +// len(mockedInterface.DeviceGetTotalEccErrorsCalls()) +func (mock *Interface) DeviceGetTotalEccErrorsCalls() []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType +} { + var calls []struct { + Device nvml.Device + MemoryErrorType nvml.MemoryErrorType + EccCounterType nvml.EccCounterType + } + mock.lockDeviceGetTotalEccErrors.RLock() + calls = mock.calls.DeviceGetTotalEccErrors + mock.lockDeviceGetTotalEccErrors.RUnlock() + return calls +} + +// DeviceGetTotalEnergyConsumption calls DeviceGetTotalEnergyConsumptionFunc. +func (mock *Interface) DeviceGetTotalEnergyConsumption(device nvml.Device) (uint64, nvml.Return) { + if mock.DeviceGetTotalEnergyConsumptionFunc == nil { + panic("Interface.DeviceGetTotalEnergyConsumptionFunc: method is nil but Interface.DeviceGetTotalEnergyConsumption was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetTotalEnergyConsumption.Lock() + mock.calls.DeviceGetTotalEnergyConsumption = append(mock.calls.DeviceGetTotalEnergyConsumption, callInfo) + mock.lockDeviceGetTotalEnergyConsumption.Unlock() + return mock.DeviceGetTotalEnergyConsumptionFunc(device) +} + +// DeviceGetTotalEnergyConsumptionCalls gets all the calls that were made to DeviceGetTotalEnergyConsumption. +// Check the length with: +// +// len(mockedInterface.DeviceGetTotalEnergyConsumptionCalls()) +func (mock *Interface) DeviceGetTotalEnergyConsumptionCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetTotalEnergyConsumption.RLock() + calls = mock.calls.DeviceGetTotalEnergyConsumption + mock.lockDeviceGetTotalEnergyConsumption.RUnlock() + return calls +} + +// DeviceGetUUID calls DeviceGetUUIDFunc. +func (mock *Interface) DeviceGetUUID(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetUUIDFunc == nil { + panic("Interface.DeviceGetUUIDFunc: method is nil but Interface.DeviceGetUUID was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetUUID.Lock() + mock.calls.DeviceGetUUID = append(mock.calls.DeviceGetUUID, callInfo) + mock.lockDeviceGetUUID.Unlock() + return mock.DeviceGetUUIDFunc(device) +} + +// DeviceGetUUIDCalls gets all the calls that were made to DeviceGetUUID. +// Check the length with: +// +// len(mockedInterface.DeviceGetUUIDCalls()) +func (mock *Interface) DeviceGetUUIDCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetUUID.RLock() + calls = mock.calls.DeviceGetUUID + mock.lockDeviceGetUUID.RUnlock() + return calls +} + +// DeviceGetUtilizationRates calls DeviceGetUtilizationRatesFunc. +func (mock *Interface) DeviceGetUtilizationRates(device nvml.Device) (nvml.Utilization, nvml.Return) { + if mock.DeviceGetUtilizationRatesFunc == nil { + panic("Interface.DeviceGetUtilizationRatesFunc: method is nil but Interface.DeviceGetUtilizationRates was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetUtilizationRates.Lock() + mock.calls.DeviceGetUtilizationRates = append(mock.calls.DeviceGetUtilizationRates, callInfo) + mock.lockDeviceGetUtilizationRates.Unlock() + return mock.DeviceGetUtilizationRatesFunc(device) +} + +// DeviceGetUtilizationRatesCalls gets all the calls that were made to DeviceGetUtilizationRates. +// Check the length with: +// +// len(mockedInterface.DeviceGetUtilizationRatesCalls()) +func (mock *Interface) DeviceGetUtilizationRatesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetUtilizationRates.RLock() + calls = mock.calls.DeviceGetUtilizationRates + mock.lockDeviceGetUtilizationRates.RUnlock() + return calls +} + +// DeviceGetVbiosVersion calls DeviceGetVbiosVersionFunc. +func (mock *Interface) DeviceGetVbiosVersion(device nvml.Device) (string, nvml.Return) { + if mock.DeviceGetVbiosVersionFunc == nil { + panic("Interface.DeviceGetVbiosVersionFunc: method is nil but Interface.DeviceGetVbiosVersion was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVbiosVersion.Lock() + mock.calls.DeviceGetVbiosVersion = append(mock.calls.DeviceGetVbiosVersion, callInfo) + mock.lockDeviceGetVbiosVersion.Unlock() + return mock.DeviceGetVbiosVersionFunc(device) +} + +// DeviceGetVbiosVersionCalls gets all the calls that were made to DeviceGetVbiosVersion. +// Check the length with: +// +// len(mockedInterface.DeviceGetVbiosVersionCalls()) +func (mock *Interface) DeviceGetVbiosVersionCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVbiosVersion.RLock() + calls = mock.calls.DeviceGetVbiosVersion + mock.lockDeviceGetVbiosVersion.RUnlock() + return calls +} + +// DeviceGetVgpuCapabilities calls DeviceGetVgpuCapabilitiesFunc. +func (mock *Interface) DeviceGetVgpuCapabilities(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability) (bool, nvml.Return) { + if mock.DeviceGetVgpuCapabilitiesFunc == nil { + panic("Interface.DeviceGetVgpuCapabilitiesFunc: method is nil but Interface.DeviceGetVgpuCapabilities was just called") + } + callInfo := struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability + }{ + Device: device, + DeviceVgpuCapability: deviceVgpuCapability, + } + mock.lockDeviceGetVgpuCapabilities.Lock() + mock.calls.DeviceGetVgpuCapabilities = append(mock.calls.DeviceGetVgpuCapabilities, callInfo) + mock.lockDeviceGetVgpuCapabilities.Unlock() + return mock.DeviceGetVgpuCapabilitiesFunc(device, deviceVgpuCapability) +} + +// DeviceGetVgpuCapabilitiesCalls gets all the calls that were made to DeviceGetVgpuCapabilities. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuCapabilitiesCalls()) +func (mock *Interface) DeviceGetVgpuCapabilitiesCalls() []struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability +} { + var calls []struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability + } + mock.lockDeviceGetVgpuCapabilities.RLock() + calls = mock.calls.DeviceGetVgpuCapabilities + mock.lockDeviceGetVgpuCapabilities.RUnlock() + return calls +} + +// DeviceGetVgpuHeterogeneousMode calls DeviceGetVgpuHeterogeneousModeFunc. +func (mock *Interface) DeviceGetVgpuHeterogeneousMode(device nvml.Device) (nvml.VgpuHeterogeneousMode, nvml.Return) { + if mock.DeviceGetVgpuHeterogeneousModeFunc == nil { + panic("Interface.DeviceGetVgpuHeterogeneousModeFunc: method is nil but Interface.DeviceGetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuHeterogeneousMode.Lock() + mock.calls.DeviceGetVgpuHeterogeneousMode = append(mock.calls.DeviceGetVgpuHeterogeneousMode, callInfo) + mock.lockDeviceGetVgpuHeterogeneousMode.Unlock() + return mock.DeviceGetVgpuHeterogeneousModeFunc(device) +} + +// DeviceGetVgpuHeterogeneousModeCalls gets all the calls that were made to DeviceGetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuHeterogeneousModeCalls()) +func (mock *Interface) DeviceGetVgpuHeterogeneousModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuHeterogeneousMode.RLock() + calls = mock.calls.DeviceGetVgpuHeterogeneousMode + mock.lockDeviceGetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// DeviceGetVgpuInstancesUtilizationInfo calls DeviceGetVgpuInstancesUtilizationInfoFunc. +func (mock *Interface) DeviceGetVgpuInstancesUtilizationInfo(device nvml.Device) (nvml.VgpuInstancesUtilizationInfo, nvml.Return) { + if mock.DeviceGetVgpuInstancesUtilizationInfoFunc == nil { + panic("Interface.DeviceGetVgpuInstancesUtilizationInfoFunc: method is nil but Interface.DeviceGetVgpuInstancesUtilizationInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuInstancesUtilizationInfo.Lock() + mock.calls.DeviceGetVgpuInstancesUtilizationInfo = append(mock.calls.DeviceGetVgpuInstancesUtilizationInfo, callInfo) + mock.lockDeviceGetVgpuInstancesUtilizationInfo.Unlock() + return mock.DeviceGetVgpuInstancesUtilizationInfoFunc(device) +} + +// DeviceGetVgpuInstancesUtilizationInfoCalls gets all the calls that were made to DeviceGetVgpuInstancesUtilizationInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuInstancesUtilizationInfoCalls()) +func (mock *Interface) DeviceGetVgpuInstancesUtilizationInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuInstancesUtilizationInfo.RLock() + calls = mock.calls.DeviceGetVgpuInstancesUtilizationInfo + mock.lockDeviceGetVgpuInstancesUtilizationInfo.RUnlock() + return calls +} + +// DeviceGetVgpuMetadata calls DeviceGetVgpuMetadataFunc. +func (mock *Interface) DeviceGetVgpuMetadata(device nvml.Device) (nvml.VgpuPgpuMetadata, nvml.Return) { + if mock.DeviceGetVgpuMetadataFunc == nil { + panic("Interface.DeviceGetVgpuMetadataFunc: method is nil but Interface.DeviceGetVgpuMetadata was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuMetadata.Lock() + mock.calls.DeviceGetVgpuMetadata = append(mock.calls.DeviceGetVgpuMetadata, callInfo) + mock.lockDeviceGetVgpuMetadata.Unlock() + return mock.DeviceGetVgpuMetadataFunc(device) +} + +// DeviceGetVgpuMetadataCalls gets all the calls that were made to DeviceGetVgpuMetadata. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuMetadataCalls()) +func (mock *Interface) DeviceGetVgpuMetadataCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuMetadata.RLock() + calls = mock.calls.DeviceGetVgpuMetadata + mock.lockDeviceGetVgpuMetadata.RUnlock() + return calls +} + +// DeviceGetVgpuProcessUtilization calls DeviceGetVgpuProcessUtilizationFunc. +func (mock *Interface) DeviceGetVgpuProcessUtilization(device nvml.Device, v uint64) ([]nvml.VgpuProcessUtilizationSample, nvml.Return) { + if mock.DeviceGetVgpuProcessUtilizationFunc == nil { + panic("Interface.DeviceGetVgpuProcessUtilizationFunc: method is nil but Interface.DeviceGetVgpuProcessUtilization was just called") + } + callInfo := struct { + Device nvml.Device + V uint64 + }{ + Device: device, + V: v, + } + mock.lockDeviceGetVgpuProcessUtilization.Lock() + mock.calls.DeviceGetVgpuProcessUtilization = append(mock.calls.DeviceGetVgpuProcessUtilization, callInfo) + mock.lockDeviceGetVgpuProcessUtilization.Unlock() + return mock.DeviceGetVgpuProcessUtilizationFunc(device, v) +} + +// DeviceGetVgpuProcessUtilizationCalls gets all the calls that were made to DeviceGetVgpuProcessUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuProcessUtilizationCalls()) +func (mock *Interface) DeviceGetVgpuProcessUtilizationCalls() []struct { + Device nvml.Device + V uint64 +} { + var calls []struct { + Device nvml.Device + V uint64 + } + mock.lockDeviceGetVgpuProcessUtilization.RLock() + calls = mock.calls.DeviceGetVgpuProcessUtilization + mock.lockDeviceGetVgpuProcessUtilization.RUnlock() + return calls +} + +// DeviceGetVgpuProcessesUtilizationInfo calls DeviceGetVgpuProcessesUtilizationInfoFunc. +func (mock *Interface) DeviceGetVgpuProcessesUtilizationInfo(device nvml.Device) (nvml.VgpuProcessesUtilizationInfo, nvml.Return) { + if mock.DeviceGetVgpuProcessesUtilizationInfoFunc == nil { + panic("Interface.DeviceGetVgpuProcessesUtilizationInfoFunc: method is nil but Interface.DeviceGetVgpuProcessesUtilizationInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuProcessesUtilizationInfo.Lock() + mock.calls.DeviceGetVgpuProcessesUtilizationInfo = append(mock.calls.DeviceGetVgpuProcessesUtilizationInfo, callInfo) + mock.lockDeviceGetVgpuProcessesUtilizationInfo.Unlock() + return mock.DeviceGetVgpuProcessesUtilizationInfoFunc(device) +} + +// DeviceGetVgpuProcessesUtilizationInfoCalls gets all the calls that were made to DeviceGetVgpuProcessesUtilizationInfo. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuProcessesUtilizationInfoCalls()) +func (mock *Interface) DeviceGetVgpuProcessesUtilizationInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuProcessesUtilizationInfo.RLock() + calls = mock.calls.DeviceGetVgpuProcessesUtilizationInfo + mock.lockDeviceGetVgpuProcessesUtilizationInfo.RUnlock() + return calls +} + +// DeviceGetVgpuSchedulerCapabilities calls DeviceGetVgpuSchedulerCapabilitiesFunc. +func (mock *Interface) DeviceGetVgpuSchedulerCapabilities(device nvml.Device) (nvml.VgpuSchedulerCapabilities, nvml.Return) { + if mock.DeviceGetVgpuSchedulerCapabilitiesFunc == nil { + panic("Interface.DeviceGetVgpuSchedulerCapabilitiesFunc: method is nil but Interface.DeviceGetVgpuSchedulerCapabilities was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuSchedulerCapabilities.Lock() + mock.calls.DeviceGetVgpuSchedulerCapabilities = append(mock.calls.DeviceGetVgpuSchedulerCapabilities, callInfo) + mock.lockDeviceGetVgpuSchedulerCapabilities.Unlock() + return mock.DeviceGetVgpuSchedulerCapabilitiesFunc(device) +} + +// DeviceGetVgpuSchedulerCapabilitiesCalls gets all the calls that were made to DeviceGetVgpuSchedulerCapabilities. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuSchedulerCapabilitiesCalls()) +func (mock *Interface) DeviceGetVgpuSchedulerCapabilitiesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuSchedulerCapabilities.RLock() + calls = mock.calls.DeviceGetVgpuSchedulerCapabilities + mock.lockDeviceGetVgpuSchedulerCapabilities.RUnlock() + return calls +} + +// DeviceGetVgpuSchedulerLog calls DeviceGetVgpuSchedulerLogFunc. +func (mock *Interface) DeviceGetVgpuSchedulerLog(device nvml.Device) (nvml.VgpuSchedulerLog, nvml.Return) { + if mock.DeviceGetVgpuSchedulerLogFunc == nil { + panic("Interface.DeviceGetVgpuSchedulerLogFunc: method is nil but Interface.DeviceGetVgpuSchedulerLog was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuSchedulerLog.Lock() + mock.calls.DeviceGetVgpuSchedulerLog = append(mock.calls.DeviceGetVgpuSchedulerLog, callInfo) + mock.lockDeviceGetVgpuSchedulerLog.Unlock() + return mock.DeviceGetVgpuSchedulerLogFunc(device) +} + +// DeviceGetVgpuSchedulerLogCalls gets all the calls that were made to DeviceGetVgpuSchedulerLog. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuSchedulerLogCalls()) +func (mock *Interface) DeviceGetVgpuSchedulerLogCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuSchedulerLog.RLock() + calls = mock.calls.DeviceGetVgpuSchedulerLog + mock.lockDeviceGetVgpuSchedulerLog.RUnlock() + return calls +} + +// DeviceGetVgpuSchedulerState calls DeviceGetVgpuSchedulerStateFunc. +func (mock *Interface) DeviceGetVgpuSchedulerState(device nvml.Device) (nvml.VgpuSchedulerGetState, nvml.Return) { + if mock.DeviceGetVgpuSchedulerStateFunc == nil { + panic("Interface.DeviceGetVgpuSchedulerStateFunc: method is nil but Interface.DeviceGetVgpuSchedulerState was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVgpuSchedulerState.Lock() + mock.calls.DeviceGetVgpuSchedulerState = append(mock.calls.DeviceGetVgpuSchedulerState, callInfo) + mock.lockDeviceGetVgpuSchedulerState.Unlock() + return mock.DeviceGetVgpuSchedulerStateFunc(device) +} + +// DeviceGetVgpuSchedulerStateCalls gets all the calls that were made to DeviceGetVgpuSchedulerState. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuSchedulerStateCalls()) +func (mock *Interface) DeviceGetVgpuSchedulerStateCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVgpuSchedulerState.RLock() + calls = mock.calls.DeviceGetVgpuSchedulerState + mock.lockDeviceGetVgpuSchedulerState.RUnlock() + return calls +} + +// DeviceGetVgpuTypeCreatablePlacements calls DeviceGetVgpuTypeCreatablePlacementsFunc. +func (mock *Interface) DeviceGetVgpuTypeCreatablePlacements(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { + if mock.DeviceGetVgpuTypeCreatablePlacementsFunc == nil { + panic("Interface.DeviceGetVgpuTypeCreatablePlacementsFunc: method is nil but Interface.DeviceGetVgpuTypeCreatablePlacements was just called") + } + callInfo := struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + }{ + Device: device, + VgpuTypeId: vgpuTypeId, + } + mock.lockDeviceGetVgpuTypeCreatablePlacements.Lock() + mock.calls.DeviceGetVgpuTypeCreatablePlacements = append(mock.calls.DeviceGetVgpuTypeCreatablePlacements, callInfo) + mock.lockDeviceGetVgpuTypeCreatablePlacements.Unlock() + return mock.DeviceGetVgpuTypeCreatablePlacementsFunc(device, vgpuTypeId) +} + +// DeviceGetVgpuTypeCreatablePlacementsCalls gets all the calls that were made to DeviceGetVgpuTypeCreatablePlacements. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuTypeCreatablePlacementsCalls()) +func (mock *Interface) DeviceGetVgpuTypeCreatablePlacementsCalls() []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + } + mock.lockDeviceGetVgpuTypeCreatablePlacements.RLock() + calls = mock.calls.DeviceGetVgpuTypeCreatablePlacements + mock.lockDeviceGetVgpuTypeCreatablePlacements.RUnlock() + return calls +} + +// DeviceGetVgpuTypeSupportedPlacements calls DeviceGetVgpuTypeSupportedPlacementsFunc. +func (mock *Interface) DeviceGetVgpuTypeSupportedPlacements(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuPlacementList, nvml.Return) { + if mock.DeviceGetVgpuTypeSupportedPlacementsFunc == nil { + panic("Interface.DeviceGetVgpuTypeSupportedPlacementsFunc: method is nil but Interface.DeviceGetVgpuTypeSupportedPlacements was just called") + } + callInfo := struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + }{ + Device: device, + VgpuTypeId: vgpuTypeId, + } + mock.lockDeviceGetVgpuTypeSupportedPlacements.Lock() + mock.calls.DeviceGetVgpuTypeSupportedPlacements = append(mock.calls.DeviceGetVgpuTypeSupportedPlacements, callInfo) + mock.lockDeviceGetVgpuTypeSupportedPlacements.Unlock() + return mock.DeviceGetVgpuTypeSupportedPlacementsFunc(device, vgpuTypeId) +} + +// DeviceGetVgpuTypeSupportedPlacementsCalls gets all the calls that were made to DeviceGetVgpuTypeSupportedPlacements. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuTypeSupportedPlacementsCalls()) +func (mock *Interface) DeviceGetVgpuTypeSupportedPlacementsCalls() []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + } + mock.lockDeviceGetVgpuTypeSupportedPlacements.RLock() + calls = mock.calls.DeviceGetVgpuTypeSupportedPlacements + mock.lockDeviceGetVgpuTypeSupportedPlacements.RUnlock() + return calls +} + +// DeviceGetVgpuUtilization calls DeviceGetVgpuUtilizationFunc. +func (mock *Interface) DeviceGetVgpuUtilization(device nvml.Device, v uint64) (nvml.ValueType, []nvml.VgpuInstanceUtilizationSample, nvml.Return) { + if mock.DeviceGetVgpuUtilizationFunc == nil { + panic("Interface.DeviceGetVgpuUtilizationFunc: method is nil but Interface.DeviceGetVgpuUtilization was just called") + } + callInfo := struct { + Device nvml.Device + V uint64 + }{ + Device: device, + V: v, + } + mock.lockDeviceGetVgpuUtilization.Lock() + mock.calls.DeviceGetVgpuUtilization = append(mock.calls.DeviceGetVgpuUtilization, callInfo) + mock.lockDeviceGetVgpuUtilization.Unlock() + return mock.DeviceGetVgpuUtilizationFunc(device, v) +} + +// DeviceGetVgpuUtilizationCalls gets all the calls that were made to DeviceGetVgpuUtilization. +// Check the length with: +// +// len(mockedInterface.DeviceGetVgpuUtilizationCalls()) +func (mock *Interface) DeviceGetVgpuUtilizationCalls() []struct { + Device nvml.Device + V uint64 +} { + var calls []struct { + Device nvml.Device + V uint64 + } + mock.lockDeviceGetVgpuUtilization.RLock() + calls = mock.calls.DeviceGetVgpuUtilization + mock.lockDeviceGetVgpuUtilization.RUnlock() + return calls +} + +// DeviceGetViolationStatus calls DeviceGetViolationStatusFunc. +func (mock *Interface) DeviceGetViolationStatus(device nvml.Device, perfPolicyType nvml.PerfPolicyType) (nvml.ViolationTime, nvml.Return) { + if mock.DeviceGetViolationStatusFunc == nil { + panic("Interface.DeviceGetViolationStatusFunc: method is nil but Interface.DeviceGetViolationStatus was just called") + } + callInfo := struct { + Device nvml.Device + PerfPolicyType nvml.PerfPolicyType + }{ + Device: device, + PerfPolicyType: perfPolicyType, + } + mock.lockDeviceGetViolationStatus.Lock() + mock.calls.DeviceGetViolationStatus = append(mock.calls.DeviceGetViolationStatus, callInfo) + mock.lockDeviceGetViolationStatus.Unlock() + return mock.DeviceGetViolationStatusFunc(device, perfPolicyType) +} + +// DeviceGetViolationStatusCalls gets all the calls that were made to DeviceGetViolationStatus. +// Check the length with: +// +// len(mockedInterface.DeviceGetViolationStatusCalls()) +func (mock *Interface) DeviceGetViolationStatusCalls() []struct { + Device nvml.Device + PerfPolicyType nvml.PerfPolicyType +} { + var calls []struct { + Device nvml.Device + PerfPolicyType nvml.PerfPolicyType + } + mock.lockDeviceGetViolationStatus.RLock() + calls = mock.calls.DeviceGetViolationStatus + mock.lockDeviceGetViolationStatus.RUnlock() + return calls +} + +// DeviceGetVirtualizationMode calls DeviceGetVirtualizationModeFunc. +func (mock *Interface) DeviceGetVirtualizationMode(device nvml.Device) (nvml.GpuVirtualizationMode, nvml.Return) { + if mock.DeviceGetVirtualizationModeFunc == nil { + panic("Interface.DeviceGetVirtualizationModeFunc: method is nil but Interface.DeviceGetVirtualizationMode was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceGetVirtualizationMode.Lock() + mock.calls.DeviceGetVirtualizationMode = append(mock.calls.DeviceGetVirtualizationMode, callInfo) + mock.lockDeviceGetVirtualizationMode.Unlock() + return mock.DeviceGetVirtualizationModeFunc(device) +} + +// DeviceGetVirtualizationModeCalls gets all the calls that were made to DeviceGetVirtualizationMode. +// Check the length with: +// +// len(mockedInterface.DeviceGetVirtualizationModeCalls()) +func (mock *Interface) DeviceGetVirtualizationModeCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceGetVirtualizationMode.RLock() + calls = mock.calls.DeviceGetVirtualizationMode + mock.lockDeviceGetVirtualizationMode.RUnlock() + return calls +} + +// DeviceIsMigDeviceHandle calls DeviceIsMigDeviceHandleFunc. +func (mock *Interface) DeviceIsMigDeviceHandle(device nvml.Device) (bool, nvml.Return) { + if mock.DeviceIsMigDeviceHandleFunc == nil { + panic("Interface.DeviceIsMigDeviceHandleFunc: method is nil but Interface.DeviceIsMigDeviceHandle was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceIsMigDeviceHandle.Lock() + mock.calls.DeviceIsMigDeviceHandle = append(mock.calls.DeviceIsMigDeviceHandle, callInfo) + mock.lockDeviceIsMigDeviceHandle.Unlock() + return mock.DeviceIsMigDeviceHandleFunc(device) +} + +// DeviceIsMigDeviceHandleCalls gets all the calls that were made to DeviceIsMigDeviceHandle. +// Check the length with: +// +// len(mockedInterface.DeviceIsMigDeviceHandleCalls()) +func (mock *Interface) DeviceIsMigDeviceHandleCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceIsMigDeviceHandle.RLock() + calls = mock.calls.DeviceIsMigDeviceHandle + mock.lockDeviceIsMigDeviceHandle.RUnlock() + return calls +} + +// DeviceModifyDrainState calls DeviceModifyDrainStateFunc. +func (mock *Interface) DeviceModifyDrainState(pciInfo *nvml.PciInfo, enableState nvml.EnableState) nvml.Return { + if mock.DeviceModifyDrainStateFunc == nil { + panic("Interface.DeviceModifyDrainStateFunc: method is nil but Interface.DeviceModifyDrainState was just called") + } + callInfo := struct { + PciInfo *nvml.PciInfo + EnableState nvml.EnableState + }{ + PciInfo: pciInfo, + EnableState: enableState, + } + mock.lockDeviceModifyDrainState.Lock() + mock.calls.DeviceModifyDrainState = append(mock.calls.DeviceModifyDrainState, callInfo) + mock.lockDeviceModifyDrainState.Unlock() + return mock.DeviceModifyDrainStateFunc(pciInfo, enableState) +} + +// DeviceModifyDrainStateCalls gets all the calls that were made to DeviceModifyDrainState. +// Check the length with: +// +// len(mockedInterface.DeviceModifyDrainStateCalls()) +func (mock *Interface) DeviceModifyDrainStateCalls() []struct { + PciInfo *nvml.PciInfo + EnableState nvml.EnableState +} { + var calls []struct { + PciInfo *nvml.PciInfo + EnableState nvml.EnableState + } + mock.lockDeviceModifyDrainState.RLock() + calls = mock.calls.DeviceModifyDrainState + mock.lockDeviceModifyDrainState.RUnlock() + return calls +} + +// DeviceOnSameBoard calls DeviceOnSameBoardFunc. +func (mock *Interface) DeviceOnSameBoard(device1 nvml.Device, device2 nvml.Device) (int, nvml.Return) { + if mock.DeviceOnSameBoardFunc == nil { + panic("Interface.DeviceOnSameBoardFunc: method is nil but Interface.DeviceOnSameBoard was just called") + } + callInfo := struct { + Device1 nvml.Device + Device2 nvml.Device + }{ + Device1: device1, + Device2: device2, + } + mock.lockDeviceOnSameBoard.Lock() + mock.calls.DeviceOnSameBoard = append(mock.calls.DeviceOnSameBoard, callInfo) + mock.lockDeviceOnSameBoard.Unlock() + return mock.DeviceOnSameBoardFunc(device1, device2) +} + +// DeviceOnSameBoardCalls gets all the calls that were made to DeviceOnSameBoard. +// Check the length with: +// +// len(mockedInterface.DeviceOnSameBoardCalls()) +func (mock *Interface) DeviceOnSameBoardCalls() []struct { + Device1 nvml.Device + Device2 nvml.Device +} { + var calls []struct { + Device1 nvml.Device + Device2 nvml.Device + } + mock.lockDeviceOnSameBoard.RLock() + calls = mock.calls.DeviceOnSameBoard + mock.lockDeviceOnSameBoard.RUnlock() + return calls +} + +// DevicePowerSmoothingActivatePresetProfile calls DevicePowerSmoothingActivatePresetProfileFunc. +func (mock *Interface) DevicePowerSmoothingActivatePresetProfile(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { + if mock.DevicePowerSmoothingActivatePresetProfileFunc == nil { + panic("Interface.DevicePowerSmoothingActivatePresetProfileFunc: method is nil but Interface.DevicePowerSmoothingActivatePresetProfile was just called") + } + callInfo := struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile + }{ + Device: device, + PowerSmoothingProfile: powerSmoothingProfile, + } + mock.lockDevicePowerSmoothingActivatePresetProfile.Lock() + mock.calls.DevicePowerSmoothingActivatePresetProfile = append(mock.calls.DevicePowerSmoothingActivatePresetProfile, callInfo) + mock.lockDevicePowerSmoothingActivatePresetProfile.Unlock() + return mock.DevicePowerSmoothingActivatePresetProfileFunc(device, powerSmoothingProfile) +} + +// DevicePowerSmoothingActivatePresetProfileCalls gets all the calls that were made to DevicePowerSmoothingActivatePresetProfile. +// Check the length with: +// +// len(mockedInterface.DevicePowerSmoothingActivatePresetProfileCalls()) +func (mock *Interface) DevicePowerSmoothingActivatePresetProfileCalls() []struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile +} { + var calls []struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + mock.lockDevicePowerSmoothingActivatePresetProfile.RLock() + calls = mock.calls.DevicePowerSmoothingActivatePresetProfile + mock.lockDevicePowerSmoothingActivatePresetProfile.RUnlock() + return calls +} + +// DevicePowerSmoothingSetState calls DevicePowerSmoothingSetStateFunc. +func (mock *Interface) DevicePowerSmoothingSetState(device nvml.Device, powerSmoothingState *nvml.PowerSmoothingState) nvml.Return { + if mock.DevicePowerSmoothingSetStateFunc == nil { + panic("Interface.DevicePowerSmoothingSetStateFunc: method is nil but Interface.DevicePowerSmoothingSetState was just called") + } + callInfo := struct { + Device nvml.Device + PowerSmoothingState *nvml.PowerSmoothingState + }{ + Device: device, + PowerSmoothingState: powerSmoothingState, + } + mock.lockDevicePowerSmoothingSetState.Lock() + mock.calls.DevicePowerSmoothingSetState = append(mock.calls.DevicePowerSmoothingSetState, callInfo) + mock.lockDevicePowerSmoothingSetState.Unlock() + return mock.DevicePowerSmoothingSetStateFunc(device, powerSmoothingState) +} + +// DevicePowerSmoothingSetStateCalls gets all the calls that were made to DevicePowerSmoothingSetState. +// Check the length with: +// +// len(mockedInterface.DevicePowerSmoothingSetStateCalls()) +func (mock *Interface) DevicePowerSmoothingSetStateCalls() []struct { + Device nvml.Device + PowerSmoothingState *nvml.PowerSmoothingState +} { + var calls []struct { + Device nvml.Device + PowerSmoothingState *nvml.PowerSmoothingState + } + mock.lockDevicePowerSmoothingSetState.RLock() + calls = mock.calls.DevicePowerSmoothingSetState + mock.lockDevicePowerSmoothingSetState.RUnlock() + return calls +} + +// DevicePowerSmoothingUpdatePresetProfileParam calls DevicePowerSmoothingUpdatePresetProfileParamFunc. +func (mock *Interface) DevicePowerSmoothingUpdatePresetProfileParam(device nvml.Device, powerSmoothingProfile *nvml.PowerSmoothingProfile) nvml.Return { + if mock.DevicePowerSmoothingUpdatePresetProfileParamFunc == nil { + panic("Interface.DevicePowerSmoothingUpdatePresetProfileParamFunc: method is nil but Interface.DevicePowerSmoothingUpdatePresetProfileParam was just called") + } + callInfo := struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile + }{ + Device: device, + PowerSmoothingProfile: powerSmoothingProfile, + } + mock.lockDevicePowerSmoothingUpdatePresetProfileParam.Lock() + mock.calls.DevicePowerSmoothingUpdatePresetProfileParam = append(mock.calls.DevicePowerSmoothingUpdatePresetProfileParam, callInfo) + mock.lockDevicePowerSmoothingUpdatePresetProfileParam.Unlock() + return mock.DevicePowerSmoothingUpdatePresetProfileParamFunc(device, powerSmoothingProfile) +} + +// DevicePowerSmoothingUpdatePresetProfileParamCalls gets all the calls that were made to DevicePowerSmoothingUpdatePresetProfileParam. +// Check the length with: +// +// len(mockedInterface.DevicePowerSmoothingUpdatePresetProfileParamCalls()) +func (mock *Interface) DevicePowerSmoothingUpdatePresetProfileParamCalls() []struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile +} { + var calls []struct { + Device nvml.Device + PowerSmoothingProfile *nvml.PowerSmoothingProfile + } + mock.lockDevicePowerSmoothingUpdatePresetProfileParam.RLock() + calls = mock.calls.DevicePowerSmoothingUpdatePresetProfileParam + mock.lockDevicePowerSmoothingUpdatePresetProfileParam.RUnlock() + return calls +} + +// DeviceQueryDrainState calls DeviceQueryDrainStateFunc. +func (mock *Interface) DeviceQueryDrainState(pciInfo *nvml.PciInfo) (nvml.EnableState, nvml.Return) { + if mock.DeviceQueryDrainStateFunc == nil { + panic("Interface.DeviceQueryDrainStateFunc: method is nil but Interface.DeviceQueryDrainState was just called") + } + callInfo := struct { + PciInfo *nvml.PciInfo + }{ + PciInfo: pciInfo, + } + mock.lockDeviceQueryDrainState.Lock() + mock.calls.DeviceQueryDrainState = append(mock.calls.DeviceQueryDrainState, callInfo) + mock.lockDeviceQueryDrainState.Unlock() + return mock.DeviceQueryDrainStateFunc(pciInfo) +} + +// DeviceQueryDrainStateCalls gets all the calls that were made to DeviceQueryDrainState. +// Check the length with: +// +// len(mockedInterface.DeviceQueryDrainStateCalls()) +func (mock *Interface) DeviceQueryDrainStateCalls() []struct { + PciInfo *nvml.PciInfo +} { + var calls []struct { + PciInfo *nvml.PciInfo + } + mock.lockDeviceQueryDrainState.RLock() + calls = mock.calls.DeviceQueryDrainState + mock.lockDeviceQueryDrainState.RUnlock() + return calls +} + +// DeviceReadWritePRM_v1 calls DeviceReadWritePRM_v1Func. +func (mock *Interface) DeviceReadWritePRM_v1(device nvml.Device, pRMTLV_v1 *nvml.PRMTLV_v1) nvml.Return { + if mock.DeviceReadWritePRM_v1Func == nil { + panic("Interface.DeviceReadWritePRM_v1Func: method is nil but Interface.DeviceReadWritePRM_v1 was just called") + } + callInfo := struct { + Device nvml.Device + PRMTLV_v1 *nvml.PRMTLV_v1 + }{ + Device: device, + PRMTLV_v1: pRMTLV_v1, + } + mock.lockDeviceReadWritePRM_v1.Lock() + mock.calls.DeviceReadWritePRM_v1 = append(mock.calls.DeviceReadWritePRM_v1, callInfo) + mock.lockDeviceReadWritePRM_v1.Unlock() + return mock.DeviceReadWritePRM_v1Func(device, pRMTLV_v1) +} + +// DeviceReadWritePRM_v1Calls gets all the calls that were made to DeviceReadWritePRM_v1. +// Check the length with: +// +// len(mockedInterface.DeviceReadWritePRM_v1Calls()) +func (mock *Interface) DeviceReadWritePRM_v1Calls() []struct { + Device nvml.Device + PRMTLV_v1 *nvml.PRMTLV_v1 +} { + var calls []struct { + Device nvml.Device + PRMTLV_v1 *nvml.PRMTLV_v1 + } + mock.lockDeviceReadWritePRM_v1.RLock() + calls = mock.calls.DeviceReadWritePRM_v1 + mock.lockDeviceReadWritePRM_v1.RUnlock() + return calls +} + +// DeviceRegisterEvents calls DeviceRegisterEventsFunc. +func (mock *Interface) DeviceRegisterEvents(device nvml.Device, v uint64, eventSet nvml.EventSet) nvml.Return { + if mock.DeviceRegisterEventsFunc == nil { + panic("Interface.DeviceRegisterEventsFunc: method is nil but Interface.DeviceRegisterEvents was just called") + } + callInfo := struct { + Device nvml.Device + V uint64 + EventSet nvml.EventSet + }{ + Device: device, + V: v, + EventSet: eventSet, + } + mock.lockDeviceRegisterEvents.Lock() + mock.calls.DeviceRegisterEvents = append(mock.calls.DeviceRegisterEvents, callInfo) + mock.lockDeviceRegisterEvents.Unlock() + return mock.DeviceRegisterEventsFunc(device, v, eventSet) +} + +// DeviceRegisterEventsCalls gets all the calls that were made to DeviceRegisterEvents. +// Check the length with: +// +// len(mockedInterface.DeviceRegisterEventsCalls()) +func (mock *Interface) DeviceRegisterEventsCalls() []struct { + Device nvml.Device + V uint64 + EventSet nvml.EventSet +} { + var calls []struct { + Device nvml.Device + V uint64 + EventSet nvml.EventSet + } + mock.lockDeviceRegisterEvents.RLock() + calls = mock.calls.DeviceRegisterEvents + mock.lockDeviceRegisterEvents.RUnlock() + return calls +} + +// DeviceRemoveGpu calls DeviceRemoveGpuFunc. +func (mock *Interface) DeviceRemoveGpu(pciInfo *nvml.PciInfo) nvml.Return { + if mock.DeviceRemoveGpuFunc == nil { + panic("Interface.DeviceRemoveGpuFunc: method is nil but Interface.DeviceRemoveGpu was just called") + } + callInfo := struct { + PciInfo *nvml.PciInfo + }{ + PciInfo: pciInfo, + } + mock.lockDeviceRemoveGpu.Lock() + mock.calls.DeviceRemoveGpu = append(mock.calls.DeviceRemoveGpu, callInfo) + mock.lockDeviceRemoveGpu.Unlock() + return mock.DeviceRemoveGpuFunc(pciInfo) +} + +// DeviceRemoveGpuCalls gets all the calls that were made to DeviceRemoveGpu. +// Check the length with: +// +// len(mockedInterface.DeviceRemoveGpuCalls()) +func (mock *Interface) DeviceRemoveGpuCalls() []struct { + PciInfo *nvml.PciInfo +} { + var calls []struct { + PciInfo *nvml.PciInfo + } + mock.lockDeviceRemoveGpu.RLock() + calls = mock.calls.DeviceRemoveGpu + mock.lockDeviceRemoveGpu.RUnlock() + return calls +} + +// DeviceRemoveGpu_v2 calls DeviceRemoveGpu_v2Func. +func (mock *Interface) DeviceRemoveGpu_v2(pciInfo *nvml.PciInfo, detachGpuState nvml.DetachGpuState, pcieLinkState nvml.PcieLinkState) nvml.Return { + if mock.DeviceRemoveGpu_v2Func == nil { + panic("Interface.DeviceRemoveGpu_v2Func: method is nil but Interface.DeviceRemoveGpu_v2 was just called") + } + callInfo := struct { + PciInfo *nvml.PciInfo + DetachGpuState nvml.DetachGpuState + PcieLinkState nvml.PcieLinkState + }{ + PciInfo: pciInfo, + DetachGpuState: detachGpuState, + PcieLinkState: pcieLinkState, + } + mock.lockDeviceRemoveGpu_v2.Lock() + mock.calls.DeviceRemoveGpu_v2 = append(mock.calls.DeviceRemoveGpu_v2, callInfo) + mock.lockDeviceRemoveGpu_v2.Unlock() + return mock.DeviceRemoveGpu_v2Func(pciInfo, detachGpuState, pcieLinkState) +} + +// DeviceRemoveGpu_v2Calls gets all the calls that were made to DeviceRemoveGpu_v2. +// Check the length with: +// +// len(mockedInterface.DeviceRemoveGpu_v2Calls()) +func (mock *Interface) DeviceRemoveGpu_v2Calls() []struct { + PciInfo *nvml.PciInfo + DetachGpuState nvml.DetachGpuState + PcieLinkState nvml.PcieLinkState +} { + var calls []struct { + PciInfo *nvml.PciInfo + DetachGpuState nvml.DetachGpuState + PcieLinkState nvml.PcieLinkState + } + mock.lockDeviceRemoveGpu_v2.RLock() + calls = mock.calls.DeviceRemoveGpu_v2 + mock.lockDeviceRemoveGpu_v2.RUnlock() + return calls +} + +// DeviceResetApplicationsClocks calls DeviceResetApplicationsClocksFunc. +func (mock *Interface) DeviceResetApplicationsClocks(device nvml.Device) nvml.Return { + if mock.DeviceResetApplicationsClocksFunc == nil { + panic("Interface.DeviceResetApplicationsClocksFunc: method is nil but Interface.DeviceResetApplicationsClocks was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceResetApplicationsClocks.Lock() + mock.calls.DeviceResetApplicationsClocks = append(mock.calls.DeviceResetApplicationsClocks, callInfo) + mock.lockDeviceResetApplicationsClocks.Unlock() + return mock.DeviceResetApplicationsClocksFunc(device) +} + +// DeviceResetApplicationsClocksCalls gets all the calls that were made to DeviceResetApplicationsClocks. +// Check the length with: +// +// len(mockedInterface.DeviceResetApplicationsClocksCalls()) +func (mock *Interface) DeviceResetApplicationsClocksCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceResetApplicationsClocks.RLock() + calls = mock.calls.DeviceResetApplicationsClocks + mock.lockDeviceResetApplicationsClocks.RUnlock() + return calls +} + +// DeviceResetGpuLockedClocks calls DeviceResetGpuLockedClocksFunc. +func (mock *Interface) DeviceResetGpuLockedClocks(device nvml.Device) nvml.Return { + if mock.DeviceResetGpuLockedClocksFunc == nil { + panic("Interface.DeviceResetGpuLockedClocksFunc: method is nil but Interface.DeviceResetGpuLockedClocks was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceResetGpuLockedClocks.Lock() + mock.calls.DeviceResetGpuLockedClocks = append(mock.calls.DeviceResetGpuLockedClocks, callInfo) + mock.lockDeviceResetGpuLockedClocks.Unlock() + return mock.DeviceResetGpuLockedClocksFunc(device) +} + +// DeviceResetGpuLockedClocksCalls gets all the calls that were made to DeviceResetGpuLockedClocks. +// Check the length with: +// +// len(mockedInterface.DeviceResetGpuLockedClocksCalls()) +func (mock *Interface) DeviceResetGpuLockedClocksCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceResetGpuLockedClocks.RLock() + calls = mock.calls.DeviceResetGpuLockedClocks + mock.lockDeviceResetGpuLockedClocks.RUnlock() + return calls +} + +// DeviceResetMemoryLockedClocks calls DeviceResetMemoryLockedClocksFunc. +func (mock *Interface) DeviceResetMemoryLockedClocks(device nvml.Device) nvml.Return { + if mock.DeviceResetMemoryLockedClocksFunc == nil { + panic("Interface.DeviceResetMemoryLockedClocksFunc: method is nil but Interface.DeviceResetMemoryLockedClocks was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceResetMemoryLockedClocks.Lock() + mock.calls.DeviceResetMemoryLockedClocks = append(mock.calls.DeviceResetMemoryLockedClocks, callInfo) + mock.lockDeviceResetMemoryLockedClocks.Unlock() + return mock.DeviceResetMemoryLockedClocksFunc(device) +} + +// DeviceResetMemoryLockedClocksCalls gets all the calls that were made to DeviceResetMemoryLockedClocks. +// Check the length with: +// +// len(mockedInterface.DeviceResetMemoryLockedClocksCalls()) +func (mock *Interface) DeviceResetMemoryLockedClocksCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceResetMemoryLockedClocks.RLock() + calls = mock.calls.DeviceResetMemoryLockedClocks + mock.lockDeviceResetMemoryLockedClocks.RUnlock() + return calls +} + +// DeviceResetNvLinkErrorCounters calls DeviceResetNvLinkErrorCountersFunc. +func (mock *Interface) DeviceResetNvLinkErrorCounters(device nvml.Device, n int) nvml.Return { + if mock.DeviceResetNvLinkErrorCountersFunc == nil { + panic("Interface.DeviceResetNvLinkErrorCountersFunc: method is nil but Interface.DeviceResetNvLinkErrorCounters was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceResetNvLinkErrorCounters.Lock() + mock.calls.DeviceResetNvLinkErrorCounters = append(mock.calls.DeviceResetNvLinkErrorCounters, callInfo) + mock.lockDeviceResetNvLinkErrorCounters.Unlock() + return mock.DeviceResetNvLinkErrorCountersFunc(device, n) +} + +// DeviceResetNvLinkErrorCountersCalls gets all the calls that were made to DeviceResetNvLinkErrorCounters. +// Check the length with: +// +// len(mockedInterface.DeviceResetNvLinkErrorCountersCalls()) +func (mock *Interface) DeviceResetNvLinkErrorCountersCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceResetNvLinkErrorCounters.RLock() + calls = mock.calls.DeviceResetNvLinkErrorCounters + mock.lockDeviceResetNvLinkErrorCounters.RUnlock() + return calls +} + +// DeviceResetNvLinkUtilizationCounter calls DeviceResetNvLinkUtilizationCounterFunc. +func (mock *Interface) DeviceResetNvLinkUtilizationCounter(device nvml.Device, n1 int, n2 int) nvml.Return { + if mock.DeviceResetNvLinkUtilizationCounterFunc == nil { + panic("Interface.DeviceResetNvLinkUtilizationCounterFunc: method is nil but Interface.DeviceResetNvLinkUtilizationCounter was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + }{ + Device: device, + N1: n1, + N2: n2, + } + mock.lockDeviceResetNvLinkUtilizationCounter.Lock() + mock.calls.DeviceResetNvLinkUtilizationCounter = append(mock.calls.DeviceResetNvLinkUtilizationCounter, callInfo) + mock.lockDeviceResetNvLinkUtilizationCounter.Unlock() + return mock.DeviceResetNvLinkUtilizationCounterFunc(device, n1, n2) +} + +// DeviceResetNvLinkUtilizationCounterCalls gets all the calls that were made to DeviceResetNvLinkUtilizationCounter. +// Check the length with: +// +// len(mockedInterface.DeviceResetNvLinkUtilizationCounterCalls()) +func (mock *Interface) DeviceResetNvLinkUtilizationCounterCalls() []struct { + Device nvml.Device + N1 int + N2 int +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + } + mock.lockDeviceResetNvLinkUtilizationCounter.RLock() + calls = mock.calls.DeviceResetNvLinkUtilizationCounter + mock.lockDeviceResetNvLinkUtilizationCounter.RUnlock() + return calls +} + +// DeviceSetAPIRestriction calls DeviceSetAPIRestrictionFunc. +func (mock *Interface) DeviceSetAPIRestriction(device nvml.Device, restrictedAPI nvml.RestrictedAPI, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetAPIRestrictionFunc == nil { + panic("Interface.DeviceSetAPIRestrictionFunc: method is nil but Interface.DeviceSetAPIRestriction was just called") + } + callInfo := struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState + }{ + Device: device, + RestrictedAPI: restrictedAPI, + EnableState: enableState, + } + mock.lockDeviceSetAPIRestriction.Lock() + mock.calls.DeviceSetAPIRestriction = append(mock.calls.DeviceSetAPIRestriction, callInfo) + mock.lockDeviceSetAPIRestriction.Unlock() + return mock.DeviceSetAPIRestrictionFunc(device, restrictedAPI, enableState) +} + +// DeviceSetAPIRestrictionCalls gets all the calls that were made to DeviceSetAPIRestriction. +// Check the length with: +// +// len(mockedInterface.DeviceSetAPIRestrictionCalls()) +func (mock *Interface) DeviceSetAPIRestrictionCalls() []struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + RestrictedAPI nvml.RestrictedAPI + EnableState nvml.EnableState + } + mock.lockDeviceSetAPIRestriction.RLock() + calls = mock.calls.DeviceSetAPIRestriction + mock.lockDeviceSetAPIRestriction.RUnlock() + return calls +} + +// DeviceSetAccountingMode calls DeviceSetAccountingModeFunc. +func (mock *Interface) DeviceSetAccountingMode(device nvml.Device, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetAccountingModeFunc == nil { + panic("Interface.DeviceSetAccountingModeFunc: method is nil but Interface.DeviceSetAccountingMode was just called") + } + callInfo := struct { + Device nvml.Device + EnableState nvml.EnableState + }{ + Device: device, + EnableState: enableState, + } + mock.lockDeviceSetAccountingMode.Lock() + mock.calls.DeviceSetAccountingMode = append(mock.calls.DeviceSetAccountingMode, callInfo) + mock.lockDeviceSetAccountingMode.Unlock() + return mock.DeviceSetAccountingModeFunc(device, enableState) +} + +// DeviceSetAccountingModeCalls gets all the calls that were made to DeviceSetAccountingMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetAccountingModeCalls()) +func (mock *Interface) DeviceSetAccountingModeCalls() []struct { + Device nvml.Device + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + EnableState nvml.EnableState + } + mock.lockDeviceSetAccountingMode.RLock() + calls = mock.calls.DeviceSetAccountingMode + mock.lockDeviceSetAccountingMode.RUnlock() + return calls +} + +// DeviceSetApplicationsClocks calls DeviceSetApplicationsClocksFunc. +func (mock *Interface) DeviceSetApplicationsClocks(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { + if mock.DeviceSetApplicationsClocksFunc == nil { + panic("Interface.DeviceSetApplicationsClocksFunc: method is nil but Interface.DeviceSetApplicationsClocks was just called") + } + callInfo := struct { + Device nvml.Device + V1 uint32 + V2 uint32 + }{ + Device: device, + V1: v1, + V2: v2, + } + mock.lockDeviceSetApplicationsClocks.Lock() + mock.calls.DeviceSetApplicationsClocks = append(mock.calls.DeviceSetApplicationsClocks, callInfo) + mock.lockDeviceSetApplicationsClocks.Unlock() + return mock.DeviceSetApplicationsClocksFunc(device, v1, v2) +} + +// DeviceSetApplicationsClocksCalls gets all the calls that were made to DeviceSetApplicationsClocks. +// Check the length with: +// +// len(mockedInterface.DeviceSetApplicationsClocksCalls()) +func (mock *Interface) DeviceSetApplicationsClocksCalls() []struct { + Device nvml.Device + V1 uint32 + V2 uint32 +} { + var calls []struct { + Device nvml.Device + V1 uint32 + V2 uint32 + } + mock.lockDeviceSetApplicationsClocks.RLock() + calls = mock.calls.DeviceSetApplicationsClocks + mock.lockDeviceSetApplicationsClocks.RUnlock() + return calls +} + +// DeviceSetAutoBoostedClocksEnabled calls DeviceSetAutoBoostedClocksEnabledFunc. +func (mock *Interface) DeviceSetAutoBoostedClocksEnabled(device nvml.Device, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetAutoBoostedClocksEnabledFunc == nil { + panic("Interface.DeviceSetAutoBoostedClocksEnabledFunc: method is nil but Interface.DeviceSetAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + Device nvml.Device + EnableState nvml.EnableState + }{ + Device: device, + EnableState: enableState, + } + mock.lockDeviceSetAutoBoostedClocksEnabled.Lock() + mock.calls.DeviceSetAutoBoostedClocksEnabled = append(mock.calls.DeviceSetAutoBoostedClocksEnabled, callInfo) + mock.lockDeviceSetAutoBoostedClocksEnabled.Unlock() + return mock.DeviceSetAutoBoostedClocksEnabledFunc(device, enableState) +} + +// DeviceSetAutoBoostedClocksEnabledCalls gets all the calls that were made to DeviceSetAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedInterface.DeviceSetAutoBoostedClocksEnabledCalls()) +func (mock *Interface) DeviceSetAutoBoostedClocksEnabledCalls() []struct { + Device nvml.Device + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + EnableState nvml.EnableState + } + mock.lockDeviceSetAutoBoostedClocksEnabled.RLock() + calls = mock.calls.DeviceSetAutoBoostedClocksEnabled + mock.lockDeviceSetAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// DeviceSetClockOffsets calls DeviceSetClockOffsetsFunc. +func (mock *Interface) DeviceSetClockOffsets(device nvml.Device, clockOffset nvml.ClockOffset) nvml.Return { + if mock.DeviceSetClockOffsetsFunc == nil { + panic("Interface.DeviceSetClockOffsetsFunc: method is nil but Interface.DeviceSetClockOffsets was just called") + } + callInfo := struct { + Device nvml.Device + ClockOffset nvml.ClockOffset + }{ + Device: device, + ClockOffset: clockOffset, + } + mock.lockDeviceSetClockOffsets.Lock() + mock.calls.DeviceSetClockOffsets = append(mock.calls.DeviceSetClockOffsets, callInfo) + mock.lockDeviceSetClockOffsets.Unlock() + return mock.DeviceSetClockOffsetsFunc(device, clockOffset) +} + +// DeviceSetClockOffsetsCalls gets all the calls that were made to DeviceSetClockOffsets. +// Check the length with: +// +// len(mockedInterface.DeviceSetClockOffsetsCalls()) +func (mock *Interface) DeviceSetClockOffsetsCalls() []struct { + Device nvml.Device + ClockOffset nvml.ClockOffset +} { + var calls []struct { + Device nvml.Device + ClockOffset nvml.ClockOffset + } + mock.lockDeviceSetClockOffsets.RLock() + calls = mock.calls.DeviceSetClockOffsets + mock.lockDeviceSetClockOffsets.RUnlock() + return calls +} + +// DeviceSetComputeMode calls DeviceSetComputeModeFunc. +func (mock *Interface) DeviceSetComputeMode(device nvml.Device, computeMode nvml.ComputeMode) nvml.Return { + if mock.DeviceSetComputeModeFunc == nil { + panic("Interface.DeviceSetComputeModeFunc: method is nil but Interface.DeviceSetComputeMode was just called") + } + callInfo := struct { + Device nvml.Device + ComputeMode nvml.ComputeMode + }{ + Device: device, + ComputeMode: computeMode, + } + mock.lockDeviceSetComputeMode.Lock() + mock.calls.DeviceSetComputeMode = append(mock.calls.DeviceSetComputeMode, callInfo) + mock.lockDeviceSetComputeMode.Unlock() + return mock.DeviceSetComputeModeFunc(device, computeMode) +} + +// DeviceSetComputeModeCalls gets all the calls that were made to DeviceSetComputeMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetComputeModeCalls()) +func (mock *Interface) DeviceSetComputeModeCalls() []struct { + Device nvml.Device + ComputeMode nvml.ComputeMode +} { + var calls []struct { + Device nvml.Device + ComputeMode nvml.ComputeMode + } + mock.lockDeviceSetComputeMode.RLock() + calls = mock.calls.DeviceSetComputeMode + mock.lockDeviceSetComputeMode.RUnlock() + return calls +} + +// DeviceSetConfComputeUnprotectedMemSize calls DeviceSetConfComputeUnprotectedMemSizeFunc. +func (mock *Interface) DeviceSetConfComputeUnprotectedMemSize(device nvml.Device, v uint64) nvml.Return { + if mock.DeviceSetConfComputeUnprotectedMemSizeFunc == nil { + panic("Interface.DeviceSetConfComputeUnprotectedMemSizeFunc: method is nil but Interface.DeviceSetConfComputeUnprotectedMemSize was just called") + } + callInfo := struct { + Device nvml.Device + V uint64 + }{ + Device: device, + V: v, + } + mock.lockDeviceSetConfComputeUnprotectedMemSize.Lock() + mock.calls.DeviceSetConfComputeUnprotectedMemSize = append(mock.calls.DeviceSetConfComputeUnprotectedMemSize, callInfo) + mock.lockDeviceSetConfComputeUnprotectedMemSize.Unlock() + return mock.DeviceSetConfComputeUnprotectedMemSizeFunc(device, v) +} + +// DeviceSetConfComputeUnprotectedMemSizeCalls gets all the calls that were made to DeviceSetConfComputeUnprotectedMemSize. +// Check the length with: +// +// len(mockedInterface.DeviceSetConfComputeUnprotectedMemSizeCalls()) +func (mock *Interface) DeviceSetConfComputeUnprotectedMemSizeCalls() []struct { + Device nvml.Device + V uint64 +} { + var calls []struct { + Device nvml.Device + V uint64 + } + mock.lockDeviceSetConfComputeUnprotectedMemSize.RLock() + calls = mock.calls.DeviceSetConfComputeUnprotectedMemSize + mock.lockDeviceSetConfComputeUnprotectedMemSize.RUnlock() + return calls +} + +// DeviceSetCpuAffinity calls DeviceSetCpuAffinityFunc. +func (mock *Interface) DeviceSetCpuAffinity(device nvml.Device) nvml.Return { + if mock.DeviceSetCpuAffinityFunc == nil { + panic("Interface.DeviceSetCpuAffinityFunc: method is nil but Interface.DeviceSetCpuAffinity was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceSetCpuAffinity.Lock() + mock.calls.DeviceSetCpuAffinity = append(mock.calls.DeviceSetCpuAffinity, callInfo) + mock.lockDeviceSetCpuAffinity.Unlock() + return mock.DeviceSetCpuAffinityFunc(device) +} + +// DeviceSetCpuAffinityCalls gets all the calls that were made to DeviceSetCpuAffinity. +// Check the length with: +// +// len(mockedInterface.DeviceSetCpuAffinityCalls()) +func (mock *Interface) DeviceSetCpuAffinityCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceSetCpuAffinity.RLock() + calls = mock.calls.DeviceSetCpuAffinity + mock.lockDeviceSetCpuAffinity.RUnlock() + return calls +} + +// DeviceSetDefaultAutoBoostedClocksEnabled calls DeviceSetDefaultAutoBoostedClocksEnabledFunc. +func (mock *Interface) DeviceSetDefaultAutoBoostedClocksEnabled(device nvml.Device, enableState nvml.EnableState, v uint32) nvml.Return { + if mock.DeviceSetDefaultAutoBoostedClocksEnabledFunc == nil { + panic("Interface.DeviceSetDefaultAutoBoostedClocksEnabledFunc: method is nil but Interface.DeviceSetDefaultAutoBoostedClocksEnabled was just called") + } + callInfo := struct { + Device nvml.Device + EnableState nvml.EnableState + V uint32 + }{ + Device: device, + EnableState: enableState, + V: v, + } + mock.lockDeviceSetDefaultAutoBoostedClocksEnabled.Lock() + mock.calls.DeviceSetDefaultAutoBoostedClocksEnabled = append(mock.calls.DeviceSetDefaultAutoBoostedClocksEnabled, callInfo) + mock.lockDeviceSetDefaultAutoBoostedClocksEnabled.Unlock() + return mock.DeviceSetDefaultAutoBoostedClocksEnabledFunc(device, enableState, v) +} + +// DeviceSetDefaultAutoBoostedClocksEnabledCalls gets all the calls that were made to DeviceSetDefaultAutoBoostedClocksEnabled. +// Check the length with: +// +// len(mockedInterface.DeviceSetDefaultAutoBoostedClocksEnabledCalls()) +func (mock *Interface) DeviceSetDefaultAutoBoostedClocksEnabledCalls() []struct { + Device nvml.Device + EnableState nvml.EnableState + V uint32 +} { + var calls []struct { + Device nvml.Device + EnableState nvml.EnableState + V uint32 + } + mock.lockDeviceSetDefaultAutoBoostedClocksEnabled.RLock() + calls = mock.calls.DeviceSetDefaultAutoBoostedClocksEnabled + mock.lockDeviceSetDefaultAutoBoostedClocksEnabled.RUnlock() + return calls +} + +// DeviceSetDefaultFanSpeed_v2 calls DeviceSetDefaultFanSpeed_v2Func. +func (mock *Interface) DeviceSetDefaultFanSpeed_v2(device nvml.Device, n int) nvml.Return { + if mock.DeviceSetDefaultFanSpeed_v2Func == nil { + panic("Interface.DeviceSetDefaultFanSpeed_v2Func: method is nil but Interface.DeviceSetDefaultFanSpeed_v2 was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceSetDefaultFanSpeed_v2.Lock() + mock.calls.DeviceSetDefaultFanSpeed_v2 = append(mock.calls.DeviceSetDefaultFanSpeed_v2, callInfo) + mock.lockDeviceSetDefaultFanSpeed_v2.Unlock() + return mock.DeviceSetDefaultFanSpeed_v2Func(device, n) +} + +// DeviceSetDefaultFanSpeed_v2Calls gets all the calls that were made to DeviceSetDefaultFanSpeed_v2. +// Check the length with: +// +// len(mockedInterface.DeviceSetDefaultFanSpeed_v2Calls()) +func (mock *Interface) DeviceSetDefaultFanSpeed_v2Calls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceSetDefaultFanSpeed_v2.RLock() + calls = mock.calls.DeviceSetDefaultFanSpeed_v2 + mock.lockDeviceSetDefaultFanSpeed_v2.RUnlock() + return calls +} + +// DeviceSetDramEncryptionMode calls DeviceSetDramEncryptionModeFunc. +func (mock *Interface) DeviceSetDramEncryptionMode(device nvml.Device, dramEncryptionInfo *nvml.DramEncryptionInfo) nvml.Return { + if mock.DeviceSetDramEncryptionModeFunc == nil { + panic("Interface.DeviceSetDramEncryptionModeFunc: method is nil but Interface.DeviceSetDramEncryptionMode was just called") + } + callInfo := struct { + Device nvml.Device + DramEncryptionInfo *nvml.DramEncryptionInfo + }{ + Device: device, + DramEncryptionInfo: dramEncryptionInfo, + } + mock.lockDeviceSetDramEncryptionMode.Lock() + mock.calls.DeviceSetDramEncryptionMode = append(mock.calls.DeviceSetDramEncryptionMode, callInfo) + mock.lockDeviceSetDramEncryptionMode.Unlock() + return mock.DeviceSetDramEncryptionModeFunc(device, dramEncryptionInfo) +} + +// DeviceSetDramEncryptionModeCalls gets all the calls that were made to DeviceSetDramEncryptionMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetDramEncryptionModeCalls()) +func (mock *Interface) DeviceSetDramEncryptionModeCalls() []struct { + Device nvml.Device + DramEncryptionInfo *nvml.DramEncryptionInfo +} { + var calls []struct { + Device nvml.Device + DramEncryptionInfo *nvml.DramEncryptionInfo + } + mock.lockDeviceSetDramEncryptionMode.RLock() + calls = mock.calls.DeviceSetDramEncryptionMode + mock.lockDeviceSetDramEncryptionMode.RUnlock() + return calls +} + +// DeviceSetDriverModel calls DeviceSetDriverModelFunc. +func (mock *Interface) DeviceSetDriverModel(device nvml.Device, driverModel nvml.DriverModel, v uint32) nvml.Return { + if mock.DeviceSetDriverModelFunc == nil { + panic("Interface.DeviceSetDriverModelFunc: method is nil but Interface.DeviceSetDriverModel was just called") + } + callInfo := struct { + Device nvml.Device + DriverModel nvml.DriverModel + V uint32 + }{ + Device: device, + DriverModel: driverModel, + V: v, + } + mock.lockDeviceSetDriverModel.Lock() + mock.calls.DeviceSetDriverModel = append(mock.calls.DeviceSetDriverModel, callInfo) + mock.lockDeviceSetDriverModel.Unlock() + return mock.DeviceSetDriverModelFunc(device, driverModel, v) +} + +// DeviceSetDriverModelCalls gets all the calls that were made to DeviceSetDriverModel. +// Check the length with: +// +// len(mockedInterface.DeviceSetDriverModelCalls()) +func (mock *Interface) DeviceSetDriverModelCalls() []struct { + Device nvml.Device + DriverModel nvml.DriverModel + V uint32 +} { + var calls []struct { + Device nvml.Device + DriverModel nvml.DriverModel + V uint32 + } + mock.lockDeviceSetDriverModel.RLock() + calls = mock.calls.DeviceSetDriverModel + mock.lockDeviceSetDriverModel.RUnlock() + return calls +} + +// DeviceSetEccMode calls DeviceSetEccModeFunc. +func (mock *Interface) DeviceSetEccMode(device nvml.Device, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetEccModeFunc == nil { + panic("Interface.DeviceSetEccModeFunc: method is nil but Interface.DeviceSetEccMode was just called") + } + callInfo := struct { + Device nvml.Device + EnableState nvml.EnableState + }{ + Device: device, + EnableState: enableState, + } + mock.lockDeviceSetEccMode.Lock() + mock.calls.DeviceSetEccMode = append(mock.calls.DeviceSetEccMode, callInfo) + mock.lockDeviceSetEccMode.Unlock() + return mock.DeviceSetEccModeFunc(device, enableState) +} + +// DeviceSetEccModeCalls gets all the calls that were made to DeviceSetEccMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetEccModeCalls()) +func (mock *Interface) DeviceSetEccModeCalls() []struct { + Device nvml.Device + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + EnableState nvml.EnableState + } + mock.lockDeviceSetEccMode.RLock() + calls = mock.calls.DeviceSetEccMode + mock.lockDeviceSetEccMode.RUnlock() + return calls +} + +// DeviceSetFanControlPolicy calls DeviceSetFanControlPolicyFunc. +func (mock *Interface) DeviceSetFanControlPolicy(device nvml.Device, n int, fanControlPolicy nvml.FanControlPolicy) nvml.Return { + if mock.DeviceSetFanControlPolicyFunc == nil { + panic("Interface.DeviceSetFanControlPolicyFunc: method is nil but Interface.DeviceSetFanControlPolicy was just called") + } + callInfo := struct { + Device nvml.Device + N int + FanControlPolicy nvml.FanControlPolicy + }{ + Device: device, + N: n, + FanControlPolicy: fanControlPolicy, + } + mock.lockDeviceSetFanControlPolicy.Lock() + mock.calls.DeviceSetFanControlPolicy = append(mock.calls.DeviceSetFanControlPolicy, callInfo) + mock.lockDeviceSetFanControlPolicy.Unlock() + return mock.DeviceSetFanControlPolicyFunc(device, n, fanControlPolicy) +} + +// DeviceSetFanControlPolicyCalls gets all the calls that were made to DeviceSetFanControlPolicy. +// Check the length with: +// +// len(mockedInterface.DeviceSetFanControlPolicyCalls()) +func (mock *Interface) DeviceSetFanControlPolicyCalls() []struct { + Device nvml.Device + N int + FanControlPolicy nvml.FanControlPolicy +} { + var calls []struct { + Device nvml.Device + N int + FanControlPolicy nvml.FanControlPolicy + } + mock.lockDeviceSetFanControlPolicy.RLock() + calls = mock.calls.DeviceSetFanControlPolicy + mock.lockDeviceSetFanControlPolicy.RUnlock() + return calls +} + +// DeviceSetFanSpeed_v2 calls DeviceSetFanSpeed_v2Func. +func (mock *Interface) DeviceSetFanSpeed_v2(device nvml.Device, n1 int, n2 int) nvml.Return { + if mock.DeviceSetFanSpeed_v2Func == nil { + panic("Interface.DeviceSetFanSpeed_v2Func: method is nil but Interface.DeviceSetFanSpeed_v2 was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + }{ + Device: device, + N1: n1, + N2: n2, + } + mock.lockDeviceSetFanSpeed_v2.Lock() + mock.calls.DeviceSetFanSpeed_v2 = append(mock.calls.DeviceSetFanSpeed_v2, callInfo) + mock.lockDeviceSetFanSpeed_v2.Unlock() + return mock.DeviceSetFanSpeed_v2Func(device, n1, n2) +} + +// DeviceSetFanSpeed_v2Calls gets all the calls that were made to DeviceSetFanSpeed_v2. +// Check the length with: +// +// len(mockedInterface.DeviceSetFanSpeed_v2Calls()) +func (mock *Interface) DeviceSetFanSpeed_v2Calls() []struct { + Device nvml.Device + N1 int + N2 int +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + } + mock.lockDeviceSetFanSpeed_v2.RLock() + calls = mock.calls.DeviceSetFanSpeed_v2 + mock.lockDeviceSetFanSpeed_v2.RUnlock() + return calls +} + +// DeviceSetGpcClkVfOffset calls DeviceSetGpcClkVfOffsetFunc. +func (mock *Interface) DeviceSetGpcClkVfOffset(device nvml.Device, n int) nvml.Return { + if mock.DeviceSetGpcClkVfOffsetFunc == nil { + panic("Interface.DeviceSetGpcClkVfOffsetFunc: method is nil but Interface.DeviceSetGpcClkVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceSetGpcClkVfOffset.Lock() + mock.calls.DeviceSetGpcClkVfOffset = append(mock.calls.DeviceSetGpcClkVfOffset, callInfo) + mock.lockDeviceSetGpcClkVfOffset.Unlock() + return mock.DeviceSetGpcClkVfOffsetFunc(device, n) +} + +// DeviceSetGpcClkVfOffsetCalls gets all the calls that were made to DeviceSetGpcClkVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceSetGpcClkVfOffsetCalls()) +func (mock *Interface) DeviceSetGpcClkVfOffsetCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceSetGpcClkVfOffset.RLock() + calls = mock.calls.DeviceSetGpcClkVfOffset + mock.lockDeviceSetGpcClkVfOffset.RUnlock() + return calls +} + +// DeviceSetGpuLockedClocks calls DeviceSetGpuLockedClocksFunc. +func (mock *Interface) DeviceSetGpuLockedClocks(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { + if mock.DeviceSetGpuLockedClocksFunc == nil { + panic("Interface.DeviceSetGpuLockedClocksFunc: method is nil but Interface.DeviceSetGpuLockedClocks was just called") + } + callInfo := struct { + Device nvml.Device + V1 uint32 + V2 uint32 + }{ + Device: device, + V1: v1, + V2: v2, + } + mock.lockDeviceSetGpuLockedClocks.Lock() + mock.calls.DeviceSetGpuLockedClocks = append(mock.calls.DeviceSetGpuLockedClocks, callInfo) + mock.lockDeviceSetGpuLockedClocks.Unlock() + return mock.DeviceSetGpuLockedClocksFunc(device, v1, v2) +} + +// DeviceSetGpuLockedClocksCalls gets all the calls that were made to DeviceSetGpuLockedClocks. +// Check the length with: +// +// len(mockedInterface.DeviceSetGpuLockedClocksCalls()) +func (mock *Interface) DeviceSetGpuLockedClocksCalls() []struct { + Device nvml.Device + V1 uint32 + V2 uint32 +} { + var calls []struct { + Device nvml.Device + V1 uint32 + V2 uint32 + } + mock.lockDeviceSetGpuLockedClocks.RLock() + calls = mock.calls.DeviceSetGpuLockedClocks + mock.lockDeviceSetGpuLockedClocks.RUnlock() + return calls +} + +// DeviceSetGpuOperationMode calls DeviceSetGpuOperationModeFunc. +func (mock *Interface) DeviceSetGpuOperationMode(device nvml.Device, gpuOperationMode nvml.GpuOperationMode) nvml.Return { + if mock.DeviceSetGpuOperationModeFunc == nil { + panic("Interface.DeviceSetGpuOperationModeFunc: method is nil but Interface.DeviceSetGpuOperationMode was just called") + } + callInfo := struct { + Device nvml.Device + GpuOperationMode nvml.GpuOperationMode + }{ + Device: device, + GpuOperationMode: gpuOperationMode, + } + mock.lockDeviceSetGpuOperationMode.Lock() + mock.calls.DeviceSetGpuOperationMode = append(mock.calls.DeviceSetGpuOperationMode, callInfo) + mock.lockDeviceSetGpuOperationMode.Unlock() + return mock.DeviceSetGpuOperationModeFunc(device, gpuOperationMode) +} + +// DeviceSetGpuOperationModeCalls gets all the calls that were made to DeviceSetGpuOperationMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetGpuOperationModeCalls()) +func (mock *Interface) DeviceSetGpuOperationModeCalls() []struct { + Device nvml.Device + GpuOperationMode nvml.GpuOperationMode +} { + var calls []struct { + Device nvml.Device + GpuOperationMode nvml.GpuOperationMode + } + mock.lockDeviceSetGpuOperationMode.RLock() + calls = mock.calls.DeviceSetGpuOperationMode + mock.lockDeviceSetGpuOperationMode.RUnlock() + return calls +} + +// DeviceSetMemClkVfOffset calls DeviceSetMemClkVfOffsetFunc. +func (mock *Interface) DeviceSetMemClkVfOffset(device nvml.Device, n int) nvml.Return { + if mock.DeviceSetMemClkVfOffsetFunc == nil { + panic("Interface.DeviceSetMemClkVfOffsetFunc: method is nil but Interface.DeviceSetMemClkVfOffset was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceSetMemClkVfOffset.Lock() + mock.calls.DeviceSetMemClkVfOffset = append(mock.calls.DeviceSetMemClkVfOffset, callInfo) + mock.lockDeviceSetMemClkVfOffset.Unlock() + return mock.DeviceSetMemClkVfOffsetFunc(device, n) +} + +// DeviceSetMemClkVfOffsetCalls gets all the calls that were made to DeviceSetMemClkVfOffset. +// Check the length with: +// +// len(mockedInterface.DeviceSetMemClkVfOffsetCalls()) +func (mock *Interface) DeviceSetMemClkVfOffsetCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceSetMemClkVfOffset.RLock() + calls = mock.calls.DeviceSetMemClkVfOffset + mock.lockDeviceSetMemClkVfOffset.RUnlock() + return calls +} + +// DeviceSetMemoryLockedClocks calls DeviceSetMemoryLockedClocksFunc. +func (mock *Interface) DeviceSetMemoryLockedClocks(device nvml.Device, v1 uint32, v2 uint32) nvml.Return { + if mock.DeviceSetMemoryLockedClocksFunc == nil { + panic("Interface.DeviceSetMemoryLockedClocksFunc: method is nil but Interface.DeviceSetMemoryLockedClocks was just called") + } + callInfo := struct { + Device nvml.Device + V1 uint32 + V2 uint32 + }{ + Device: device, + V1: v1, + V2: v2, + } + mock.lockDeviceSetMemoryLockedClocks.Lock() + mock.calls.DeviceSetMemoryLockedClocks = append(mock.calls.DeviceSetMemoryLockedClocks, callInfo) + mock.lockDeviceSetMemoryLockedClocks.Unlock() + return mock.DeviceSetMemoryLockedClocksFunc(device, v1, v2) +} + +// DeviceSetMemoryLockedClocksCalls gets all the calls that were made to DeviceSetMemoryLockedClocks. +// Check the length with: +// +// len(mockedInterface.DeviceSetMemoryLockedClocksCalls()) +func (mock *Interface) DeviceSetMemoryLockedClocksCalls() []struct { + Device nvml.Device + V1 uint32 + V2 uint32 +} { + var calls []struct { + Device nvml.Device + V1 uint32 + V2 uint32 + } + mock.lockDeviceSetMemoryLockedClocks.RLock() + calls = mock.calls.DeviceSetMemoryLockedClocks + mock.lockDeviceSetMemoryLockedClocks.RUnlock() + return calls +} + +// DeviceSetMigMode calls DeviceSetMigModeFunc. +func (mock *Interface) DeviceSetMigMode(device nvml.Device, n int) (nvml.Return, nvml.Return) { + if mock.DeviceSetMigModeFunc == nil { + panic("Interface.DeviceSetMigModeFunc: method is nil but Interface.DeviceSetMigMode was just called") + } + callInfo := struct { + Device nvml.Device + N int + }{ + Device: device, + N: n, + } + mock.lockDeviceSetMigMode.Lock() + mock.calls.DeviceSetMigMode = append(mock.calls.DeviceSetMigMode, callInfo) + mock.lockDeviceSetMigMode.Unlock() + return mock.DeviceSetMigModeFunc(device, n) +} + +// DeviceSetMigModeCalls gets all the calls that were made to DeviceSetMigMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetMigModeCalls()) +func (mock *Interface) DeviceSetMigModeCalls() []struct { + Device nvml.Device + N int +} { + var calls []struct { + Device nvml.Device + N int + } + mock.lockDeviceSetMigMode.RLock() + calls = mock.calls.DeviceSetMigMode + mock.lockDeviceSetMigMode.RUnlock() + return calls +} + +// DeviceSetNvLinkDeviceLowPowerThreshold calls DeviceSetNvLinkDeviceLowPowerThresholdFunc. +func (mock *Interface) DeviceSetNvLinkDeviceLowPowerThreshold(device nvml.Device, nvLinkPowerThres *nvml.NvLinkPowerThres) nvml.Return { + if mock.DeviceSetNvLinkDeviceLowPowerThresholdFunc == nil { + panic("Interface.DeviceSetNvLinkDeviceLowPowerThresholdFunc: method is nil but Interface.DeviceSetNvLinkDeviceLowPowerThreshold was just called") + } + callInfo := struct { + Device nvml.Device + NvLinkPowerThres *nvml.NvLinkPowerThres + }{ + Device: device, + NvLinkPowerThres: nvLinkPowerThres, + } + mock.lockDeviceSetNvLinkDeviceLowPowerThreshold.Lock() + mock.calls.DeviceSetNvLinkDeviceLowPowerThreshold = append(mock.calls.DeviceSetNvLinkDeviceLowPowerThreshold, callInfo) + mock.lockDeviceSetNvLinkDeviceLowPowerThreshold.Unlock() + return mock.DeviceSetNvLinkDeviceLowPowerThresholdFunc(device, nvLinkPowerThres) +} + +// DeviceSetNvLinkDeviceLowPowerThresholdCalls gets all the calls that were made to DeviceSetNvLinkDeviceLowPowerThreshold. +// Check the length with: +// +// len(mockedInterface.DeviceSetNvLinkDeviceLowPowerThresholdCalls()) +func (mock *Interface) DeviceSetNvLinkDeviceLowPowerThresholdCalls() []struct { + Device nvml.Device + NvLinkPowerThres *nvml.NvLinkPowerThres +} { + var calls []struct { + Device nvml.Device + NvLinkPowerThres *nvml.NvLinkPowerThres + } + mock.lockDeviceSetNvLinkDeviceLowPowerThreshold.RLock() + calls = mock.calls.DeviceSetNvLinkDeviceLowPowerThreshold + mock.lockDeviceSetNvLinkDeviceLowPowerThreshold.RUnlock() + return calls +} + +// DeviceSetNvLinkUtilizationControl calls DeviceSetNvLinkUtilizationControlFunc. +func (mock *Interface) DeviceSetNvLinkUtilizationControl(device nvml.Device, n1 int, n2 int, nvLinkUtilizationControl *nvml.NvLinkUtilizationControl, b bool) nvml.Return { + if mock.DeviceSetNvLinkUtilizationControlFunc == nil { + panic("Interface.DeviceSetNvLinkUtilizationControlFunc: method is nil but Interface.DeviceSetNvLinkUtilizationControl was just called") + } + callInfo := struct { + Device nvml.Device + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool + }{ + Device: device, + N1: n1, + N2: n2, + NvLinkUtilizationControl: nvLinkUtilizationControl, + B: b, + } + mock.lockDeviceSetNvLinkUtilizationControl.Lock() + mock.calls.DeviceSetNvLinkUtilizationControl = append(mock.calls.DeviceSetNvLinkUtilizationControl, callInfo) + mock.lockDeviceSetNvLinkUtilizationControl.Unlock() + return mock.DeviceSetNvLinkUtilizationControlFunc(device, n1, n2, nvLinkUtilizationControl, b) +} + +// DeviceSetNvLinkUtilizationControlCalls gets all the calls that were made to DeviceSetNvLinkUtilizationControl. +// Check the length with: +// +// len(mockedInterface.DeviceSetNvLinkUtilizationControlCalls()) +func (mock *Interface) DeviceSetNvLinkUtilizationControlCalls() []struct { + Device nvml.Device + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool +} { + var calls []struct { + Device nvml.Device + N1 int + N2 int + NvLinkUtilizationControl *nvml.NvLinkUtilizationControl + B bool + } + mock.lockDeviceSetNvLinkUtilizationControl.RLock() + calls = mock.calls.DeviceSetNvLinkUtilizationControl + mock.lockDeviceSetNvLinkUtilizationControl.RUnlock() + return calls +} + +// DeviceSetNvlinkBwMode calls DeviceSetNvlinkBwModeFunc. +func (mock *Interface) DeviceSetNvlinkBwMode(device nvml.Device, nvlinkSetBwMode *nvml.NvlinkSetBwMode) nvml.Return { + if mock.DeviceSetNvlinkBwModeFunc == nil { + panic("Interface.DeviceSetNvlinkBwModeFunc: method is nil but Interface.DeviceSetNvlinkBwMode was just called") + } + callInfo := struct { + Device nvml.Device + NvlinkSetBwMode *nvml.NvlinkSetBwMode + }{ + Device: device, + NvlinkSetBwMode: nvlinkSetBwMode, + } + mock.lockDeviceSetNvlinkBwMode.Lock() + mock.calls.DeviceSetNvlinkBwMode = append(mock.calls.DeviceSetNvlinkBwMode, callInfo) + mock.lockDeviceSetNvlinkBwMode.Unlock() + return mock.DeviceSetNvlinkBwModeFunc(device, nvlinkSetBwMode) +} + +// DeviceSetNvlinkBwModeCalls gets all the calls that were made to DeviceSetNvlinkBwMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetNvlinkBwModeCalls()) +func (mock *Interface) DeviceSetNvlinkBwModeCalls() []struct { + Device nvml.Device + NvlinkSetBwMode *nvml.NvlinkSetBwMode +} { + var calls []struct { + Device nvml.Device + NvlinkSetBwMode *nvml.NvlinkSetBwMode + } + mock.lockDeviceSetNvlinkBwMode.RLock() + calls = mock.calls.DeviceSetNvlinkBwMode + mock.lockDeviceSetNvlinkBwMode.RUnlock() + return calls +} + +// DeviceSetPersistenceMode calls DeviceSetPersistenceModeFunc. +func (mock *Interface) DeviceSetPersistenceMode(device nvml.Device, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetPersistenceModeFunc == nil { + panic("Interface.DeviceSetPersistenceModeFunc: method is nil but Interface.DeviceSetPersistenceMode was just called") + } + callInfo := struct { + Device nvml.Device + EnableState nvml.EnableState + }{ + Device: device, + EnableState: enableState, + } + mock.lockDeviceSetPersistenceMode.Lock() + mock.calls.DeviceSetPersistenceMode = append(mock.calls.DeviceSetPersistenceMode, callInfo) + mock.lockDeviceSetPersistenceMode.Unlock() + return mock.DeviceSetPersistenceModeFunc(device, enableState) +} + +// DeviceSetPersistenceModeCalls gets all the calls that were made to DeviceSetPersistenceMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetPersistenceModeCalls()) +func (mock *Interface) DeviceSetPersistenceModeCalls() []struct { + Device nvml.Device + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + EnableState nvml.EnableState + } + mock.lockDeviceSetPersistenceMode.RLock() + calls = mock.calls.DeviceSetPersistenceMode + mock.lockDeviceSetPersistenceMode.RUnlock() + return calls +} + +// DeviceSetPowerManagementLimit calls DeviceSetPowerManagementLimitFunc. +func (mock *Interface) DeviceSetPowerManagementLimit(device nvml.Device, v uint32) nvml.Return { + if mock.DeviceSetPowerManagementLimitFunc == nil { + panic("Interface.DeviceSetPowerManagementLimitFunc: method is nil but Interface.DeviceSetPowerManagementLimit was just called") + } + callInfo := struct { + Device nvml.Device + V uint32 + }{ + Device: device, + V: v, + } + mock.lockDeviceSetPowerManagementLimit.Lock() + mock.calls.DeviceSetPowerManagementLimit = append(mock.calls.DeviceSetPowerManagementLimit, callInfo) + mock.lockDeviceSetPowerManagementLimit.Unlock() + return mock.DeviceSetPowerManagementLimitFunc(device, v) +} + +// DeviceSetPowerManagementLimitCalls gets all the calls that were made to DeviceSetPowerManagementLimit. +// Check the length with: +// +// len(mockedInterface.DeviceSetPowerManagementLimitCalls()) +func (mock *Interface) DeviceSetPowerManagementLimitCalls() []struct { + Device nvml.Device + V uint32 +} { + var calls []struct { + Device nvml.Device + V uint32 + } + mock.lockDeviceSetPowerManagementLimit.RLock() + calls = mock.calls.DeviceSetPowerManagementLimit + mock.lockDeviceSetPowerManagementLimit.RUnlock() + return calls +} + +// DeviceSetPowerManagementLimit_v2 calls DeviceSetPowerManagementLimit_v2Func. +func (mock *Interface) DeviceSetPowerManagementLimit_v2(device nvml.Device, powerValue_v2 *nvml.PowerValue_v2) nvml.Return { + if mock.DeviceSetPowerManagementLimit_v2Func == nil { + panic("Interface.DeviceSetPowerManagementLimit_v2Func: method is nil but Interface.DeviceSetPowerManagementLimit_v2 was just called") + } + callInfo := struct { + Device nvml.Device + PowerValue_v2 *nvml.PowerValue_v2 + }{ + Device: device, + PowerValue_v2: powerValue_v2, + } + mock.lockDeviceSetPowerManagementLimit_v2.Lock() + mock.calls.DeviceSetPowerManagementLimit_v2 = append(mock.calls.DeviceSetPowerManagementLimit_v2, callInfo) + mock.lockDeviceSetPowerManagementLimit_v2.Unlock() + return mock.DeviceSetPowerManagementLimit_v2Func(device, powerValue_v2) +} + +// DeviceSetPowerManagementLimit_v2Calls gets all the calls that were made to DeviceSetPowerManagementLimit_v2. +// Check the length with: +// +// len(mockedInterface.DeviceSetPowerManagementLimit_v2Calls()) +func (mock *Interface) DeviceSetPowerManagementLimit_v2Calls() []struct { + Device nvml.Device + PowerValue_v2 *nvml.PowerValue_v2 +} { + var calls []struct { + Device nvml.Device + PowerValue_v2 *nvml.PowerValue_v2 + } + mock.lockDeviceSetPowerManagementLimit_v2.RLock() + calls = mock.calls.DeviceSetPowerManagementLimit_v2 + mock.lockDeviceSetPowerManagementLimit_v2.RUnlock() + return calls +} + +// DeviceSetTemperatureThreshold calls DeviceSetTemperatureThresholdFunc. +func (mock *Interface) DeviceSetTemperatureThreshold(device nvml.Device, temperatureThresholds nvml.TemperatureThresholds, n int) nvml.Return { + if mock.DeviceSetTemperatureThresholdFunc == nil { + panic("Interface.DeviceSetTemperatureThresholdFunc: method is nil but Interface.DeviceSetTemperatureThreshold was just called") + } + callInfo := struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds + N int + }{ + Device: device, + TemperatureThresholds: temperatureThresholds, + N: n, + } + mock.lockDeviceSetTemperatureThreshold.Lock() + mock.calls.DeviceSetTemperatureThreshold = append(mock.calls.DeviceSetTemperatureThreshold, callInfo) + mock.lockDeviceSetTemperatureThreshold.Unlock() + return mock.DeviceSetTemperatureThresholdFunc(device, temperatureThresholds, n) +} + +// DeviceSetTemperatureThresholdCalls gets all the calls that were made to DeviceSetTemperatureThreshold. +// Check the length with: +// +// len(mockedInterface.DeviceSetTemperatureThresholdCalls()) +func (mock *Interface) DeviceSetTemperatureThresholdCalls() []struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds + N int +} { + var calls []struct { + Device nvml.Device + TemperatureThresholds nvml.TemperatureThresholds + N int + } + mock.lockDeviceSetTemperatureThreshold.RLock() + calls = mock.calls.DeviceSetTemperatureThreshold + mock.lockDeviceSetTemperatureThreshold.RUnlock() + return calls +} + +// DeviceSetVgpuCapabilities calls DeviceSetVgpuCapabilitiesFunc. +func (mock *Interface) DeviceSetVgpuCapabilities(device nvml.Device, deviceVgpuCapability nvml.DeviceVgpuCapability, enableState nvml.EnableState) nvml.Return { + if mock.DeviceSetVgpuCapabilitiesFunc == nil { + panic("Interface.DeviceSetVgpuCapabilitiesFunc: method is nil but Interface.DeviceSetVgpuCapabilities was just called") + } + callInfo := struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState + }{ + Device: device, + DeviceVgpuCapability: deviceVgpuCapability, + EnableState: enableState, + } + mock.lockDeviceSetVgpuCapabilities.Lock() + mock.calls.DeviceSetVgpuCapabilities = append(mock.calls.DeviceSetVgpuCapabilities, callInfo) + mock.lockDeviceSetVgpuCapabilities.Unlock() + return mock.DeviceSetVgpuCapabilitiesFunc(device, deviceVgpuCapability, enableState) +} + +// DeviceSetVgpuCapabilitiesCalls gets all the calls that were made to DeviceSetVgpuCapabilities. +// Check the length with: +// +// len(mockedInterface.DeviceSetVgpuCapabilitiesCalls()) +func (mock *Interface) DeviceSetVgpuCapabilitiesCalls() []struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState +} { + var calls []struct { + Device nvml.Device + DeviceVgpuCapability nvml.DeviceVgpuCapability + EnableState nvml.EnableState + } + mock.lockDeviceSetVgpuCapabilities.RLock() + calls = mock.calls.DeviceSetVgpuCapabilities + mock.lockDeviceSetVgpuCapabilities.RUnlock() + return calls +} + +// DeviceSetVgpuHeterogeneousMode calls DeviceSetVgpuHeterogeneousModeFunc. +func (mock *Interface) DeviceSetVgpuHeterogeneousMode(device nvml.Device, vgpuHeterogeneousMode nvml.VgpuHeterogeneousMode) nvml.Return { + if mock.DeviceSetVgpuHeterogeneousModeFunc == nil { + panic("Interface.DeviceSetVgpuHeterogeneousModeFunc: method is nil but Interface.DeviceSetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + Device nvml.Device + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + }{ + Device: device, + VgpuHeterogeneousMode: vgpuHeterogeneousMode, + } + mock.lockDeviceSetVgpuHeterogeneousMode.Lock() + mock.calls.DeviceSetVgpuHeterogeneousMode = append(mock.calls.DeviceSetVgpuHeterogeneousMode, callInfo) + mock.lockDeviceSetVgpuHeterogeneousMode.Unlock() + return mock.DeviceSetVgpuHeterogeneousModeFunc(device, vgpuHeterogeneousMode) +} + +// DeviceSetVgpuHeterogeneousModeCalls gets all the calls that were made to DeviceSetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetVgpuHeterogeneousModeCalls()) +func (mock *Interface) DeviceSetVgpuHeterogeneousModeCalls() []struct { + Device nvml.Device + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode +} { + var calls []struct { + Device nvml.Device + VgpuHeterogeneousMode nvml.VgpuHeterogeneousMode + } + mock.lockDeviceSetVgpuHeterogeneousMode.RLock() + calls = mock.calls.DeviceSetVgpuHeterogeneousMode + mock.lockDeviceSetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// DeviceSetVgpuSchedulerState calls DeviceSetVgpuSchedulerStateFunc. +func (mock *Interface) DeviceSetVgpuSchedulerState(device nvml.Device, vgpuSchedulerSetState *nvml.VgpuSchedulerSetState) nvml.Return { + if mock.DeviceSetVgpuSchedulerStateFunc == nil { + panic("Interface.DeviceSetVgpuSchedulerStateFunc: method is nil but Interface.DeviceSetVgpuSchedulerState was just called") + } + callInfo := struct { + Device nvml.Device + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + }{ + Device: device, + VgpuSchedulerSetState: vgpuSchedulerSetState, + } + mock.lockDeviceSetVgpuSchedulerState.Lock() + mock.calls.DeviceSetVgpuSchedulerState = append(mock.calls.DeviceSetVgpuSchedulerState, callInfo) + mock.lockDeviceSetVgpuSchedulerState.Unlock() + return mock.DeviceSetVgpuSchedulerStateFunc(device, vgpuSchedulerSetState) +} + +// DeviceSetVgpuSchedulerStateCalls gets all the calls that were made to DeviceSetVgpuSchedulerState. +// Check the length with: +// +// len(mockedInterface.DeviceSetVgpuSchedulerStateCalls()) +func (mock *Interface) DeviceSetVgpuSchedulerStateCalls() []struct { + Device nvml.Device + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState +} { + var calls []struct { + Device nvml.Device + VgpuSchedulerSetState *nvml.VgpuSchedulerSetState + } + mock.lockDeviceSetVgpuSchedulerState.RLock() + calls = mock.calls.DeviceSetVgpuSchedulerState + mock.lockDeviceSetVgpuSchedulerState.RUnlock() + return calls +} + +// DeviceSetVirtualizationMode calls DeviceSetVirtualizationModeFunc. +func (mock *Interface) DeviceSetVirtualizationMode(device nvml.Device, gpuVirtualizationMode nvml.GpuVirtualizationMode) nvml.Return { + if mock.DeviceSetVirtualizationModeFunc == nil { + panic("Interface.DeviceSetVirtualizationModeFunc: method is nil but Interface.DeviceSetVirtualizationMode was just called") + } + callInfo := struct { + Device nvml.Device + GpuVirtualizationMode nvml.GpuVirtualizationMode + }{ + Device: device, + GpuVirtualizationMode: gpuVirtualizationMode, + } + mock.lockDeviceSetVirtualizationMode.Lock() + mock.calls.DeviceSetVirtualizationMode = append(mock.calls.DeviceSetVirtualizationMode, callInfo) + mock.lockDeviceSetVirtualizationMode.Unlock() + return mock.DeviceSetVirtualizationModeFunc(device, gpuVirtualizationMode) +} + +// DeviceSetVirtualizationModeCalls gets all the calls that were made to DeviceSetVirtualizationMode. +// Check the length with: +// +// len(mockedInterface.DeviceSetVirtualizationModeCalls()) +func (mock *Interface) DeviceSetVirtualizationModeCalls() []struct { + Device nvml.Device + GpuVirtualizationMode nvml.GpuVirtualizationMode +} { + var calls []struct { + Device nvml.Device + GpuVirtualizationMode nvml.GpuVirtualizationMode + } + mock.lockDeviceSetVirtualizationMode.RLock() + calls = mock.calls.DeviceSetVirtualizationMode + mock.lockDeviceSetVirtualizationMode.RUnlock() + return calls +} + +// DeviceValidateInforom calls DeviceValidateInforomFunc. +func (mock *Interface) DeviceValidateInforom(device nvml.Device) nvml.Return { + if mock.DeviceValidateInforomFunc == nil { + panic("Interface.DeviceValidateInforomFunc: method is nil but Interface.DeviceValidateInforom was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceValidateInforom.Lock() + mock.calls.DeviceValidateInforom = append(mock.calls.DeviceValidateInforom, callInfo) + mock.lockDeviceValidateInforom.Unlock() + return mock.DeviceValidateInforomFunc(device) +} + +// DeviceValidateInforomCalls gets all the calls that were made to DeviceValidateInforom. +// Check the length with: +// +// len(mockedInterface.DeviceValidateInforomCalls()) +func (mock *Interface) DeviceValidateInforomCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceValidateInforom.RLock() + calls = mock.calls.DeviceValidateInforom + mock.lockDeviceValidateInforom.RUnlock() + return calls +} + +// DeviceWorkloadPowerProfileClearRequestedProfiles calls DeviceWorkloadPowerProfileClearRequestedProfilesFunc. +func (mock *Interface) DeviceWorkloadPowerProfileClearRequestedProfiles(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { + if mock.DeviceWorkloadPowerProfileClearRequestedProfilesFunc == nil { + panic("Interface.DeviceWorkloadPowerProfileClearRequestedProfilesFunc: method is nil but Interface.DeviceWorkloadPowerProfileClearRequestedProfiles was just called") + } + callInfo := struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + }{ + Device: device, + WorkloadPowerProfileRequestedProfiles: workloadPowerProfileRequestedProfiles, + } + mock.lockDeviceWorkloadPowerProfileClearRequestedProfiles.Lock() + mock.calls.DeviceWorkloadPowerProfileClearRequestedProfiles = append(mock.calls.DeviceWorkloadPowerProfileClearRequestedProfiles, callInfo) + mock.lockDeviceWorkloadPowerProfileClearRequestedProfiles.Unlock() + return mock.DeviceWorkloadPowerProfileClearRequestedProfilesFunc(device, workloadPowerProfileRequestedProfiles) +} + +// DeviceWorkloadPowerProfileClearRequestedProfilesCalls gets all the calls that were made to DeviceWorkloadPowerProfileClearRequestedProfiles. +// Check the length with: +// +// len(mockedInterface.DeviceWorkloadPowerProfileClearRequestedProfilesCalls()) +func (mock *Interface) DeviceWorkloadPowerProfileClearRequestedProfilesCalls() []struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles +} { + var calls []struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + mock.lockDeviceWorkloadPowerProfileClearRequestedProfiles.RLock() + calls = mock.calls.DeviceWorkloadPowerProfileClearRequestedProfiles + mock.lockDeviceWorkloadPowerProfileClearRequestedProfiles.RUnlock() + return calls +} + +// DeviceWorkloadPowerProfileGetCurrentProfiles calls DeviceWorkloadPowerProfileGetCurrentProfilesFunc. +func (mock *Interface) DeviceWorkloadPowerProfileGetCurrentProfiles(device nvml.Device) (nvml.WorkloadPowerProfileCurrentProfiles, nvml.Return) { + if mock.DeviceWorkloadPowerProfileGetCurrentProfilesFunc == nil { + panic("Interface.DeviceWorkloadPowerProfileGetCurrentProfilesFunc: method is nil but Interface.DeviceWorkloadPowerProfileGetCurrentProfiles was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceWorkloadPowerProfileGetCurrentProfiles.Lock() + mock.calls.DeviceWorkloadPowerProfileGetCurrentProfiles = append(mock.calls.DeviceWorkloadPowerProfileGetCurrentProfiles, callInfo) + mock.lockDeviceWorkloadPowerProfileGetCurrentProfiles.Unlock() + return mock.DeviceWorkloadPowerProfileGetCurrentProfilesFunc(device) +} + +// DeviceWorkloadPowerProfileGetCurrentProfilesCalls gets all the calls that were made to DeviceWorkloadPowerProfileGetCurrentProfiles. +// Check the length with: +// +// len(mockedInterface.DeviceWorkloadPowerProfileGetCurrentProfilesCalls()) +func (mock *Interface) DeviceWorkloadPowerProfileGetCurrentProfilesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceWorkloadPowerProfileGetCurrentProfiles.RLock() + calls = mock.calls.DeviceWorkloadPowerProfileGetCurrentProfiles + mock.lockDeviceWorkloadPowerProfileGetCurrentProfiles.RUnlock() + return calls +} + +// DeviceWorkloadPowerProfileGetProfilesInfo calls DeviceWorkloadPowerProfileGetProfilesInfoFunc. +func (mock *Interface) DeviceWorkloadPowerProfileGetProfilesInfo(device nvml.Device) (nvml.WorkloadPowerProfileProfilesInfo, nvml.Return) { + if mock.DeviceWorkloadPowerProfileGetProfilesInfoFunc == nil { + panic("Interface.DeviceWorkloadPowerProfileGetProfilesInfoFunc: method is nil but Interface.DeviceWorkloadPowerProfileGetProfilesInfo was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockDeviceWorkloadPowerProfileGetProfilesInfo.Lock() + mock.calls.DeviceWorkloadPowerProfileGetProfilesInfo = append(mock.calls.DeviceWorkloadPowerProfileGetProfilesInfo, callInfo) + mock.lockDeviceWorkloadPowerProfileGetProfilesInfo.Unlock() + return mock.DeviceWorkloadPowerProfileGetProfilesInfoFunc(device) +} + +// DeviceWorkloadPowerProfileGetProfilesInfoCalls gets all the calls that were made to DeviceWorkloadPowerProfileGetProfilesInfo. +// Check the length with: +// +// len(mockedInterface.DeviceWorkloadPowerProfileGetProfilesInfoCalls()) +func (mock *Interface) DeviceWorkloadPowerProfileGetProfilesInfoCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockDeviceWorkloadPowerProfileGetProfilesInfo.RLock() + calls = mock.calls.DeviceWorkloadPowerProfileGetProfilesInfo + mock.lockDeviceWorkloadPowerProfileGetProfilesInfo.RUnlock() + return calls +} + +// DeviceWorkloadPowerProfileSetRequestedProfiles calls DeviceWorkloadPowerProfileSetRequestedProfilesFunc. +func (mock *Interface) DeviceWorkloadPowerProfileSetRequestedProfiles(device nvml.Device, workloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles) nvml.Return { + if mock.DeviceWorkloadPowerProfileSetRequestedProfilesFunc == nil { + panic("Interface.DeviceWorkloadPowerProfileSetRequestedProfilesFunc: method is nil but Interface.DeviceWorkloadPowerProfileSetRequestedProfiles was just called") + } + callInfo := struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + }{ + Device: device, + WorkloadPowerProfileRequestedProfiles: workloadPowerProfileRequestedProfiles, + } + mock.lockDeviceWorkloadPowerProfileSetRequestedProfiles.Lock() + mock.calls.DeviceWorkloadPowerProfileSetRequestedProfiles = append(mock.calls.DeviceWorkloadPowerProfileSetRequestedProfiles, callInfo) + mock.lockDeviceWorkloadPowerProfileSetRequestedProfiles.Unlock() + return mock.DeviceWorkloadPowerProfileSetRequestedProfilesFunc(device, workloadPowerProfileRequestedProfiles) +} + +// DeviceWorkloadPowerProfileSetRequestedProfilesCalls gets all the calls that were made to DeviceWorkloadPowerProfileSetRequestedProfiles. +// Check the length with: +// +// len(mockedInterface.DeviceWorkloadPowerProfileSetRequestedProfilesCalls()) +func (mock *Interface) DeviceWorkloadPowerProfileSetRequestedProfilesCalls() []struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles +} { + var calls []struct { + Device nvml.Device + WorkloadPowerProfileRequestedProfiles *nvml.WorkloadPowerProfileRequestedProfiles + } + mock.lockDeviceWorkloadPowerProfileSetRequestedProfiles.RLock() + calls = mock.calls.DeviceWorkloadPowerProfileSetRequestedProfiles + mock.lockDeviceWorkloadPowerProfileSetRequestedProfiles.RUnlock() + return calls +} + +// ErrorString calls ErrorStringFunc. +func (mock *Interface) ErrorString(returnMoqParam nvml.Return) string { + if mock.ErrorStringFunc == nil { + panic("Interface.ErrorStringFunc: method is nil but Interface.ErrorString was just called") + } + callInfo := struct { + ReturnMoqParam nvml.Return + }{ + ReturnMoqParam: returnMoqParam, + } + mock.lockErrorString.Lock() + mock.calls.ErrorString = append(mock.calls.ErrorString, callInfo) + mock.lockErrorString.Unlock() + return mock.ErrorStringFunc(returnMoqParam) +} + +// ErrorStringCalls gets all the calls that were made to ErrorString. +// Check the length with: +// +// len(mockedInterface.ErrorStringCalls()) +func (mock *Interface) ErrorStringCalls() []struct { + ReturnMoqParam nvml.Return +} { + var calls []struct { + ReturnMoqParam nvml.Return + } + mock.lockErrorString.RLock() + calls = mock.calls.ErrorString + mock.lockErrorString.RUnlock() + return calls +} + +// EventSetCreate calls EventSetCreateFunc. +func (mock *Interface) EventSetCreate() (nvml.EventSet, nvml.Return) { + if mock.EventSetCreateFunc == nil { + panic("Interface.EventSetCreateFunc: method is nil but Interface.EventSetCreate was just called") + } + callInfo := struct { + }{} + mock.lockEventSetCreate.Lock() + mock.calls.EventSetCreate = append(mock.calls.EventSetCreate, callInfo) + mock.lockEventSetCreate.Unlock() + return mock.EventSetCreateFunc() +} + +// EventSetCreateCalls gets all the calls that were made to EventSetCreate. +// Check the length with: +// +// len(mockedInterface.EventSetCreateCalls()) +func (mock *Interface) EventSetCreateCalls() []struct { +} { + var calls []struct { + } + mock.lockEventSetCreate.RLock() + calls = mock.calls.EventSetCreate + mock.lockEventSetCreate.RUnlock() + return calls +} + +// EventSetFree calls EventSetFreeFunc. +func (mock *Interface) EventSetFree(eventSet nvml.EventSet) nvml.Return { + if mock.EventSetFreeFunc == nil { + panic("Interface.EventSetFreeFunc: method is nil but Interface.EventSetFree was just called") + } + callInfo := struct { + EventSet nvml.EventSet + }{ + EventSet: eventSet, + } + mock.lockEventSetFree.Lock() + mock.calls.EventSetFree = append(mock.calls.EventSetFree, callInfo) + mock.lockEventSetFree.Unlock() + return mock.EventSetFreeFunc(eventSet) +} + +// EventSetFreeCalls gets all the calls that were made to EventSetFree. +// Check the length with: +// +// len(mockedInterface.EventSetFreeCalls()) +func (mock *Interface) EventSetFreeCalls() []struct { + EventSet nvml.EventSet +} { + var calls []struct { + EventSet nvml.EventSet + } + mock.lockEventSetFree.RLock() + calls = mock.calls.EventSetFree + mock.lockEventSetFree.RUnlock() + return calls +} + +// EventSetWait calls EventSetWaitFunc. +func (mock *Interface) EventSetWait(eventSet nvml.EventSet, v uint32) (nvml.EventData, nvml.Return) { + if mock.EventSetWaitFunc == nil { + panic("Interface.EventSetWaitFunc: method is nil but Interface.EventSetWait was just called") + } + callInfo := struct { + EventSet nvml.EventSet + V uint32 + }{ + EventSet: eventSet, + V: v, + } + mock.lockEventSetWait.Lock() + mock.calls.EventSetWait = append(mock.calls.EventSetWait, callInfo) + mock.lockEventSetWait.Unlock() + return mock.EventSetWaitFunc(eventSet, v) +} + +// EventSetWaitCalls gets all the calls that were made to EventSetWait. +// Check the length with: +// +// len(mockedInterface.EventSetWaitCalls()) +func (mock *Interface) EventSetWaitCalls() []struct { + EventSet nvml.EventSet + V uint32 +} { + var calls []struct { + EventSet nvml.EventSet + V uint32 + } + mock.lockEventSetWait.RLock() + calls = mock.calls.EventSetWait + mock.lockEventSetWait.RUnlock() + return calls +} + +// Extensions calls ExtensionsFunc. +func (mock *Interface) Extensions() nvml.ExtendedInterface { + if mock.ExtensionsFunc == nil { + panic("Interface.ExtensionsFunc: method is nil but Interface.Extensions was just called") + } + callInfo := struct { + }{} + mock.lockExtensions.Lock() + mock.calls.Extensions = append(mock.calls.Extensions, callInfo) + mock.lockExtensions.Unlock() + return mock.ExtensionsFunc() +} + +// ExtensionsCalls gets all the calls that were made to Extensions. +// Check the length with: +// +// len(mockedInterface.ExtensionsCalls()) +func (mock *Interface) ExtensionsCalls() []struct { +} { + var calls []struct { + } + mock.lockExtensions.RLock() + calls = mock.calls.Extensions + mock.lockExtensions.RUnlock() + return calls +} + +// GetExcludedDeviceCount calls GetExcludedDeviceCountFunc. +func (mock *Interface) GetExcludedDeviceCount() (int, nvml.Return) { + if mock.GetExcludedDeviceCountFunc == nil { + panic("Interface.GetExcludedDeviceCountFunc: method is nil but Interface.GetExcludedDeviceCount was just called") + } + callInfo := struct { + }{} + mock.lockGetExcludedDeviceCount.Lock() + mock.calls.GetExcludedDeviceCount = append(mock.calls.GetExcludedDeviceCount, callInfo) + mock.lockGetExcludedDeviceCount.Unlock() + return mock.GetExcludedDeviceCountFunc() +} + +// GetExcludedDeviceCountCalls gets all the calls that were made to GetExcludedDeviceCount. +// Check the length with: +// +// len(mockedInterface.GetExcludedDeviceCountCalls()) +func (mock *Interface) GetExcludedDeviceCountCalls() []struct { +} { + var calls []struct { + } + mock.lockGetExcludedDeviceCount.RLock() + calls = mock.calls.GetExcludedDeviceCount + mock.lockGetExcludedDeviceCount.RUnlock() + return calls +} + +// GetExcludedDeviceInfoByIndex calls GetExcludedDeviceInfoByIndexFunc. +func (mock *Interface) GetExcludedDeviceInfoByIndex(n int) (nvml.ExcludedDeviceInfo, nvml.Return) { + if mock.GetExcludedDeviceInfoByIndexFunc == nil { + panic("Interface.GetExcludedDeviceInfoByIndexFunc: method is nil but Interface.GetExcludedDeviceInfoByIndex was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetExcludedDeviceInfoByIndex.Lock() + mock.calls.GetExcludedDeviceInfoByIndex = append(mock.calls.GetExcludedDeviceInfoByIndex, callInfo) + mock.lockGetExcludedDeviceInfoByIndex.Unlock() + return mock.GetExcludedDeviceInfoByIndexFunc(n) +} + +// GetExcludedDeviceInfoByIndexCalls gets all the calls that were made to GetExcludedDeviceInfoByIndex. +// Check the length with: +// +// len(mockedInterface.GetExcludedDeviceInfoByIndexCalls()) +func (mock *Interface) GetExcludedDeviceInfoByIndexCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetExcludedDeviceInfoByIndex.RLock() + calls = mock.calls.GetExcludedDeviceInfoByIndex + mock.lockGetExcludedDeviceInfoByIndex.RUnlock() + return calls +} + +// GetVgpuCompatibility calls GetVgpuCompatibilityFunc. +func (mock *Interface) GetVgpuCompatibility(vgpuMetadata *nvml.VgpuMetadata, vgpuPgpuMetadata *nvml.VgpuPgpuMetadata) (nvml.VgpuPgpuCompatibility, nvml.Return) { + if mock.GetVgpuCompatibilityFunc == nil { + panic("Interface.GetVgpuCompatibilityFunc: method is nil but Interface.GetVgpuCompatibility was just called") + } + callInfo := struct { + VgpuMetadata *nvml.VgpuMetadata + VgpuPgpuMetadata *nvml.VgpuPgpuMetadata + }{ + VgpuMetadata: vgpuMetadata, + VgpuPgpuMetadata: vgpuPgpuMetadata, + } + mock.lockGetVgpuCompatibility.Lock() + mock.calls.GetVgpuCompatibility = append(mock.calls.GetVgpuCompatibility, callInfo) + mock.lockGetVgpuCompatibility.Unlock() + return mock.GetVgpuCompatibilityFunc(vgpuMetadata, vgpuPgpuMetadata) +} + +// GetVgpuCompatibilityCalls gets all the calls that were made to GetVgpuCompatibility. +// Check the length with: +// +// len(mockedInterface.GetVgpuCompatibilityCalls()) +func (mock *Interface) GetVgpuCompatibilityCalls() []struct { + VgpuMetadata *nvml.VgpuMetadata + VgpuPgpuMetadata *nvml.VgpuPgpuMetadata +} { + var calls []struct { + VgpuMetadata *nvml.VgpuMetadata + VgpuPgpuMetadata *nvml.VgpuPgpuMetadata + } + mock.lockGetVgpuCompatibility.RLock() + calls = mock.calls.GetVgpuCompatibility + mock.lockGetVgpuCompatibility.RUnlock() + return calls +} + +// GetVgpuDriverCapabilities calls GetVgpuDriverCapabilitiesFunc. +func (mock *Interface) GetVgpuDriverCapabilities(vgpuDriverCapability nvml.VgpuDriverCapability) (bool, nvml.Return) { + if mock.GetVgpuDriverCapabilitiesFunc == nil { + panic("Interface.GetVgpuDriverCapabilitiesFunc: method is nil but Interface.GetVgpuDriverCapabilities was just called") + } + callInfo := struct { + VgpuDriverCapability nvml.VgpuDriverCapability + }{ + VgpuDriverCapability: vgpuDriverCapability, + } + mock.lockGetVgpuDriverCapabilities.Lock() + mock.calls.GetVgpuDriverCapabilities = append(mock.calls.GetVgpuDriverCapabilities, callInfo) + mock.lockGetVgpuDriverCapabilities.Unlock() + return mock.GetVgpuDriverCapabilitiesFunc(vgpuDriverCapability) +} + +// GetVgpuDriverCapabilitiesCalls gets all the calls that were made to GetVgpuDriverCapabilities. +// Check the length with: +// +// len(mockedInterface.GetVgpuDriverCapabilitiesCalls()) +func (mock *Interface) GetVgpuDriverCapabilitiesCalls() []struct { + VgpuDriverCapability nvml.VgpuDriverCapability +} { + var calls []struct { + VgpuDriverCapability nvml.VgpuDriverCapability + } + mock.lockGetVgpuDriverCapabilities.RLock() + calls = mock.calls.GetVgpuDriverCapabilities + mock.lockGetVgpuDriverCapabilities.RUnlock() + return calls +} + +// GetVgpuVersion calls GetVgpuVersionFunc. +func (mock *Interface) GetVgpuVersion() (nvml.VgpuVersion, nvml.VgpuVersion, nvml.Return) { + if mock.GetVgpuVersionFunc == nil { + panic("Interface.GetVgpuVersionFunc: method is nil but Interface.GetVgpuVersion was just called") + } + callInfo := struct { + }{} + mock.lockGetVgpuVersion.Lock() + mock.calls.GetVgpuVersion = append(mock.calls.GetVgpuVersion, callInfo) + mock.lockGetVgpuVersion.Unlock() + return mock.GetVgpuVersionFunc() +} + +// GetVgpuVersionCalls gets all the calls that were made to GetVgpuVersion. +// Check the length with: +// +// len(mockedInterface.GetVgpuVersionCalls()) +func (mock *Interface) GetVgpuVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVgpuVersion.RLock() + calls = mock.calls.GetVgpuVersion + mock.lockGetVgpuVersion.RUnlock() + return calls +} + +// GpmMetricsGet calls GpmMetricsGetFunc. +func (mock *Interface) GpmMetricsGet(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.Return { + if mock.GpmMetricsGetFunc == nil { + panic("Interface.GpmMetricsGetFunc: method is nil but Interface.GpmMetricsGet was just called") + } + callInfo := struct { + GpmMetricsGetType *nvml.GpmMetricsGetType + }{ + GpmMetricsGetType: gpmMetricsGetType, + } + mock.lockGpmMetricsGet.Lock() + mock.calls.GpmMetricsGet = append(mock.calls.GpmMetricsGet, callInfo) + mock.lockGpmMetricsGet.Unlock() + return mock.GpmMetricsGetFunc(gpmMetricsGetType) +} + +// GpmMetricsGetCalls gets all the calls that were made to GpmMetricsGet. +// Check the length with: +// +// len(mockedInterface.GpmMetricsGetCalls()) +func (mock *Interface) GpmMetricsGetCalls() []struct { + GpmMetricsGetType *nvml.GpmMetricsGetType +} { + var calls []struct { + GpmMetricsGetType *nvml.GpmMetricsGetType + } + mock.lockGpmMetricsGet.RLock() + calls = mock.calls.GpmMetricsGet + mock.lockGpmMetricsGet.RUnlock() + return calls +} + +// GpmMetricsGetV calls GpmMetricsGetVFunc. +func (mock *Interface) GpmMetricsGetV(gpmMetricsGetType *nvml.GpmMetricsGetType) nvml.GpmMetricsGetVType { + if mock.GpmMetricsGetVFunc == nil { + panic("Interface.GpmMetricsGetVFunc: method is nil but Interface.GpmMetricsGetV was just called") + } + callInfo := struct { + GpmMetricsGetType *nvml.GpmMetricsGetType + }{ + GpmMetricsGetType: gpmMetricsGetType, + } + mock.lockGpmMetricsGetV.Lock() + mock.calls.GpmMetricsGetV = append(mock.calls.GpmMetricsGetV, callInfo) + mock.lockGpmMetricsGetV.Unlock() + return mock.GpmMetricsGetVFunc(gpmMetricsGetType) +} + +// GpmMetricsGetVCalls gets all the calls that were made to GpmMetricsGetV. +// Check the length with: +// +// len(mockedInterface.GpmMetricsGetVCalls()) +func (mock *Interface) GpmMetricsGetVCalls() []struct { + GpmMetricsGetType *nvml.GpmMetricsGetType +} { + var calls []struct { + GpmMetricsGetType *nvml.GpmMetricsGetType + } + mock.lockGpmMetricsGetV.RLock() + calls = mock.calls.GpmMetricsGetV + mock.lockGpmMetricsGetV.RUnlock() + return calls +} + +// GpmMigSampleGet calls GpmMigSampleGetFunc. +func (mock *Interface) GpmMigSampleGet(device nvml.Device, n int, gpmSample nvml.GpmSample) nvml.Return { + if mock.GpmMigSampleGetFunc == nil { + panic("Interface.GpmMigSampleGetFunc: method is nil but Interface.GpmMigSampleGet was just called") + } + callInfo := struct { + Device nvml.Device + N int + GpmSample nvml.GpmSample + }{ + Device: device, + N: n, + GpmSample: gpmSample, + } + mock.lockGpmMigSampleGet.Lock() + mock.calls.GpmMigSampleGet = append(mock.calls.GpmMigSampleGet, callInfo) + mock.lockGpmMigSampleGet.Unlock() + return mock.GpmMigSampleGetFunc(device, n, gpmSample) +} + +// GpmMigSampleGetCalls gets all the calls that were made to GpmMigSampleGet. +// Check the length with: +// +// len(mockedInterface.GpmMigSampleGetCalls()) +func (mock *Interface) GpmMigSampleGetCalls() []struct { + Device nvml.Device + N int + GpmSample nvml.GpmSample +} { + var calls []struct { + Device nvml.Device + N int + GpmSample nvml.GpmSample + } + mock.lockGpmMigSampleGet.RLock() + calls = mock.calls.GpmMigSampleGet + mock.lockGpmMigSampleGet.RUnlock() + return calls +} + +// GpmQueryDeviceSupport calls GpmQueryDeviceSupportFunc. +func (mock *Interface) GpmQueryDeviceSupport(device nvml.Device) (nvml.GpmSupport, nvml.Return) { + if mock.GpmQueryDeviceSupportFunc == nil { + panic("Interface.GpmQueryDeviceSupportFunc: method is nil but Interface.GpmQueryDeviceSupport was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGpmQueryDeviceSupport.Lock() + mock.calls.GpmQueryDeviceSupport = append(mock.calls.GpmQueryDeviceSupport, callInfo) + mock.lockGpmQueryDeviceSupport.Unlock() + return mock.GpmQueryDeviceSupportFunc(device) +} + +// GpmQueryDeviceSupportCalls gets all the calls that were made to GpmQueryDeviceSupport. +// Check the length with: +// +// len(mockedInterface.GpmQueryDeviceSupportCalls()) +func (mock *Interface) GpmQueryDeviceSupportCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGpmQueryDeviceSupport.RLock() + calls = mock.calls.GpmQueryDeviceSupport + mock.lockGpmQueryDeviceSupport.RUnlock() + return calls +} + +// GpmQueryDeviceSupportV calls GpmQueryDeviceSupportVFunc. +func (mock *Interface) GpmQueryDeviceSupportV(device nvml.Device) nvml.GpmSupportV { + if mock.GpmQueryDeviceSupportVFunc == nil { + panic("Interface.GpmQueryDeviceSupportVFunc: method is nil but Interface.GpmQueryDeviceSupportV was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGpmQueryDeviceSupportV.Lock() + mock.calls.GpmQueryDeviceSupportV = append(mock.calls.GpmQueryDeviceSupportV, callInfo) + mock.lockGpmQueryDeviceSupportV.Unlock() + return mock.GpmQueryDeviceSupportVFunc(device) +} + +// GpmQueryDeviceSupportVCalls gets all the calls that were made to GpmQueryDeviceSupportV. +// Check the length with: +// +// len(mockedInterface.GpmQueryDeviceSupportVCalls()) +func (mock *Interface) GpmQueryDeviceSupportVCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGpmQueryDeviceSupportV.RLock() + calls = mock.calls.GpmQueryDeviceSupportV + mock.lockGpmQueryDeviceSupportV.RUnlock() + return calls +} + +// GpmQueryIfStreamingEnabled calls GpmQueryIfStreamingEnabledFunc. +func (mock *Interface) GpmQueryIfStreamingEnabled(device nvml.Device) (uint32, nvml.Return) { + if mock.GpmQueryIfStreamingEnabledFunc == nil { + panic("Interface.GpmQueryIfStreamingEnabledFunc: method is nil but Interface.GpmQueryIfStreamingEnabled was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGpmQueryIfStreamingEnabled.Lock() + mock.calls.GpmQueryIfStreamingEnabled = append(mock.calls.GpmQueryIfStreamingEnabled, callInfo) + mock.lockGpmQueryIfStreamingEnabled.Unlock() + return mock.GpmQueryIfStreamingEnabledFunc(device) +} + +// GpmQueryIfStreamingEnabledCalls gets all the calls that were made to GpmQueryIfStreamingEnabled. +// Check the length with: +// +// len(mockedInterface.GpmQueryIfStreamingEnabledCalls()) +func (mock *Interface) GpmQueryIfStreamingEnabledCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGpmQueryIfStreamingEnabled.RLock() + calls = mock.calls.GpmQueryIfStreamingEnabled + mock.lockGpmQueryIfStreamingEnabled.RUnlock() + return calls +} + +// GpmSampleAlloc calls GpmSampleAllocFunc. +func (mock *Interface) GpmSampleAlloc() (nvml.GpmSample, nvml.Return) { + if mock.GpmSampleAllocFunc == nil { + panic("Interface.GpmSampleAllocFunc: method is nil but Interface.GpmSampleAlloc was just called") + } + callInfo := struct { + }{} + mock.lockGpmSampleAlloc.Lock() + mock.calls.GpmSampleAlloc = append(mock.calls.GpmSampleAlloc, callInfo) + mock.lockGpmSampleAlloc.Unlock() + return mock.GpmSampleAllocFunc() +} + +// GpmSampleAllocCalls gets all the calls that were made to GpmSampleAlloc. +// Check the length with: +// +// len(mockedInterface.GpmSampleAllocCalls()) +func (mock *Interface) GpmSampleAllocCalls() []struct { +} { + var calls []struct { + } + mock.lockGpmSampleAlloc.RLock() + calls = mock.calls.GpmSampleAlloc + mock.lockGpmSampleAlloc.RUnlock() + return calls +} + +// GpmSampleFree calls GpmSampleFreeFunc. +func (mock *Interface) GpmSampleFree(gpmSample nvml.GpmSample) nvml.Return { + if mock.GpmSampleFreeFunc == nil { + panic("Interface.GpmSampleFreeFunc: method is nil but Interface.GpmSampleFree was just called") + } + callInfo := struct { + GpmSample nvml.GpmSample + }{ + GpmSample: gpmSample, + } + mock.lockGpmSampleFree.Lock() + mock.calls.GpmSampleFree = append(mock.calls.GpmSampleFree, callInfo) + mock.lockGpmSampleFree.Unlock() + return mock.GpmSampleFreeFunc(gpmSample) +} + +// GpmSampleFreeCalls gets all the calls that were made to GpmSampleFree. +// Check the length with: +// +// len(mockedInterface.GpmSampleFreeCalls()) +func (mock *Interface) GpmSampleFreeCalls() []struct { + GpmSample nvml.GpmSample +} { + var calls []struct { + GpmSample nvml.GpmSample + } + mock.lockGpmSampleFree.RLock() + calls = mock.calls.GpmSampleFree + mock.lockGpmSampleFree.RUnlock() + return calls +} + +// GpmSampleGet calls GpmSampleGetFunc. +func (mock *Interface) GpmSampleGet(device nvml.Device, gpmSample nvml.GpmSample) nvml.Return { + if mock.GpmSampleGetFunc == nil { + panic("Interface.GpmSampleGetFunc: method is nil but Interface.GpmSampleGet was just called") + } + callInfo := struct { + Device nvml.Device + GpmSample nvml.GpmSample + }{ + Device: device, + GpmSample: gpmSample, + } + mock.lockGpmSampleGet.Lock() + mock.calls.GpmSampleGet = append(mock.calls.GpmSampleGet, callInfo) + mock.lockGpmSampleGet.Unlock() + return mock.GpmSampleGetFunc(device, gpmSample) +} + +// GpmSampleGetCalls gets all the calls that were made to GpmSampleGet. +// Check the length with: +// +// len(mockedInterface.GpmSampleGetCalls()) +func (mock *Interface) GpmSampleGetCalls() []struct { + Device nvml.Device + GpmSample nvml.GpmSample +} { + var calls []struct { + Device nvml.Device + GpmSample nvml.GpmSample + } + mock.lockGpmSampleGet.RLock() + calls = mock.calls.GpmSampleGet + mock.lockGpmSampleGet.RUnlock() + return calls +} + +// GpmSetStreamingEnabled calls GpmSetStreamingEnabledFunc. +func (mock *Interface) GpmSetStreamingEnabled(device nvml.Device, v uint32) nvml.Return { + if mock.GpmSetStreamingEnabledFunc == nil { + panic("Interface.GpmSetStreamingEnabledFunc: method is nil but Interface.GpmSetStreamingEnabled was just called") + } + callInfo := struct { + Device nvml.Device + V uint32 + }{ + Device: device, + V: v, + } + mock.lockGpmSetStreamingEnabled.Lock() + mock.calls.GpmSetStreamingEnabled = append(mock.calls.GpmSetStreamingEnabled, callInfo) + mock.lockGpmSetStreamingEnabled.Unlock() + return mock.GpmSetStreamingEnabledFunc(device, v) +} + +// GpmSetStreamingEnabledCalls gets all the calls that were made to GpmSetStreamingEnabled. +// Check the length with: +// +// len(mockedInterface.GpmSetStreamingEnabledCalls()) +func (mock *Interface) GpmSetStreamingEnabledCalls() []struct { + Device nvml.Device + V uint32 +} { + var calls []struct { + Device nvml.Device + V uint32 + } + mock.lockGpmSetStreamingEnabled.RLock() + calls = mock.calls.GpmSetStreamingEnabled + mock.lockGpmSetStreamingEnabled.RUnlock() + return calls +} + +// GpuInstanceCreateComputeInstance calls GpuInstanceCreateComputeInstanceFunc. +func (mock *Interface) GpuInstanceCreateComputeInstance(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (nvml.ComputeInstance, nvml.Return) { + if mock.GpuInstanceCreateComputeInstanceFunc == nil { + panic("Interface.GpuInstanceCreateComputeInstanceFunc: method is nil but Interface.GpuInstanceCreateComputeInstance was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + GpuInstance: gpuInstance, + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGpuInstanceCreateComputeInstance.Lock() + mock.calls.GpuInstanceCreateComputeInstance = append(mock.calls.GpuInstanceCreateComputeInstance, callInfo) + mock.lockGpuInstanceCreateComputeInstance.Unlock() + return mock.GpuInstanceCreateComputeInstanceFunc(gpuInstance, computeInstanceProfileInfo) +} + +// GpuInstanceCreateComputeInstanceCalls gets all the calls that were made to GpuInstanceCreateComputeInstance. +// Check the length with: +// +// len(mockedInterface.GpuInstanceCreateComputeInstanceCalls()) +func (mock *Interface) GpuInstanceCreateComputeInstanceCalls() []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGpuInstanceCreateComputeInstance.RLock() + calls = mock.calls.GpuInstanceCreateComputeInstance + mock.lockGpuInstanceCreateComputeInstance.RUnlock() + return calls +} + +// GpuInstanceCreateComputeInstanceWithPlacement calls GpuInstanceCreateComputeInstanceWithPlacementFunc. +func (mock *Interface) GpuInstanceCreateComputeInstanceWithPlacement(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo, computeInstancePlacement *nvml.ComputeInstancePlacement) (nvml.ComputeInstance, nvml.Return) { + if mock.GpuInstanceCreateComputeInstanceWithPlacementFunc == nil { + panic("Interface.GpuInstanceCreateComputeInstanceWithPlacementFunc: method is nil but Interface.GpuInstanceCreateComputeInstanceWithPlacement was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement + }{ + GpuInstance: gpuInstance, + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + ComputeInstancePlacement: computeInstancePlacement, + } + mock.lockGpuInstanceCreateComputeInstanceWithPlacement.Lock() + mock.calls.GpuInstanceCreateComputeInstanceWithPlacement = append(mock.calls.GpuInstanceCreateComputeInstanceWithPlacement, callInfo) + mock.lockGpuInstanceCreateComputeInstanceWithPlacement.Unlock() + return mock.GpuInstanceCreateComputeInstanceWithPlacementFunc(gpuInstance, computeInstanceProfileInfo, computeInstancePlacement) +} + +// GpuInstanceCreateComputeInstanceWithPlacementCalls gets all the calls that were made to GpuInstanceCreateComputeInstanceWithPlacement. +// Check the length with: +// +// len(mockedInterface.GpuInstanceCreateComputeInstanceWithPlacementCalls()) +func (mock *Interface) GpuInstanceCreateComputeInstanceWithPlacementCalls() []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement +} { + var calls []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + ComputeInstancePlacement *nvml.ComputeInstancePlacement + } + mock.lockGpuInstanceCreateComputeInstanceWithPlacement.RLock() + calls = mock.calls.GpuInstanceCreateComputeInstanceWithPlacement + mock.lockGpuInstanceCreateComputeInstanceWithPlacement.RUnlock() + return calls +} + +// GpuInstanceDestroy calls GpuInstanceDestroyFunc. +func (mock *Interface) GpuInstanceDestroy(gpuInstance nvml.GpuInstance) nvml.Return { + if mock.GpuInstanceDestroyFunc == nil { + panic("Interface.GpuInstanceDestroyFunc: method is nil but Interface.GpuInstanceDestroy was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceDestroy.Lock() + mock.calls.GpuInstanceDestroy = append(mock.calls.GpuInstanceDestroy, callInfo) + mock.lockGpuInstanceDestroy.Unlock() + return mock.GpuInstanceDestroyFunc(gpuInstance) +} + +// GpuInstanceDestroyCalls gets all the calls that were made to GpuInstanceDestroy. +// Check the length with: +// +// len(mockedInterface.GpuInstanceDestroyCalls()) +func (mock *Interface) GpuInstanceDestroyCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceDestroy.RLock() + calls = mock.calls.GpuInstanceDestroy + mock.lockGpuInstanceDestroy.RUnlock() + return calls +} + +// GpuInstanceGetActiveVgpus calls GpuInstanceGetActiveVgpusFunc. +func (mock *Interface) GpuInstanceGetActiveVgpus(gpuInstance nvml.GpuInstance) (nvml.ActiveVgpuInstanceInfo, nvml.Return) { + if mock.GpuInstanceGetActiveVgpusFunc == nil { + panic("Interface.GpuInstanceGetActiveVgpusFunc: method is nil but Interface.GpuInstanceGetActiveVgpus was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetActiveVgpus.Lock() + mock.calls.GpuInstanceGetActiveVgpus = append(mock.calls.GpuInstanceGetActiveVgpus, callInfo) + mock.lockGpuInstanceGetActiveVgpus.Unlock() + return mock.GpuInstanceGetActiveVgpusFunc(gpuInstance) +} + +// GpuInstanceGetActiveVgpusCalls gets all the calls that were made to GpuInstanceGetActiveVgpus. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetActiveVgpusCalls()) +func (mock *Interface) GpuInstanceGetActiveVgpusCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetActiveVgpus.RLock() + calls = mock.calls.GpuInstanceGetActiveVgpus + mock.lockGpuInstanceGetActiveVgpus.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstanceById calls GpuInstanceGetComputeInstanceByIdFunc. +func (mock *Interface) GpuInstanceGetComputeInstanceById(gpuInstance nvml.GpuInstance, n int) (nvml.ComputeInstance, nvml.Return) { + if mock.GpuInstanceGetComputeInstanceByIdFunc == nil { + panic("Interface.GpuInstanceGetComputeInstanceByIdFunc: method is nil but Interface.GpuInstanceGetComputeInstanceById was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + N int + }{ + GpuInstance: gpuInstance, + N: n, + } + mock.lockGpuInstanceGetComputeInstanceById.Lock() + mock.calls.GpuInstanceGetComputeInstanceById = append(mock.calls.GpuInstanceGetComputeInstanceById, callInfo) + mock.lockGpuInstanceGetComputeInstanceById.Unlock() + return mock.GpuInstanceGetComputeInstanceByIdFunc(gpuInstance, n) +} + +// GpuInstanceGetComputeInstanceByIdCalls gets all the calls that were made to GpuInstanceGetComputeInstanceById. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstanceByIdCalls()) +func (mock *Interface) GpuInstanceGetComputeInstanceByIdCalls() []struct { + GpuInstance nvml.GpuInstance + N int +} { + var calls []struct { + GpuInstance nvml.GpuInstance + N int + } + mock.lockGpuInstanceGetComputeInstanceById.RLock() + calls = mock.calls.GpuInstanceGetComputeInstanceById + mock.lockGpuInstanceGetComputeInstanceById.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstancePossiblePlacements calls GpuInstanceGetComputeInstancePossiblePlacementsFunc. +func (mock *Interface) GpuInstanceGetComputeInstancePossiblePlacements(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstancePlacement, nvml.Return) { + if mock.GpuInstanceGetComputeInstancePossiblePlacementsFunc == nil { + panic("Interface.GpuInstanceGetComputeInstancePossiblePlacementsFunc: method is nil but Interface.GpuInstanceGetComputeInstancePossiblePlacements was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + GpuInstance: gpuInstance, + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGpuInstanceGetComputeInstancePossiblePlacements.Lock() + mock.calls.GpuInstanceGetComputeInstancePossiblePlacements = append(mock.calls.GpuInstanceGetComputeInstancePossiblePlacements, callInfo) + mock.lockGpuInstanceGetComputeInstancePossiblePlacements.Unlock() + return mock.GpuInstanceGetComputeInstancePossiblePlacementsFunc(gpuInstance, computeInstanceProfileInfo) +} + +// GpuInstanceGetComputeInstancePossiblePlacementsCalls gets all the calls that were made to GpuInstanceGetComputeInstancePossiblePlacements. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstancePossiblePlacementsCalls()) +func (mock *Interface) GpuInstanceGetComputeInstancePossiblePlacementsCalls() []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGpuInstanceGetComputeInstancePossiblePlacements.RLock() + calls = mock.calls.GpuInstanceGetComputeInstancePossiblePlacements + mock.lockGpuInstanceGetComputeInstancePossiblePlacements.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstanceProfileInfo calls GpuInstanceGetComputeInstanceProfileInfoFunc. +func (mock *Interface) GpuInstanceGetComputeInstanceProfileInfo(gpuInstance nvml.GpuInstance, n1 int, n2 int) (nvml.ComputeInstanceProfileInfo, nvml.Return) { + if mock.GpuInstanceGetComputeInstanceProfileInfoFunc == nil { + panic("Interface.GpuInstanceGetComputeInstanceProfileInfoFunc: method is nil but Interface.GpuInstanceGetComputeInstanceProfileInfo was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int + }{ + GpuInstance: gpuInstance, + N1: n1, + N2: n2, + } + mock.lockGpuInstanceGetComputeInstanceProfileInfo.Lock() + mock.calls.GpuInstanceGetComputeInstanceProfileInfo = append(mock.calls.GpuInstanceGetComputeInstanceProfileInfo, callInfo) + mock.lockGpuInstanceGetComputeInstanceProfileInfo.Unlock() + return mock.GpuInstanceGetComputeInstanceProfileInfoFunc(gpuInstance, n1, n2) +} + +// GpuInstanceGetComputeInstanceProfileInfoCalls gets all the calls that were made to GpuInstanceGetComputeInstanceProfileInfo. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstanceProfileInfoCalls()) +func (mock *Interface) GpuInstanceGetComputeInstanceProfileInfoCalls() []struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int +} { + var calls []struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int + } + mock.lockGpuInstanceGetComputeInstanceProfileInfo.RLock() + calls = mock.calls.GpuInstanceGetComputeInstanceProfileInfo + mock.lockGpuInstanceGetComputeInstanceProfileInfo.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstanceProfileInfoV calls GpuInstanceGetComputeInstanceProfileInfoVFunc. +func (mock *Interface) GpuInstanceGetComputeInstanceProfileInfoV(gpuInstance nvml.GpuInstance, n1 int, n2 int) nvml.ComputeInstanceProfileInfoHandler { + if mock.GpuInstanceGetComputeInstanceProfileInfoVFunc == nil { + panic("Interface.GpuInstanceGetComputeInstanceProfileInfoVFunc: method is nil but Interface.GpuInstanceGetComputeInstanceProfileInfoV was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int + }{ + GpuInstance: gpuInstance, + N1: n1, + N2: n2, + } + mock.lockGpuInstanceGetComputeInstanceProfileInfoV.Lock() + mock.calls.GpuInstanceGetComputeInstanceProfileInfoV = append(mock.calls.GpuInstanceGetComputeInstanceProfileInfoV, callInfo) + mock.lockGpuInstanceGetComputeInstanceProfileInfoV.Unlock() + return mock.GpuInstanceGetComputeInstanceProfileInfoVFunc(gpuInstance, n1, n2) +} + +// GpuInstanceGetComputeInstanceProfileInfoVCalls gets all the calls that were made to GpuInstanceGetComputeInstanceProfileInfoV. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstanceProfileInfoVCalls()) +func (mock *Interface) GpuInstanceGetComputeInstanceProfileInfoVCalls() []struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int +} { + var calls []struct { + GpuInstance nvml.GpuInstance + N1 int + N2 int + } + mock.lockGpuInstanceGetComputeInstanceProfileInfoV.RLock() + calls = mock.calls.GpuInstanceGetComputeInstanceProfileInfoV + mock.lockGpuInstanceGetComputeInstanceProfileInfoV.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstanceRemainingCapacity calls GpuInstanceGetComputeInstanceRemainingCapacityFunc. +func (mock *Interface) GpuInstanceGetComputeInstanceRemainingCapacity(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) (int, nvml.Return) { + if mock.GpuInstanceGetComputeInstanceRemainingCapacityFunc == nil { + panic("Interface.GpuInstanceGetComputeInstanceRemainingCapacityFunc: method is nil but Interface.GpuInstanceGetComputeInstanceRemainingCapacity was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + GpuInstance: gpuInstance, + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGpuInstanceGetComputeInstanceRemainingCapacity.Lock() + mock.calls.GpuInstanceGetComputeInstanceRemainingCapacity = append(mock.calls.GpuInstanceGetComputeInstanceRemainingCapacity, callInfo) + mock.lockGpuInstanceGetComputeInstanceRemainingCapacity.Unlock() + return mock.GpuInstanceGetComputeInstanceRemainingCapacityFunc(gpuInstance, computeInstanceProfileInfo) +} + +// GpuInstanceGetComputeInstanceRemainingCapacityCalls gets all the calls that were made to GpuInstanceGetComputeInstanceRemainingCapacity. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstanceRemainingCapacityCalls()) +func (mock *Interface) GpuInstanceGetComputeInstanceRemainingCapacityCalls() []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGpuInstanceGetComputeInstanceRemainingCapacity.RLock() + calls = mock.calls.GpuInstanceGetComputeInstanceRemainingCapacity + mock.lockGpuInstanceGetComputeInstanceRemainingCapacity.RUnlock() + return calls +} + +// GpuInstanceGetComputeInstances calls GpuInstanceGetComputeInstancesFunc. +func (mock *Interface) GpuInstanceGetComputeInstances(gpuInstance nvml.GpuInstance, computeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo) ([]nvml.ComputeInstance, nvml.Return) { + if mock.GpuInstanceGetComputeInstancesFunc == nil { + panic("Interface.GpuInstanceGetComputeInstancesFunc: method is nil but Interface.GpuInstanceGetComputeInstances was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + }{ + GpuInstance: gpuInstance, + ComputeInstanceProfileInfo: computeInstanceProfileInfo, + } + mock.lockGpuInstanceGetComputeInstances.Lock() + mock.calls.GpuInstanceGetComputeInstances = append(mock.calls.GpuInstanceGetComputeInstances, callInfo) + mock.lockGpuInstanceGetComputeInstances.Unlock() + return mock.GpuInstanceGetComputeInstancesFunc(gpuInstance, computeInstanceProfileInfo) +} + +// GpuInstanceGetComputeInstancesCalls gets all the calls that were made to GpuInstanceGetComputeInstances. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetComputeInstancesCalls()) +func (mock *Interface) GpuInstanceGetComputeInstancesCalls() []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo +} { + var calls []struct { + GpuInstance nvml.GpuInstance + ComputeInstanceProfileInfo *nvml.ComputeInstanceProfileInfo + } + mock.lockGpuInstanceGetComputeInstances.RLock() + calls = mock.calls.GpuInstanceGetComputeInstances + mock.lockGpuInstanceGetComputeInstances.RUnlock() + return calls +} + +// GpuInstanceGetCreatableVgpus calls GpuInstanceGetCreatableVgpusFunc. +func (mock *Interface) GpuInstanceGetCreatableVgpus(gpuInstance nvml.GpuInstance) (nvml.VgpuTypeIdInfo, nvml.Return) { + if mock.GpuInstanceGetCreatableVgpusFunc == nil { + panic("Interface.GpuInstanceGetCreatableVgpusFunc: method is nil but Interface.GpuInstanceGetCreatableVgpus was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetCreatableVgpus.Lock() + mock.calls.GpuInstanceGetCreatableVgpus = append(mock.calls.GpuInstanceGetCreatableVgpus, callInfo) + mock.lockGpuInstanceGetCreatableVgpus.Unlock() + return mock.GpuInstanceGetCreatableVgpusFunc(gpuInstance) +} + +// GpuInstanceGetCreatableVgpusCalls gets all the calls that were made to GpuInstanceGetCreatableVgpus. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetCreatableVgpusCalls()) +func (mock *Interface) GpuInstanceGetCreatableVgpusCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetCreatableVgpus.RLock() + calls = mock.calls.GpuInstanceGetCreatableVgpus + mock.lockGpuInstanceGetCreatableVgpus.RUnlock() + return calls +} + +// GpuInstanceGetInfo calls GpuInstanceGetInfoFunc. +func (mock *Interface) GpuInstanceGetInfo(gpuInstance nvml.GpuInstance) (nvml.GpuInstanceInfo, nvml.Return) { + if mock.GpuInstanceGetInfoFunc == nil { + panic("Interface.GpuInstanceGetInfoFunc: method is nil but Interface.GpuInstanceGetInfo was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetInfo.Lock() + mock.calls.GpuInstanceGetInfo = append(mock.calls.GpuInstanceGetInfo, callInfo) + mock.lockGpuInstanceGetInfo.Unlock() + return mock.GpuInstanceGetInfoFunc(gpuInstance) +} + +// GpuInstanceGetInfoCalls gets all the calls that were made to GpuInstanceGetInfo. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetInfoCalls()) +func (mock *Interface) GpuInstanceGetInfoCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetInfo.RLock() + calls = mock.calls.GpuInstanceGetInfo + mock.lockGpuInstanceGetInfo.RUnlock() + return calls +} + +// GpuInstanceGetVgpuHeterogeneousMode calls GpuInstanceGetVgpuHeterogeneousModeFunc. +func (mock *Interface) GpuInstanceGetVgpuHeterogeneousMode(gpuInstance nvml.GpuInstance) (nvml.VgpuHeterogeneousMode, nvml.Return) { + if mock.GpuInstanceGetVgpuHeterogeneousModeFunc == nil { + panic("Interface.GpuInstanceGetVgpuHeterogeneousModeFunc: method is nil but Interface.GpuInstanceGetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetVgpuHeterogeneousMode.Lock() + mock.calls.GpuInstanceGetVgpuHeterogeneousMode = append(mock.calls.GpuInstanceGetVgpuHeterogeneousMode, callInfo) + mock.lockGpuInstanceGetVgpuHeterogeneousMode.Unlock() + return mock.GpuInstanceGetVgpuHeterogeneousModeFunc(gpuInstance) +} + +// GpuInstanceGetVgpuHeterogeneousModeCalls gets all the calls that were made to GpuInstanceGetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetVgpuHeterogeneousModeCalls()) +func (mock *Interface) GpuInstanceGetVgpuHeterogeneousModeCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetVgpuHeterogeneousMode.RLock() + calls = mock.calls.GpuInstanceGetVgpuHeterogeneousMode + mock.lockGpuInstanceGetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// GpuInstanceGetVgpuSchedulerLog calls GpuInstanceGetVgpuSchedulerLogFunc. +func (mock *Interface) GpuInstanceGetVgpuSchedulerLog(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerLogInfo, nvml.Return) { + if mock.GpuInstanceGetVgpuSchedulerLogFunc == nil { + panic("Interface.GpuInstanceGetVgpuSchedulerLogFunc: method is nil but Interface.GpuInstanceGetVgpuSchedulerLog was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetVgpuSchedulerLog.Lock() + mock.calls.GpuInstanceGetVgpuSchedulerLog = append(mock.calls.GpuInstanceGetVgpuSchedulerLog, callInfo) + mock.lockGpuInstanceGetVgpuSchedulerLog.Unlock() + return mock.GpuInstanceGetVgpuSchedulerLogFunc(gpuInstance) +} + +// GpuInstanceGetVgpuSchedulerLogCalls gets all the calls that were made to GpuInstanceGetVgpuSchedulerLog. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetVgpuSchedulerLogCalls()) +func (mock *Interface) GpuInstanceGetVgpuSchedulerLogCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetVgpuSchedulerLog.RLock() + calls = mock.calls.GpuInstanceGetVgpuSchedulerLog + mock.lockGpuInstanceGetVgpuSchedulerLog.RUnlock() + return calls +} + +// GpuInstanceGetVgpuSchedulerState calls GpuInstanceGetVgpuSchedulerStateFunc. +func (mock *Interface) GpuInstanceGetVgpuSchedulerState(gpuInstance nvml.GpuInstance) (nvml.VgpuSchedulerStateInfo, nvml.Return) { + if mock.GpuInstanceGetVgpuSchedulerStateFunc == nil { + panic("Interface.GpuInstanceGetVgpuSchedulerStateFunc: method is nil but Interface.GpuInstanceGetVgpuSchedulerState was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetVgpuSchedulerState.Lock() + mock.calls.GpuInstanceGetVgpuSchedulerState = append(mock.calls.GpuInstanceGetVgpuSchedulerState, callInfo) + mock.lockGpuInstanceGetVgpuSchedulerState.Unlock() + return mock.GpuInstanceGetVgpuSchedulerStateFunc(gpuInstance) +} + +// GpuInstanceGetVgpuSchedulerStateCalls gets all the calls that were made to GpuInstanceGetVgpuSchedulerState. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetVgpuSchedulerStateCalls()) +func (mock *Interface) GpuInstanceGetVgpuSchedulerStateCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetVgpuSchedulerState.RLock() + calls = mock.calls.GpuInstanceGetVgpuSchedulerState + mock.lockGpuInstanceGetVgpuSchedulerState.RUnlock() + return calls +} + +// GpuInstanceGetVgpuTypeCreatablePlacements calls GpuInstanceGetVgpuTypeCreatablePlacementsFunc. +func (mock *Interface) GpuInstanceGetVgpuTypeCreatablePlacements(gpuInstance nvml.GpuInstance) (nvml.VgpuCreatablePlacementInfo, nvml.Return) { + if mock.GpuInstanceGetVgpuTypeCreatablePlacementsFunc == nil { + panic("Interface.GpuInstanceGetVgpuTypeCreatablePlacementsFunc: method is nil but Interface.GpuInstanceGetVgpuTypeCreatablePlacements was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + }{ + GpuInstance: gpuInstance, + } + mock.lockGpuInstanceGetVgpuTypeCreatablePlacements.Lock() + mock.calls.GpuInstanceGetVgpuTypeCreatablePlacements = append(mock.calls.GpuInstanceGetVgpuTypeCreatablePlacements, callInfo) + mock.lockGpuInstanceGetVgpuTypeCreatablePlacements.Unlock() + return mock.GpuInstanceGetVgpuTypeCreatablePlacementsFunc(gpuInstance) +} + +// GpuInstanceGetVgpuTypeCreatablePlacementsCalls gets all the calls that were made to GpuInstanceGetVgpuTypeCreatablePlacements. +// Check the length with: +// +// len(mockedInterface.GpuInstanceGetVgpuTypeCreatablePlacementsCalls()) +func (mock *Interface) GpuInstanceGetVgpuTypeCreatablePlacementsCalls() []struct { + GpuInstance nvml.GpuInstance +} { + var calls []struct { + GpuInstance nvml.GpuInstance + } + mock.lockGpuInstanceGetVgpuTypeCreatablePlacements.RLock() + calls = mock.calls.GpuInstanceGetVgpuTypeCreatablePlacements + mock.lockGpuInstanceGetVgpuTypeCreatablePlacements.RUnlock() + return calls +} + +// GpuInstanceSetVgpuHeterogeneousMode calls GpuInstanceSetVgpuHeterogeneousModeFunc. +func (mock *Interface) GpuInstanceSetVgpuHeterogeneousMode(gpuInstance nvml.GpuInstance, vgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode) nvml.Return { + if mock.GpuInstanceSetVgpuHeterogeneousModeFunc == nil { + panic("Interface.GpuInstanceSetVgpuHeterogeneousModeFunc: method is nil but Interface.GpuInstanceSetVgpuHeterogeneousMode was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + }{ + GpuInstance: gpuInstance, + VgpuHeterogeneousMode: vgpuHeterogeneousMode, + } + mock.lockGpuInstanceSetVgpuHeterogeneousMode.Lock() + mock.calls.GpuInstanceSetVgpuHeterogeneousMode = append(mock.calls.GpuInstanceSetVgpuHeterogeneousMode, callInfo) + mock.lockGpuInstanceSetVgpuHeterogeneousMode.Unlock() + return mock.GpuInstanceSetVgpuHeterogeneousModeFunc(gpuInstance, vgpuHeterogeneousMode) +} + +// GpuInstanceSetVgpuHeterogeneousModeCalls gets all the calls that were made to GpuInstanceSetVgpuHeterogeneousMode. +// Check the length with: +// +// len(mockedInterface.GpuInstanceSetVgpuHeterogeneousModeCalls()) +func (mock *Interface) GpuInstanceSetVgpuHeterogeneousModeCalls() []struct { + GpuInstance nvml.GpuInstance + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode +} { + var calls []struct { + GpuInstance nvml.GpuInstance + VgpuHeterogeneousMode *nvml.VgpuHeterogeneousMode + } + mock.lockGpuInstanceSetVgpuHeterogeneousMode.RLock() + calls = mock.calls.GpuInstanceSetVgpuHeterogeneousMode + mock.lockGpuInstanceSetVgpuHeterogeneousMode.RUnlock() + return calls +} + +// GpuInstanceSetVgpuSchedulerState calls GpuInstanceSetVgpuSchedulerStateFunc. +func (mock *Interface) GpuInstanceSetVgpuSchedulerState(gpuInstance nvml.GpuInstance, vgpuSchedulerState *nvml.VgpuSchedulerState) nvml.Return { + if mock.GpuInstanceSetVgpuSchedulerStateFunc == nil { + panic("Interface.GpuInstanceSetVgpuSchedulerStateFunc: method is nil but Interface.GpuInstanceSetVgpuSchedulerState was just called") + } + callInfo := struct { + GpuInstance nvml.GpuInstance + VgpuSchedulerState *nvml.VgpuSchedulerState + }{ + GpuInstance: gpuInstance, + VgpuSchedulerState: vgpuSchedulerState, + } + mock.lockGpuInstanceSetVgpuSchedulerState.Lock() + mock.calls.GpuInstanceSetVgpuSchedulerState = append(mock.calls.GpuInstanceSetVgpuSchedulerState, callInfo) + mock.lockGpuInstanceSetVgpuSchedulerState.Unlock() + return mock.GpuInstanceSetVgpuSchedulerStateFunc(gpuInstance, vgpuSchedulerState) +} + +// GpuInstanceSetVgpuSchedulerStateCalls gets all the calls that were made to GpuInstanceSetVgpuSchedulerState. +// Check the length with: +// +// len(mockedInterface.GpuInstanceSetVgpuSchedulerStateCalls()) +func (mock *Interface) GpuInstanceSetVgpuSchedulerStateCalls() []struct { + GpuInstance nvml.GpuInstance + VgpuSchedulerState *nvml.VgpuSchedulerState +} { + var calls []struct { + GpuInstance nvml.GpuInstance + VgpuSchedulerState *nvml.VgpuSchedulerState + } + mock.lockGpuInstanceSetVgpuSchedulerState.RLock() + calls = mock.calls.GpuInstanceSetVgpuSchedulerState + mock.lockGpuInstanceSetVgpuSchedulerState.RUnlock() + return calls +} + +// Init calls InitFunc. +func (mock *Interface) Init() nvml.Return { + if mock.InitFunc == nil { + panic("Interface.InitFunc: method is nil but Interface.Init was just called") + } + callInfo := struct { + }{} + mock.lockInit.Lock() + mock.calls.Init = append(mock.calls.Init, callInfo) + mock.lockInit.Unlock() + return mock.InitFunc() +} + +// InitCalls gets all the calls that were made to Init. +// Check the length with: +// +// len(mockedInterface.InitCalls()) +func (mock *Interface) InitCalls() []struct { +} { + var calls []struct { + } + mock.lockInit.RLock() + calls = mock.calls.Init + mock.lockInit.RUnlock() + return calls +} + +// InitWithFlags calls InitWithFlagsFunc. +func (mock *Interface) InitWithFlags(v uint32) nvml.Return { + if mock.InitWithFlagsFunc == nil { + panic("Interface.InitWithFlagsFunc: method is nil but Interface.InitWithFlags was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockInitWithFlags.Lock() + mock.calls.InitWithFlags = append(mock.calls.InitWithFlags, callInfo) + mock.lockInitWithFlags.Unlock() + return mock.InitWithFlagsFunc(v) +} + +// InitWithFlagsCalls gets all the calls that were made to InitWithFlags. +// Check the length with: +// +// len(mockedInterface.InitWithFlagsCalls()) +func (mock *Interface) InitWithFlagsCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockInitWithFlags.RLock() + calls = mock.calls.InitWithFlags + mock.lockInitWithFlags.RUnlock() + return calls +} + +// SetVgpuVersion calls SetVgpuVersionFunc. +func (mock *Interface) SetVgpuVersion(vgpuVersion *nvml.VgpuVersion) nvml.Return { + if mock.SetVgpuVersionFunc == nil { + panic("Interface.SetVgpuVersionFunc: method is nil but Interface.SetVgpuVersion was just called") + } + callInfo := struct { + VgpuVersion *nvml.VgpuVersion + }{ + VgpuVersion: vgpuVersion, + } + mock.lockSetVgpuVersion.Lock() + mock.calls.SetVgpuVersion = append(mock.calls.SetVgpuVersion, callInfo) + mock.lockSetVgpuVersion.Unlock() + return mock.SetVgpuVersionFunc(vgpuVersion) +} + +// SetVgpuVersionCalls gets all the calls that were made to SetVgpuVersion. +// Check the length with: +// +// len(mockedInterface.SetVgpuVersionCalls()) +func (mock *Interface) SetVgpuVersionCalls() []struct { + VgpuVersion *nvml.VgpuVersion +} { + var calls []struct { + VgpuVersion *nvml.VgpuVersion + } + mock.lockSetVgpuVersion.RLock() + calls = mock.calls.SetVgpuVersion + mock.lockSetVgpuVersion.RUnlock() + return calls +} + +// Shutdown calls ShutdownFunc. +func (mock *Interface) Shutdown() nvml.Return { + if mock.ShutdownFunc == nil { + panic("Interface.ShutdownFunc: method is nil but Interface.Shutdown was just called") + } + callInfo := struct { + }{} + mock.lockShutdown.Lock() + mock.calls.Shutdown = append(mock.calls.Shutdown, callInfo) + mock.lockShutdown.Unlock() + return mock.ShutdownFunc() +} + +// ShutdownCalls gets all the calls that were made to Shutdown. +// Check the length with: +// +// len(mockedInterface.ShutdownCalls()) +func (mock *Interface) ShutdownCalls() []struct { +} { + var calls []struct { + } + mock.lockShutdown.RLock() + calls = mock.calls.Shutdown + mock.lockShutdown.RUnlock() + return calls +} + +// SystemEventSetCreate calls SystemEventSetCreateFunc. +func (mock *Interface) SystemEventSetCreate(systemEventSetCreateRequest *nvml.SystemEventSetCreateRequest) nvml.Return { + if mock.SystemEventSetCreateFunc == nil { + panic("Interface.SystemEventSetCreateFunc: method is nil but Interface.SystemEventSetCreate was just called") + } + callInfo := struct { + SystemEventSetCreateRequest *nvml.SystemEventSetCreateRequest + }{ + SystemEventSetCreateRequest: systemEventSetCreateRequest, + } + mock.lockSystemEventSetCreate.Lock() + mock.calls.SystemEventSetCreate = append(mock.calls.SystemEventSetCreate, callInfo) + mock.lockSystemEventSetCreate.Unlock() + return mock.SystemEventSetCreateFunc(systemEventSetCreateRequest) +} + +// SystemEventSetCreateCalls gets all the calls that were made to SystemEventSetCreate. +// Check the length with: +// +// len(mockedInterface.SystemEventSetCreateCalls()) +func (mock *Interface) SystemEventSetCreateCalls() []struct { + SystemEventSetCreateRequest *nvml.SystemEventSetCreateRequest +} { + var calls []struct { + SystemEventSetCreateRequest *nvml.SystemEventSetCreateRequest + } + mock.lockSystemEventSetCreate.RLock() + calls = mock.calls.SystemEventSetCreate + mock.lockSystemEventSetCreate.RUnlock() + return calls +} + +// SystemEventSetFree calls SystemEventSetFreeFunc. +func (mock *Interface) SystemEventSetFree(systemEventSetFreeRequest *nvml.SystemEventSetFreeRequest) nvml.Return { + if mock.SystemEventSetFreeFunc == nil { + panic("Interface.SystemEventSetFreeFunc: method is nil but Interface.SystemEventSetFree was just called") + } + callInfo := struct { + SystemEventSetFreeRequest *nvml.SystemEventSetFreeRequest + }{ + SystemEventSetFreeRequest: systemEventSetFreeRequest, + } + mock.lockSystemEventSetFree.Lock() + mock.calls.SystemEventSetFree = append(mock.calls.SystemEventSetFree, callInfo) + mock.lockSystemEventSetFree.Unlock() + return mock.SystemEventSetFreeFunc(systemEventSetFreeRequest) +} + +// SystemEventSetFreeCalls gets all the calls that were made to SystemEventSetFree. +// Check the length with: +// +// len(mockedInterface.SystemEventSetFreeCalls()) +func (mock *Interface) SystemEventSetFreeCalls() []struct { + SystemEventSetFreeRequest *nvml.SystemEventSetFreeRequest +} { + var calls []struct { + SystemEventSetFreeRequest *nvml.SystemEventSetFreeRequest + } + mock.lockSystemEventSetFree.RLock() + calls = mock.calls.SystemEventSetFree + mock.lockSystemEventSetFree.RUnlock() + return calls +} + +// SystemEventSetWait calls SystemEventSetWaitFunc. +func (mock *Interface) SystemEventSetWait(systemEventSetWaitRequest *nvml.SystemEventSetWaitRequest) nvml.Return { + if mock.SystemEventSetWaitFunc == nil { + panic("Interface.SystemEventSetWaitFunc: method is nil but Interface.SystemEventSetWait was just called") + } + callInfo := struct { + SystemEventSetWaitRequest *nvml.SystemEventSetWaitRequest + }{ + SystemEventSetWaitRequest: systemEventSetWaitRequest, + } + mock.lockSystemEventSetWait.Lock() + mock.calls.SystemEventSetWait = append(mock.calls.SystemEventSetWait, callInfo) + mock.lockSystemEventSetWait.Unlock() + return mock.SystemEventSetWaitFunc(systemEventSetWaitRequest) +} + +// SystemEventSetWaitCalls gets all the calls that were made to SystemEventSetWait. +// Check the length with: +// +// len(mockedInterface.SystemEventSetWaitCalls()) +func (mock *Interface) SystemEventSetWaitCalls() []struct { + SystemEventSetWaitRequest *nvml.SystemEventSetWaitRequest +} { + var calls []struct { + SystemEventSetWaitRequest *nvml.SystemEventSetWaitRequest + } + mock.lockSystemEventSetWait.RLock() + calls = mock.calls.SystemEventSetWait + mock.lockSystemEventSetWait.RUnlock() + return calls +} + +// SystemGetConfComputeCapabilities calls SystemGetConfComputeCapabilitiesFunc. +func (mock *Interface) SystemGetConfComputeCapabilities() (nvml.ConfComputeSystemCaps, nvml.Return) { + if mock.SystemGetConfComputeCapabilitiesFunc == nil { + panic("Interface.SystemGetConfComputeCapabilitiesFunc: method is nil but Interface.SystemGetConfComputeCapabilities was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetConfComputeCapabilities.Lock() + mock.calls.SystemGetConfComputeCapabilities = append(mock.calls.SystemGetConfComputeCapabilities, callInfo) + mock.lockSystemGetConfComputeCapabilities.Unlock() + return mock.SystemGetConfComputeCapabilitiesFunc() +} + +// SystemGetConfComputeCapabilitiesCalls gets all the calls that were made to SystemGetConfComputeCapabilities. +// Check the length with: +// +// len(mockedInterface.SystemGetConfComputeCapabilitiesCalls()) +func (mock *Interface) SystemGetConfComputeCapabilitiesCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetConfComputeCapabilities.RLock() + calls = mock.calls.SystemGetConfComputeCapabilities + mock.lockSystemGetConfComputeCapabilities.RUnlock() + return calls +} + +// SystemGetConfComputeGpusReadyState calls SystemGetConfComputeGpusReadyStateFunc. +func (mock *Interface) SystemGetConfComputeGpusReadyState() (uint32, nvml.Return) { + if mock.SystemGetConfComputeGpusReadyStateFunc == nil { + panic("Interface.SystemGetConfComputeGpusReadyStateFunc: method is nil but Interface.SystemGetConfComputeGpusReadyState was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetConfComputeGpusReadyState.Lock() + mock.calls.SystemGetConfComputeGpusReadyState = append(mock.calls.SystemGetConfComputeGpusReadyState, callInfo) + mock.lockSystemGetConfComputeGpusReadyState.Unlock() + return mock.SystemGetConfComputeGpusReadyStateFunc() +} + +// SystemGetConfComputeGpusReadyStateCalls gets all the calls that were made to SystemGetConfComputeGpusReadyState. +// Check the length with: +// +// len(mockedInterface.SystemGetConfComputeGpusReadyStateCalls()) +func (mock *Interface) SystemGetConfComputeGpusReadyStateCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetConfComputeGpusReadyState.RLock() + calls = mock.calls.SystemGetConfComputeGpusReadyState + mock.lockSystemGetConfComputeGpusReadyState.RUnlock() + return calls +} + +// SystemGetConfComputeKeyRotationThresholdInfo calls SystemGetConfComputeKeyRotationThresholdInfoFunc. +func (mock *Interface) SystemGetConfComputeKeyRotationThresholdInfo() (nvml.ConfComputeGetKeyRotationThresholdInfo, nvml.Return) { + if mock.SystemGetConfComputeKeyRotationThresholdInfoFunc == nil { + panic("Interface.SystemGetConfComputeKeyRotationThresholdInfoFunc: method is nil but Interface.SystemGetConfComputeKeyRotationThresholdInfo was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetConfComputeKeyRotationThresholdInfo.Lock() + mock.calls.SystemGetConfComputeKeyRotationThresholdInfo = append(mock.calls.SystemGetConfComputeKeyRotationThresholdInfo, callInfo) + mock.lockSystemGetConfComputeKeyRotationThresholdInfo.Unlock() + return mock.SystemGetConfComputeKeyRotationThresholdInfoFunc() +} + +// SystemGetConfComputeKeyRotationThresholdInfoCalls gets all the calls that were made to SystemGetConfComputeKeyRotationThresholdInfo. +// Check the length with: +// +// len(mockedInterface.SystemGetConfComputeKeyRotationThresholdInfoCalls()) +func (mock *Interface) SystemGetConfComputeKeyRotationThresholdInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetConfComputeKeyRotationThresholdInfo.RLock() + calls = mock.calls.SystemGetConfComputeKeyRotationThresholdInfo + mock.lockSystemGetConfComputeKeyRotationThresholdInfo.RUnlock() + return calls +} + +// SystemGetConfComputeSettings calls SystemGetConfComputeSettingsFunc. +func (mock *Interface) SystemGetConfComputeSettings() (nvml.SystemConfComputeSettings, nvml.Return) { + if mock.SystemGetConfComputeSettingsFunc == nil { + panic("Interface.SystemGetConfComputeSettingsFunc: method is nil but Interface.SystemGetConfComputeSettings was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetConfComputeSettings.Lock() + mock.calls.SystemGetConfComputeSettings = append(mock.calls.SystemGetConfComputeSettings, callInfo) + mock.lockSystemGetConfComputeSettings.Unlock() + return mock.SystemGetConfComputeSettingsFunc() +} + +// SystemGetConfComputeSettingsCalls gets all the calls that were made to SystemGetConfComputeSettings. +// Check the length with: +// +// len(mockedInterface.SystemGetConfComputeSettingsCalls()) +func (mock *Interface) SystemGetConfComputeSettingsCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetConfComputeSettings.RLock() + calls = mock.calls.SystemGetConfComputeSettings + mock.lockSystemGetConfComputeSettings.RUnlock() + return calls +} + +// SystemGetConfComputeState calls SystemGetConfComputeStateFunc. +func (mock *Interface) SystemGetConfComputeState() (nvml.ConfComputeSystemState, nvml.Return) { + if mock.SystemGetConfComputeStateFunc == nil { + panic("Interface.SystemGetConfComputeStateFunc: method is nil but Interface.SystemGetConfComputeState was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetConfComputeState.Lock() + mock.calls.SystemGetConfComputeState = append(mock.calls.SystemGetConfComputeState, callInfo) + mock.lockSystemGetConfComputeState.Unlock() + return mock.SystemGetConfComputeStateFunc() +} + +// SystemGetConfComputeStateCalls gets all the calls that were made to SystemGetConfComputeState. +// Check the length with: +// +// len(mockedInterface.SystemGetConfComputeStateCalls()) +func (mock *Interface) SystemGetConfComputeStateCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetConfComputeState.RLock() + calls = mock.calls.SystemGetConfComputeState + mock.lockSystemGetConfComputeState.RUnlock() + return calls +} + +// SystemGetCudaDriverVersion calls SystemGetCudaDriverVersionFunc. +func (mock *Interface) SystemGetCudaDriverVersion() (int, nvml.Return) { + if mock.SystemGetCudaDriverVersionFunc == nil { + panic("Interface.SystemGetCudaDriverVersionFunc: method is nil but Interface.SystemGetCudaDriverVersion was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetCudaDriverVersion.Lock() + mock.calls.SystemGetCudaDriverVersion = append(mock.calls.SystemGetCudaDriverVersion, callInfo) + mock.lockSystemGetCudaDriverVersion.Unlock() + return mock.SystemGetCudaDriverVersionFunc() +} + +// SystemGetCudaDriverVersionCalls gets all the calls that were made to SystemGetCudaDriverVersion. +// Check the length with: +// +// len(mockedInterface.SystemGetCudaDriverVersionCalls()) +func (mock *Interface) SystemGetCudaDriverVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetCudaDriverVersion.RLock() + calls = mock.calls.SystemGetCudaDriverVersion + mock.lockSystemGetCudaDriverVersion.RUnlock() + return calls +} + +// SystemGetCudaDriverVersion_v2 calls SystemGetCudaDriverVersion_v2Func. +func (mock *Interface) SystemGetCudaDriverVersion_v2() (int, nvml.Return) { + if mock.SystemGetCudaDriverVersion_v2Func == nil { + panic("Interface.SystemGetCudaDriverVersion_v2Func: method is nil but Interface.SystemGetCudaDriverVersion_v2 was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetCudaDriverVersion_v2.Lock() + mock.calls.SystemGetCudaDriverVersion_v2 = append(mock.calls.SystemGetCudaDriverVersion_v2, callInfo) + mock.lockSystemGetCudaDriverVersion_v2.Unlock() + return mock.SystemGetCudaDriverVersion_v2Func() +} + +// SystemGetCudaDriverVersion_v2Calls gets all the calls that were made to SystemGetCudaDriverVersion_v2. +// Check the length with: +// +// len(mockedInterface.SystemGetCudaDriverVersion_v2Calls()) +func (mock *Interface) SystemGetCudaDriverVersion_v2Calls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetCudaDriverVersion_v2.RLock() + calls = mock.calls.SystemGetCudaDriverVersion_v2 + mock.lockSystemGetCudaDriverVersion_v2.RUnlock() + return calls +} + +// SystemGetDriverBranch calls SystemGetDriverBranchFunc. +func (mock *Interface) SystemGetDriverBranch() (nvml.SystemDriverBranchInfo, nvml.Return) { + if mock.SystemGetDriverBranchFunc == nil { + panic("Interface.SystemGetDriverBranchFunc: method is nil but Interface.SystemGetDriverBranch was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetDriverBranch.Lock() + mock.calls.SystemGetDriverBranch = append(mock.calls.SystemGetDriverBranch, callInfo) + mock.lockSystemGetDriverBranch.Unlock() + return mock.SystemGetDriverBranchFunc() +} + +// SystemGetDriverBranchCalls gets all the calls that were made to SystemGetDriverBranch. +// Check the length with: +// +// len(mockedInterface.SystemGetDriverBranchCalls()) +func (mock *Interface) SystemGetDriverBranchCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetDriverBranch.RLock() + calls = mock.calls.SystemGetDriverBranch + mock.lockSystemGetDriverBranch.RUnlock() + return calls +} + +// SystemGetDriverVersion calls SystemGetDriverVersionFunc. +func (mock *Interface) SystemGetDriverVersion() (string, nvml.Return) { + if mock.SystemGetDriverVersionFunc == nil { + panic("Interface.SystemGetDriverVersionFunc: method is nil but Interface.SystemGetDriverVersion was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetDriverVersion.Lock() + mock.calls.SystemGetDriverVersion = append(mock.calls.SystemGetDriverVersion, callInfo) + mock.lockSystemGetDriverVersion.Unlock() + return mock.SystemGetDriverVersionFunc() +} + +// SystemGetDriverVersionCalls gets all the calls that were made to SystemGetDriverVersion. +// Check the length with: +// +// len(mockedInterface.SystemGetDriverVersionCalls()) +func (mock *Interface) SystemGetDriverVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetDriverVersion.RLock() + calls = mock.calls.SystemGetDriverVersion + mock.lockSystemGetDriverVersion.RUnlock() + return calls +} + +// SystemGetHicVersion calls SystemGetHicVersionFunc. +func (mock *Interface) SystemGetHicVersion() ([]nvml.HwbcEntry, nvml.Return) { + if mock.SystemGetHicVersionFunc == nil { + panic("Interface.SystemGetHicVersionFunc: method is nil but Interface.SystemGetHicVersion was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetHicVersion.Lock() + mock.calls.SystemGetHicVersion = append(mock.calls.SystemGetHicVersion, callInfo) + mock.lockSystemGetHicVersion.Unlock() + return mock.SystemGetHicVersionFunc() +} + +// SystemGetHicVersionCalls gets all the calls that were made to SystemGetHicVersion. +// Check the length with: +// +// len(mockedInterface.SystemGetHicVersionCalls()) +func (mock *Interface) SystemGetHicVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetHicVersion.RLock() + calls = mock.calls.SystemGetHicVersion + mock.lockSystemGetHicVersion.RUnlock() + return calls +} + +// SystemGetNVMLVersion calls SystemGetNVMLVersionFunc. +func (mock *Interface) SystemGetNVMLVersion() (string, nvml.Return) { + if mock.SystemGetNVMLVersionFunc == nil { + panic("Interface.SystemGetNVMLVersionFunc: method is nil but Interface.SystemGetNVMLVersion was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetNVMLVersion.Lock() + mock.calls.SystemGetNVMLVersion = append(mock.calls.SystemGetNVMLVersion, callInfo) + mock.lockSystemGetNVMLVersion.Unlock() + return mock.SystemGetNVMLVersionFunc() +} + +// SystemGetNVMLVersionCalls gets all the calls that were made to SystemGetNVMLVersion. +// Check the length with: +// +// len(mockedInterface.SystemGetNVMLVersionCalls()) +func (mock *Interface) SystemGetNVMLVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetNVMLVersion.RLock() + calls = mock.calls.SystemGetNVMLVersion + mock.lockSystemGetNVMLVersion.RUnlock() + return calls +} + +// SystemGetNvlinkBwMode calls SystemGetNvlinkBwModeFunc. +func (mock *Interface) SystemGetNvlinkBwMode() (uint32, nvml.Return) { + if mock.SystemGetNvlinkBwModeFunc == nil { + panic("Interface.SystemGetNvlinkBwModeFunc: method is nil but Interface.SystemGetNvlinkBwMode was just called") + } + callInfo := struct { + }{} + mock.lockSystemGetNvlinkBwMode.Lock() + mock.calls.SystemGetNvlinkBwMode = append(mock.calls.SystemGetNvlinkBwMode, callInfo) + mock.lockSystemGetNvlinkBwMode.Unlock() + return mock.SystemGetNvlinkBwModeFunc() +} + +// SystemGetNvlinkBwModeCalls gets all the calls that were made to SystemGetNvlinkBwMode. +// Check the length with: +// +// len(mockedInterface.SystemGetNvlinkBwModeCalls()) +func (mock *Interface) SystemGetNvlinkBwModeCalls() []struct { +} { + var calls []struct { + } + mock.lockSystemGetNvlinkBwMode.RLock() + calls = mock.calls.SystemGetNvlinkBwMode + mock.lockSystemGetNvlinkBwMode.RUnlock() + return calls +} + +// SystemGetProcessName calls SystemGetProcessNameFunc. +func (mock *Interface) SystemGetProcessName(n int) (string, nvml.Return) { + if mock.SystemGetProcessNameFunc == nil { + panic("Interface.SystemGetProcessNameFunc: method is nil but Interface.SystemGetProcessName was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSystemGetProcessName.Lock() + mock.calls.SystemGetProcessName = append(mock.calls.SystemGetProcessName, callInfo) + mock.lockSystemGetProcessName.Unlock() + return mock.SystemGetProcessNameFunc(n) +} + +// SystemGetProcessNameCalls gets all the calls that were made to SystemGetProcessName. +// Check the length with: +// +// len(mockedInterface.SystemGetProcessNameCalls()) +func (mock *Interface) SystemGetProcessNameCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSystemGetProcessName.RLock() + calls = mock.calls.SystemGetProcessName + mock.lockSystemGetProcessName.RUnlock() + return calls +} + +// SystemGetTopologyGpuSet calls SystemGetTopologyGpuSetFunc. +func (mock *Interface) SystemGetTopologyGpuSet(n int) ([]nvml.Device, nvml.Return) { + if mock.SystemGetTopologyGpuSetFunc == nil { + panic("Interface.SystemGetTopologyGpuSetFunc: method is nil but Interface.SystemGetTopologyGpuSet was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSystemGetTopologyGpuSet.Lock() + mock.calls.SystemGetTopologyGpuSet = append(mock.calls.SystemGetTopologyGpuSet, callInfo) + mock.lockSystemGetTopologyGpuSet.Unlock() + return mock.SystemGetTopologyGpuSetFunc(n) +} + +// SystemGetTopologyGpuSetCalls gets all the calls that were made to SystemGetTopologyGpuSet. +// Check the length with: +// +// len(mockedInterface.SystemGetTopologyGpuSetCalls()) +func (mock *Interface) SystemGetTopologyGpuSetCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSystemGetTopologyGpuSet.RLock() + calls = mock.calls.SystemGetTopologyGpuSet + mock.lockSystemGetTopologyGpuSet.RUnlock() + return calls +} + +// SystemRegisterEvents calls SystemRegisterEventsFunc. +func (mock *Interface) SystemRegisterEvents(systemRegisterEventRequest *nvml.SystemRegisterEventRequest) nvml.Return { + if mock.SystemRegisterEventsFunc == nil { + panic("Interface.SystemRegisterEventsFunc: method is nil but Interface.SystemRegisterEvents was just called") + } + callInfo := struct { + SystemRegisterEventRequest *nvml.SystemRegisterEventRequest + }{ + SystemRegisterEventRequest: systemRegisterEventRequest, + } + mock.lockSystemRegisterEvents.Lock() + mock.calls.SystemRegisterEvents = append(mock.calls.SystemRegisterEvents, callInfo) + mock.lockSystemRegisterEvents.Unlock() + return mock.SystemRegisterEventsFunc(systemRegisterEventRequest) +} + +// SystemRegisterEventsCalls gets all the calls that were made to SystemRegisterEvents. +// Check the length with: +// +// len(mockedInterface.SystemRegisterEventsCalls()) +func (mock *Interface) SystemRegisterEventsCalls() []struct { + SystemRegisterEventRequest *nvml.SystemRegisterEventRequest +} { + var calls []struct { + SystemRegisterEventRequest *nvml.SystemRegisterEventRequest + } + mock.lockSystemRegisterEvents.RLock() + calls = mock.calls.SystemRegisterEvents + mock.lockSystemRegisterEvents.RUnlock() + return calls +} + +// SystemSetConfComputeGpusReadyState calls SystemSetConfComputeGpusReadyStateFunc. +func (mock *Interface) SystemSetConfComputeGpusReadyState(v uint32) nvml.Return { + if mock.SystemSetConfComputeGpusReadyStateFunc == nil { + panic("Interface.SystemSetConfComputeGpusReadyStateFunc: method is nil but Interface.SystemSetConfComputeGpusReadyState was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockSystemSetConfComputeGpusReadyState.Lock() + mock.calls.SystemSetConfComputeGpusReadyState = append(mock.calls.SystemSetConfComputeGpusReadyState, callInfo) + mock.lockSystemSetConfComputeGpusReadyState.Unlock() + return mock.SystemSetConfComputeGpusReadyStateFunc(v) +} + +// SystemSetConfComputeGpusReadyStateCalls gets all the calls that were made to SystemSetConfComputeGpusReadyState. +// Check the length with: +// +// len(mockedInterface.SystemSetConfComputeGpusReadyStateCalls()) +func (mock *Interface) SystemSetConfComputeGpusReadyStateCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockSystemSetConfComputeGpusReadyState.RLock() + calls = mock.calls.SystemSetConfComputeGpusReadyState + mock.lockSystemSetConfComputeGpusReadyState.RUnlock() + return calls +} + +// SystemSetConfComputeKeyRotationThresholdInfo calls SystemSetConfComputeKeyRotationThresholdInfoFunc. +func (mock *Interface) SystemSetConfComputeKeyRotationThresholdInfo(confComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo) nvml.Return { + if mock.SystemSetConfComputeKeyRotationThresholdInfoFunc == nil { + panic("Interface.SystemSetConfComputeKeyRotationThresholdInfoFunc: method is nil but Interface.SystemSetConfComputeKeyRotationThresholdInfo was just called") + } + callInfo := struct { + ConfComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo + }{ + ConfComputeSetKeyRotationThresholdInfo: confComputeSetKeyRotationThresholdInfo, + } + mock.lockSystemSetConfComputeKeyRotationThresholdInfo.Lock() + mock.calls.SystemSetConfComputeKeyRotationThresholdInfo = append(mock.calls.SystemSetConfComputeKeyRotationThresholdInfo, callInfo) + mock.lockSystemSetConfComputeKeyRotationThresholdInfo.Unlock() + return mock.SystemSetConfComputeKeyRotationThresholdInfoFunc(confComputeSetKeyRotationThresholdInfo) +} + +// SystemSetConfComputeKeyRotationThresholdInfoCalls gets all the calls that were made to SystemSetConfComputeKeyRotationThresholdInfo. +// Check the length with: +// +// len(mockedInterface.SystemSetConfComputeKeyRotationThresholdInfoCalls()) +func (mock *Interface) SystemSetConfComputeKeyRotationThresholdInfoCalls() []struct { + ConfComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo +} { + var calls []struct { + ConfComputeSetKeyRotationThresholdInfo nvml.ConfComputeSetKeyRotationThresholdInfo + } + mock.lockSystemSetConfComputeKeyRotationThresholdInfo.RLock() + calls = mock.calls.SystemSetConfComputeKeyRotationThresholdInfo + mock.lockSystemSetConfComputeKeyRotationThresholdInfo.RUnlock() + return calls +} + +// SystemSetNvlinkBwMode calls SystemSetNvlinkBwModeFunc. +func (mock *Interface) SystemSetNvlinkBwMode(v uint32) nvml.Return { + if mock.SystemSetNvlinkBwModeFunc == nil { + panic("Interface.SystemSetNvlinkBwModeFunc: method is nil but Interface.SystemSetNvlinkBwMode was just called") + } + callInfo := struct { + V uint32 + }{ + V: v, + } + mock.lockSystemSetNvlinkBwMode.Lock() + mock.calls.SystemSetNvlinkBwMode = append(mock.calls.SystemSetNvlinkBwMode, callInfo) + mock.lockSystemSetNvlinkBwMode.Unlock() + return mock.SystemSetNvlinkBwModeFunc(v) +} + +// SystemSetNvlinkBwModeCalls gets all the calls that were made to SystemSetNvlinkBwMode. +// Check the length with: +// +// len(mockedInterface.SystemSetNvlinkBwModeCalls()) +func (mock *Interface) SystemSetNvlinkBwModeCalls() []struct { + V uint32 +} { + var calls []struct { + V uint32 + } + mock.lockSystemSetNvlinkBwMode.RLock() + calls = mock.calls.SystemSetNvlinkBwMode + mock.lockSystemSetNvlinkBwMode.RUnlock() + return calls +} + +// UnitGetCount calls UnitGetCountFunc. +func (mock *Interface) UnitGetCount() (int, nvml.Return) { + if mock.UnitGetCountFunc == nil { + panic("Interface.UnitGetCountFunc: method is nil but Interface.UnitGetCount was just called") + } + callInfo := struct { + }{} + mock.lockUnitGetCount.Lock() + mock.calls.UnitGetCount = append(mock.calls.UnitGetCount, callInfo) + mock.lockUnitGetCount.Unlock() + return mock.UnitGetCountFunc() +} + +// UnitGetCountCalls gets all the calls that were made to UnitGetCount. +// Check the length with: +// +// len(mockedInterface.UnitGetCountCalls()) +func (mock *Interface) UnitGetCountCalls() []struct { +} { + var calls []struct { + } + mock.lockUnitGetCount.RLock() + calls = mock.calls.UnitGetCount + mock.lockUnitGetCount.RUnlock() + return calls +} + +// UnitGetDevices calls UnitGetDevicesFunc. +func (mock *Interface) UnitGetDevices(unit nvml.Unit) ([]nvml.Device, nvml.Return) { + if mock.UnitGetDevicesFunc == nil { + panic("Interface.UnitGetDevicesFunc: method is nil but Interface.UnitGetDevices was just called") + } + callInfo := struct { + Unit nvml.Unit + }{ + Unit: unit, + } + mock.lockUnitGetDevices.Lock() + mock.calls.UnitGetDevices = append(mock.calls.UnitGetDevices, callInfo) + mock.lockUnitGetDevices.Unlock() + return mock.UnitGetDevicesFunc(unit) +} + +// UnitGetDevicesCalls gets all the calls that were made to UnitGetDevices. +// Check the length with: +// +// len(mockedInterface.UnitGetDevicesCalls()) +func (mock *Interface) UnitGetDevicesCalls() []struct { + Unit nvml.Unit +} { + var calls []struct { + Unit nvml.Unit + } + mock.lockUnitGetDevices.RLock() + calls = mock.calls.UnitGetDevices + mock.lockUnitGetDevices.RUnlock() + return calls +} + +// UnitGetFanSpeedInfo calls UnitGetFanSpeedInfoFunc. +func (mock *Interface) UnitGetFanSpeedInfo(unit nvml.Unit) (nvml.UnitFanSpeeds, nvml.Return) { + if mock.UnitGetFanSpeedInfoFunc == nil { + panic("Interface.UnitGetFanSpeedInfoFunc: method is nil but Interface.UnitGetFanSpeedInfo was just called") + } + callInfo := struct { + Unit nvml.Unit + }{ + Unit: unit, + } + mock.lockUnitGetFanSpeedInfo.Lock() + mock.calls.UnitGetFanSpeedInfo = append(mock.calls.UnitGetFanSpeedInfo, callInfo) + mock.lockUnitGetFanSpeedInfo.Unlock() + return mock.UnitGetFanSpeedInfoFunc(unit) +} + +// UnitGetFanSpeedInfoCalls gets all the calls that were made to UnitGetFanSpeedInfo. +// Check the length with: +// +// len(mockedInterface.UnitGetFanSpeedInfoCalls()) +func (mock *Interface) UnitGetFanSpeedInfoCalls() []struct { + Unit nvml.Unit +} { + var calls []struct { + Unit nvml.Unit + } + mock.lockUnitGetFanSpeedInfo.RLock() + calls = mock.calls.UnitGetFanSpeedInfo + mock.lockUnitGetFanSpeedInfo.RUnlock() + return calls +} + +// UnitGetHandleByIndex calls UnitGetHandleByIndexFunc. +func (mock *Interface) UnitGetHandleByIndex(n int) (nvml.Unit, nvml.Return) { + if mock.UnitGetHandleByIndexFunc == nil { + panic("Interface.UnitGetHandleByIndexFunc: method is nil but Interface.UnitGetHandleByIndex was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockUnitGetHandleByIndex.Lock() + mock.calls.UnitGetHandleByIndex = append(mock.calls.UnitGetHandleByIndex, callInfo) + mock.lockUnitGetHandleByIndex.Unlock() + return mock.UnitGetHandleByIndexFunc(n) +} + +// UnitGetHandleByIndexCalls gets all the calls that were made to UnitGetHandleByIndex. +// Check the length with: +// +// len(mockedInterface.UnitGetHandleByIndexCalls()) +func (mock *Interface) UnitGetHandleByIndexCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockUnitGetHandleByIndex.RLock() + calls = mock.calls.UnitGetHandleByIndex + mock.lockUnitGetHandleByIndex.RUnlock() + return calls +} + +// UnitGetLedState calls UnitGetLedStateFunc. +func (mock *Interface) UnitGetLedState(unit nvml.Unit) (nvml.LedState, nvml.Return) { + if mock.UnitGetLedStateFunc == nil { + panic("Interface.UnitGetLedStateFunc: method is nil but Interface.UnitGetLedState was just called") + } + callInfo := struct { + Unit nvml.Unit + }{ + Unit: unit, + } + mock.lockUnitGetLedState.Lock() + mock.calls.UnitGetLedState = append(mock.calls.UnitGetLedState, callInfo) + mock.lockUnitGetLedState.Unlock() + return mock.UnitGetLedStateFunc(unit) +} + +// UnitGetLedStateCalls gets all the calls that were made to UnitGetLedState. +// Check the length with: +// +// len(mockedInterface.UnitGetLedStateCalls()) +func (mock *Interface) UnitGetLedStateCalls() []struct { + Unit nvml.Unit +} { + var calls []struct { + Unit nvml.Unit + } + mock.lockUnitGetLedState.RLock() + calls = mock.calls.UnitGetLedState + mock.lockUnitGetLedState.RUnlock() + return calls +} + +// UnitGetPsuInfo calls UnitGetPsuInfoFunc. +func (mock *Interface) UnitGetPsuInfo(unit nvml.Unit) (nvml.PSUInfo, nvml.Return) { + if mock.UnitGetPsuInfoFunc == nil { + panic("Interface.UnitGetPsuInfoFunc: method is nil but Interface.UnitGetPsuInfo was just called") + } + callInfo := struct { + Unit nvml.Unit + }{ + Unit: unit, + } + mock.lockUnitGetPsuInfo.Lock() + mock.calls.UnitGetPsuInfo = append(mock.calls.UnitGetPsuInfo, callInfo) + mock.lockUnitGetPsuInfo.Unlock() + return mock.UnitGetPsuInfoFunc(unit) +} + +// UnitGetPsuInfoCalls gets all the calls that were made to UnitGetPsuInfo. +// Check the length with: +// +// len(mockedInterface.UnitGetPsuInfoCalls()) +func (mock *Interface) UnitGetPsuInfoCalls() []struct { + Unit nvml.Unit +} { + var calls []struct { + Unit nvml.Unit + } + mock.lockUnitGetPsuInfo.RLock() + calls = mock.calls.UnitGetPsuInfo + mock.lockUnitGetPsuInfo.RUnlock() + return calls +} + +// UnitGetTemperature calls UnitGetTemperatureFunc. +func (mock *Interface) UnitGetTemperature(unit nvml.Unit, n int) (uint32, nvml.Return) { + if mock.UnitGetTemperatureFunc == nil { + panic("Interface.UnitGetTemperatureFunc: method is nil but Interface.UnitGetTemperature was just called") + } + callInfo := struct { + Unit nvml.Unit + N int + }{ + Unit: unit, + N: n, + } + mock.lockUnitGetTemperature.Lock() + mock.calls.UnitGetTemperature = append(mock.calls.UnitGetTemperature, callInfo) + mock.lockUnitGetTemperature.Unlock() + return mock.UnitGetTemperatureFunc(unit, n) +} + +// UnitGetTemperatureCalls gets all the calls that were made to UnitGetTemperature. +// Check the length with: +// +// len(mockedInterface.UnitGetTemperatureCalls()) +func (mock *Interface) UnitGetTemperatureCalls() []struct { + Unit nvml.Unit + N int +} { + var calls []struct { + Unit nvml.Unit + N int + } + mock.lockUnitGetTemperature.RLock() + calls = mock.calls.UnitGetTemperature + mock.lockUnitGetTemperature.RUnlock() + return calls +} + +// UnitGetUnitInfo calls UnitGetUnitInfoFunc. +func (mock *Interface) UnitGetUnitInfo(unit nvml.Unit) (nvml.UnitInfo, nvml.Return) { + if mock.UnitGetUnitInfoFunc == nil { + panic("Interface.UnitGetUnitInfoFunc: method is nil but Interface.UnitGetUnitInfo was just called") + } + callInfo := struct { + Unit nvml.Unit + }{ + Unit: unit, + } + mock.lockUnitGetUnitInfo.Lock() + mock.calls.UnitGetUnitInfo = append(mock.calls.UnitGetUnitInfo, callInfo) + mock.lockUnitGetUnitInfo.Unlock() + return mock.UnitGetUnitInfoFunc(unit) +} + +// UnitGetUnitInfoCalls gets all the calls that were made to UnitGetUnitInfo. +// Check the length with: +// +// len(mockedInterface.UnitGetUnitInfoCalls()) +func (mock *Interface) UnitGetUnitInfoCalls() []struct { + Unit nvml.Unit +} { + var calls []struct { + Unit nvml.Unit + } + mock.lockUnitGetUnitInfo.RLock() + calls = mock.calls.UnitGetUnitInfo + mock.lockUnitGetUnitInfo.RUnlock() + return calls +} + +// UnitSetLedState calls UnitSetLedStateFunc. +func (mock *Interface) UnitSetLedState(unit nvml.Unit, ledColor nvml.LedColor) nvml.Return { + if mock.UnitSetLedStateFunc == nil { + panic("Interface.UnitSetLedStateFunc: method is nil but Interface.UnitSetLedState was just called") + } + callInfo := struct { + Unit nvml.Unit + LedColor nvml.LedColor + }{ + Unit: unit, + LedColor: ledColor, + } + mock.lockUnitSetLedState.Lock() + mock.calls.UnitSetLedState = append(mock.calls.UnitSetLedState, callInfo) + mock.lockUnitSetLedState.Unlock() + return mock.UnitSetLedStateFunc(unit, ledColor) +} + +// UnitSetLedStateCalls gets all the calls that were made to UnitSetLedState. +// Check the length with: +// +// len(mockedInterface.UnitSetLedStateCalls()) +func (mock *Interface) UnitSetLedStateCalls() []struct { + Unit nvml.Unit + LedColor nvml.LedColor +} { + var calls []struct { + Unit nvml.Unit + LedColor nvml.LedColor + } + mock.lockUnitSetLedState.RLock() + calls = mock.calls.UnitSetLedState + mock.lockUnitSetLedState.RUnlock() + return calls +} + +// VgpuInstanceClearAccountingPids calls VgpuInstanceClearAccountingPidsFunc. +func (mock *Interface) VgpuInstanceClearAccountingPids(vgpuInstance nvml.VgpuInstance) nvml.Return { + if mock.VgpuInstanceClearAccountingPidsFunc == nil { + panic("Interface.VgpuInstanceClearAccountingPidsFunc: method is nil but Interface.VgpuInstanceClearAccountingPids was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceClearAccountingPids.Lock() + mock.calls.VgpuInstanceClearAccountingPids = append(mock.calls.VgpuInstanceClearAccountingPids, callInfo) + mock.lockVgpuInstanceClearAccountingPids.Unlock() + return mock.VgpuInstanceClearAccountingPidsFunc(vgpuInstance) +} + +// VgpuInstanceClearAccountingPidsCalls gets all the calls that were made to VgpuInstanceClearAccountingPids. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceClearAccountingPidsCalls()) +func (mock *Interface) VgpuInstanceClearAccountingPidsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceClearAccountingPids.RLock() + calls = mock.calls.VgpuInstanceClearAccountingPids + mock.lockVgpuInstanceClearAccountingPids.RUnlock() + return calls +} + +// VgpuInstanceGetAccountingMode calls VgpuInstanceGetAccountingModeFunc. +func (mock *Interface) VgpuInstanceGetAccountingMode(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) { + if mock.VgpuInstanceGetAccountingModeFunc == nil { + panic("Interface.VgpuInstanceGetAccountingModeFunc: method is nil but Interface.VgpuInstanceGetAccountingMode was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetAccountingMode.Lock() + mock.calls.VgpuInstanceGetAccountingMode = append(mock.calls.VgpuInstanceGetAccountingMode, callInfo) + mock.lockVgpuInstanceGetAccountingMode.Unlock() + return mock.VgpuInstanceGetAccountingModeFunc(vgpuInstance) +} + +// VgpuInstanceGetAccountingModeCalls gets all the calls that were made to VgpuInstanceGetAccountingMode. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetAccountingModeCalls()) +func (mock *Interface) VgpuInstanceGetAccountingModeCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetAccountingMode.RLock() + calls = mock.calls.VgpuInstanceGetAccountingMode + mock.lockVgpuInstanceGetAccountingMode.RUnlock() + return calls +} + +// VgpuInstanceGetAccountingPids calls VgpuInstanceGetAccountingPidsFunc. +func (mock *Interface) VgpuInstanceGetAccountingPids(vgpuInstance nvml.VgpuInstance) ([]int, nvml.Return) { + if mock.VgpuInstanceGetAccountingPidsFunc == nil { + panic("Interface.VgpuInstanceGetAccountingPidsFunc: method is nil but Interface.VgpuInstanceGetAccountingPids was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetAccountingPids.Lock() + mock.calls.VgpuInstanceGetAccountingPids = append(mock.calls.VgpuInstanceGetAccountingPids, callInfo) + mock.lockVgpuInstanceGetAccountingPids.Unlock() + return mock.VgpuInstanceGetAccountingPidsFunc(vgpuInstance) +} + +// VgpuInstanceGetAccountingPidsCalls gets all the calls that were made to VgpuInstanceGetAccountingPids. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetAccountingPidsCalls()) +func (mock *Interface) VgpuInstanceGetAccountingPidsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetAccountingPids.RLock() + calls = mock.calls.VgpuInstanceGetAccountingPids + mock.lockVgpuInstanceGetAccountingPids.RUnlock() + return calls +} + +// VgpuInstanceGetAccountingStats calls VgpuInstanceGetAccountingStatsFunc. +func (mock *Interface) VgpuInstanceGetAccountingStats(vgpuInstance nvml.VgpuInstance, n int) (nvml.AccountingStats, nvml.Return) { + if mock.VgpuInstanceGetAccountingStatsFunc == nil { + panic("Interface.VgpuInstanceGetAccountingStatsFunc: method is nil but Interface.VgpuInstanceGetAccountingStats was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + N int + }{ + VgpuInstance: vgpuInstance, + N: n, + } + mock.lockVgpuInstanceGetAccountingStats.Lock() + mock.calls.VgpuInstanceGetAccountingStats = append(mock.calls.VgpuInstanceGetAccountingStats, callInfo) + mock.lockVgpuInstanceGetAccountingStats.Unlock() + return mock.VgpuInstanceGetAccountingStatsFunc(vgpuInstance, n) +} + +// VgpuInstanceGetAccountingStatsCalls gets all the calls that were made to VgpuInstanceGetAccountingStats. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetAccountingStatsCalls()) +func (mock *Interface) VgpuInstanceGetAccountingStatsCalls() []struct { + VgpuInstance nvml.VgpuInstance + N int +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + N int + } + mock.lockVgpuInstanceGetAccountingStats.RLock() + calls = mock.calls.VgpuInstanceGetAccountingStats + mock.lockVgpuInstanceGetAccountingStats.RUnlock() + return calls +} + +// VgpuInstanceGetEccMode calls VgpuInstanceGetEccModeFunc. +func (mock *Interface) VgpuInstanceGetEccMode(vgpuInstance nvml.VgpuInstance) (nvml.EnableState, nvml.Return) { + if mock.VgpuInstanceGetEccModeFunc == nil { + panic("Interface.VgpuInstanceGetEccModeFunc: method is nil but Interface.VgpuInstanceGetEccMode was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetEccMode.Lock() + mock.calls.VgpuInstanceGetEccMode = append(mock.calls.VgpuInstanceGetEccMode, callInfo) + mock.lockVgpuInstanceGetEccMode.Unlock() + return mock.VgpuInstanceGetEccModeFunc(vgpuInstance) +} + +// VgpuInstanceGetEccModeCalls gets all the calls that were made to VgpuInstanceGetEccMode. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetEccModeCalls()) +func (mock *Interface) VgpuInstanceGetEccModeCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetEccMode.RLock() + calls = mock.calls.VgpuInstanceGetEccMode + mock.lockVgpuInstanceGetEccMode.RUnlock() + return calls +} + +// VgpuInstanceGetEncoderCapacity calls VgpuInstanceGetEncoderCapacityFunc. +func (mock *Interface) VgpuInstanceGetEncoderCapacity(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { + if mock.VgpuInstanceGetEncoderCapacityFunc == nil { + panic("Interface.VgpuInstanceGetEncoderCapacityFunc: method is nil but Interface.VgpuInstanceGetEncoderCapacity was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetEncoderCapacity.Lock() + mock.calls.VgpuInstanceGetEncoderCapacity = append(mock.calls.VgpuInstanceGetEncoderCapacity, callInfo) + mock.lockVgpuInstanceGetEncoderCapacity.Unlock() + return mock.VgpuInstanceGetEncoderCapacityFunc(vgpuInstance) +} + +// VgpuInstanceGetEncoderCapacityCalls gets all the calls that were made to VgpuInstanceGetEncoderCapacity. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetEncoderCapacityCalls()) +func (mock *Interface) VgpuInstanceGetEncoderCapacityCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetEncoderCapacity.RLock() + calls = mock.calls.VgpuInstanceGetEncoderCapacity + mock.lockVgpuInstanceGetEncoderCapacity.RUnlock() + return calls +} + +// VgpuInstanceGetEncoderSessions calls VgpuInstanceGetEncoderSessionsFunc. +func (mock *Interface) VgpuInstanceGetEncoderSessions(vgpuInstance nvml.VgpuInstance) (int, nvml.EncoderSessionInfo, nvml.Return) { + if mock.VgpuInstanceGetEncoderSessionsFunc == nil { + panic("Interface.VgpuInstanceGetEncoderSessionsFunc: method is nil but Interface.VgpuInstanceGetEncoderSessions was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetEncoderSessions.Lock() + mock.calls.VgpuInstanceGetEncoderSessions = append(mock.calls.VgpuInstanceGetEncoderSessions, callInfo) + mock.lockVgpuInstanceGetEncoderSessions.Unlock() + return mock.VgpuInstanceGetEncoderSessionsFunc(vgpuInstance) +} + +// VgpuInstanceGetEncoderSessionsCalls gets all the calls that were made to VgpuInstanceGetEncoderSessions. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetEncoderSessionsCalls()) +func (mock *Interface) VgpuInstanceGetEncoderSessionsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetEncoderSessions.RLock() + calls = mock.calls.VgpuInstanceGetEncoderSessions + mock.lockVgpuInstanceGetEncoderSessions.RUnlock() + return calls +} + +// VgpuInstanceGetEncoderStats calls VgpuInstanceGetEncoderStatsFunc. +func (mock *Interface) VgpuInstanceGetEncoderStats(vgpuInstance nvml.VgpuInstance) (int, uint32, uint32, nvml.Return) { + if mock.VgpuInstanceGetEncoderStatsFunc == nil { + panic("Interface.VgpuInstanceGetEncoderStatsFunc: method is nil but Interface.VgpuInstanceGetEncoderStats was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetEncoderStats.Lock() + mock.calls.VgpuInstanceGetEncoderStats = append(mock.calls.VgpuInstanceGetEncoderStats, callInfo) + mock.lockVgpuInstanceGetEncoderStats.Unlock() + return mock.VgpuInstanceGetEncoderStatsFunc(vgpuInstance) +} + +// VgpuInstanceGetEncoderStatsCalls gets all the calls that were made to VgpuInstanceGetEncoderStats. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetEncoderStatsCalls()) +func (mock *Interface) VgpuInstanceGetEncoderStatsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetEncoderStats.RLock() + calls = mock.calls.VgpuInstanceGetEncoderStats + mock.lockVgpuInstanceGetEncoderStats.RUnlock() + return calls +} + +// VgpuInstanceGetFBCSessions calls VgpuInstanceGetFBCSessionsFunc. +func (mock *Interface) VgpuInstanceGetFBCSessions(vgpuInstance nvml.VgpuInstance) (int, nvml.FBCSessionInfo, nvml.Return) { + if mock.VgpuInstanceGetFBCSessionsFunc == nil { + panic("Interface.VgpuInstanceGetFBCSessionsFunc: method is nil but Interface.VgpuInstanceGetFBCSessions was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetFBCSessions.Lock() + mock.calls.VgpuInstanceGetFBCSessions = append(mock.calls.VgpuInstanceGetFBCSessions, callInfo) + mock.lockVgpuInstanceGetFBCSessions.Unlock() + return mock.VgpuInstanceGetFBCSessionsFunc(vgpuInstance) +} + +// VgpuInstanceGetFBCSessionsCalls gets all the calls that were made to VgpuInstanceGetFBCSessions. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetFBCSessionsCalls()) +func (mock *Interface) VgpuInstanceGetFBCSessionsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetFBCSessions.RLock() + calls = mock.calls.VgpuInstanceGetFBCSessions + mock.lockVgpuInstanceGetFBCSessions.RUnlock() + return calls +} + +// VgpuInstanceGetFBCStats calls VgpuInstanceGetFBCStatsFunc. +func (mock *Interface) VgpuInstanceGetFBCStats(vgpuInstance nvml.VgpuInstance) (nvml.FBCStats, nvml.Return) { + if mock.VgpuInstanceGetFBCStatsFunc == nil { + panic("Interface.VgpuInstanceGetFBCStatsFunc: method is nil but Interface.VgpuInstanceGetFBCStats was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetFBCStats.Lock() + mock.calls.VgpuInstanceGetFBCStats = append(mock.calls.VgpuInstanceGetFBCStats, callInfo) + mock.lockVgpuInstanceGetFBCStats.Unlock() + return mock.VgpuInstanceGetFBCStatsFunc(vgpuInstance) +} + +// VgpuInstanceGetFBCStatsCalls gets all the calls that were made to VgpuInstanceGetFBCStats. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetFBCStatsCalls()) +func (mock *Interface) VgpuInstanceGetFBCStatsCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetFBCStats.RLock() + calls = mock.calls.VgpuInstanceGetFBCStats + mock.lockVgpuInstanceGetFBCStats.RUnlock() + return calls +} + +// VgpuInstanceGetFbUsage calls VgpuInstanceGetFbUsageFunc. +func (mock *Interface) VgpuInstanceGetFbUsage(vgpuInstance nvml.VgpuInstance) (uint64, nvml.Return) { + if mock.VgpuInstanceGetFbUsageFunc == nil { + panic("Interface.VgpuInstanceGetFbUsageFunc: method is nil but Interface.VgpuInstanceGetFbUsage was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetFbUsage.Lock() + mock.calls.VgpuInstanceGetFbUsage = append(mock.calls.VgpuInstanceGetFbUsage, callInfo) + mock.lockVgpuInstanceGetFbUsage.Unlock() + return mock.VgpuInstanceGetFbUsageFunc(vgpuInstance) +} + +// VgpuInstanceGetFbUsageCalls gets all the calls that were made to VgpuInstanceGetFbUsage. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetFbUsageCalls()) +func (mock *Interface) VgpuInstanceGetFbUsageCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetFbUsage.RLock() + calls = mock.calls.VgpuInstanceGetFbUsage + mock.lockVgpuInstanceGetFbUsage.RUnlock() + return calls +} + +// VgpuInstanceGetFrameRateLimit calls VgpuInstanceGetFrameRateLimitFunc. +func (mock *Interface) VgpuInstanceGetFrameRateLimit(vgpuInstance nvml.VgpuInstance) (uint32, nvml.Return) { + if mock.VgpuInstanceGetFrameRateLimitFunc == nil { + panic("Interface.VgpuInstanceGetFrameRateLimitFunc: method is nil but Interface.VgpuInstanceGetFrameRateLimit was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetFrameRateLimit.Lock() + mock.calls.VgpuInstanceGetFrameRateLimit = append(mock.calls.VgpuInstanceGetFrameRateLimit, callInfo) + mock.lockVgpuInstanceGetFrameRateLimit.Unlock() + return mock.VgpuInstanceGetFrameRateLimitFunc(vgpuInstance) +} + +// VgpuInstanceGetFrameRateLimitCalls gets all the calls that were made to VgpuInstanceGetFrameRateLimit. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetFrameRateLimitCalls()) +func (mock *Interface) VgpuInstanceGetFrameRateLimitCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetFrameRateLimit.RLock() + calls = mock.calls.VgpuInstanceGetFrameRateLimit + mock.lockVgpuInstanceGetFrameRateLimit.RUnlock() + return calls +} + +// VgpuInstanceGetGpuInstanceId calls VgpuInstanceGetGpuInstanceIdFunc. +func (mock *Interface) VgpuInstanceGetGpuInstanceId(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { + if mock.VgpuInstanceGetGpuInstanceIdFunc == nil { + panic("Interface.VgpuInstanceGetGpuInstanceIdFunc: method is nil but Interface.VgpuInstanceGetGpuInstanceId was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetGpuInstanceId.Lock() + mock.calls.VgpuInstanceGetGpuInstanceId = append(mock.calls.VgpuInstanceGetGpuInstanceId, callInfo) + mock.lockVgpuInstanceGetGpuInstanceId.Unlock() + return mock.VgpuInstanceGetGpuInstanceIdFunc(vgpuInstance) +} + +// VgpuInstanceGetGpuInstanceIdCalls gets all the calls that were made to VgpuInstanceGetGpuInstanceId. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetGpuInstanceIdCalls()) +func (mock *Interface) VgpuInstanceGetGpuInstanceIdCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetGpuInstanceId.RLock() + calls = mock.calls.VgpuInstanceGetGpuInstanceId + mock.lockVgpuInstanceGetGpuInstanceId.RUnlock() + return calls +} + +// VgpuInstanceGetGpuPciId calls VgpuInstanceGetGpuPciIdFunc. +func (mock *Interface) VgpuInstanceGetGpuPciId(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { + if mock.VgpuInstanceGetGpuPciIdFunc == nil { + panic("Interface.VgpuInstanceGetGpuPciIdFunc: method is nil but Interface.VgpuInstanceGetGpuPciId was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetGpuPciId.Lock() + mock.calls.VgpuInstanceGetGpuPciId = append(mock.calls.VgpuInstanceGetGpuPciId, callInfo) + mock.lockVgpuInstanceGetGpuPciId.Unlock() + return mock.VgpuInstanceGetGpuPciIdFunc(vgpuInstance) +} + +// VgpuInstanceGetGpuPciIdCalls gets all the calls that were made to VgpuInstanceGetGpuPciId. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetGpuPciIdCalls()) +func (mock *Interface) VgpuInstanceGetGpuPciIdCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetGpuPciId.RLock() + calls = mock.calls.VgpuInstanceGetGpuPciId + mock.lockVgpuInstanceGetGpuPciId.RUnlock() + return calls +} + +// VgpuInstanceGetLicenseInfo calls VgpuInstanceGetLicenseInfoFunc. +func (mock *Interface) VgpuInstanceGetLicenseInfo(vgpuInstance nvml.VgpuInstance) (nvml.VgpuLicenseInfo, nvml.Return) { + if mock.VgpuInstanceGetLicenseInfoFunc == nil { + panic("Interface.VgpuInstanceGetLicenseInfoFunc: method is nil but Interface.VgpuInstanceGetLicenseInfo was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetLicenseInfo.Lock() + mock.calls.VgpuInstanceGetLicenseInfo = append(mock.calls.VgpuInstanceGetLicenseInfo, callInfo) + mock.lockVgpuInstanceGetLicenseInfo.Unlock() + return mock.VgpuInstanceGetLicenseInfoFunc(vgpuInstance) +} + +// VgpuInstanceGetLicenseInfoCalls gets all the calls that were made to VgpuInstanceGetLicenseInfo. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetLicenseInfoCalls()) +func (mock *Interface) VgpuInstanceGetLicenseInfoCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetLicenseInfo.RLock() + calls = mock.calls.VgpuInstanceGetLicenseInfo + mock.lockVgpuInstanceGetLicenseInfo.RUnlock() + return calls +} + +// VgpuInstanceGetLicenseStatus calls VgpuInstanceGetLicenseStatusFunc. +func (mock *Interface) VgpuInstanceGetLicenseStatus(vgpuInstance nvml.VgpuInstance) (int, nvml.Return) { + if mock.VgpuInstanceGetLicenseStatusFunc == nil { + panic("Interface.VgpuInstanceGetLicenseStatusFunc: method is nil but Interface.VgpuInstanceGetLicenseStatus was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetLicenseStatus.Lock() + mock.calls.VgpuInstanceGetLicenseStatus = append(mock.calls.VgpuInstanceGetLicenseStatus, callInfo) + mock.lockVgpuInstanceGetLicenseStatus.Unlock() + return mock.VgpuInstanceGetLicenseStatusFunc(vgpuInstance) +} + +// VgpuInstanceGetLicenseStatusCalls gets all the calls that were made to VgpuInstanceGetLicenseStatus. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetLicenseStatusCalls()) +func (mock *Interface) VgpuInstanceGetLicenseStatusCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetLicenseStatus.RLock() + calls = mock.calls.VgpuInstanceGetLicenseStatus + mock.lockVgpuInstanceGetLicenseStatus.RUnlock() + return calls +} + +// VgpuInstanceGetMdevUUID calls VgpuInstanceGetMdevUUIDFunc. +func (mock *Interface) VgpuInstanceGetMdevUUID(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { + if mock.VgpuInstanceGetMdevUUIDFunc == nil { + panic("Interface.VgpuInstanceGetMdevUUIDFunc: method is nil but Interface.VgpuInstanceGetMdevUUID was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetMdevUUID.Lock() + mock.calls.VgpuInstanceGetMdevUUID = append(mock.calls.VgpuInstanceGetMdevUUID, callInfo) + mock.lockVgpuInstanceGetMdevUUID.Unlock() + return mock.VgpuInstanceGetMdevUUIDFunc(vgpuInstance) +} + +// VgpuInstanceGetMdevUUIDCalls gets all the calls that were made to VgpuInstanceGetMdevUUID. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetMdevUUIDCalls()) +func (mock *Interface) VgpuInstanceGetMdevUUIDCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetMdevUUID.RLock() + calls = mock.calls.VgpuInstanceGetMdevUUID + mock.lockVgpuInstanceGetMdevUUID.RUnlock() + return calls +} + +// VgpuInstanceGetMetadata calls VgpuInstanceGetMetadataFunc. +func (mock *Interface) VgpuInstanceGetMetadata(vgpuInstance nvml.VgpuInstance) (nvml.VgpuMetadata, nvml.Return) { + if mock.VgpuInstanceGetMetadataFunc == nil { + panic("Interface.VgpuInstanceGetMetadataFunc: method is nil but Interface.VgpuInstanceGetMetadata was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetMetadata.Lock() + mock.calls.VgpuInstanceGetMetadata = append(mock.calls.VgpuInstanceGetMetadata, callInfo) + mock.lockVgpuInstanceGetMetadata.Unlock() + return mock.VgpuInstanceGetMetadataFunc(vgpuInstance) +} + +// VgpuInstanceGetMetadataCalls gets all the calls that were made to VgpuInstanceGetMetadata. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetMetadataCalls()) +func (mock *Interface) VgpuInstanceGetMetadataCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetMetadata.RLock() + calls = mock.calls.VgpuInstanceGetMetadata + mock.lockVgpuInstanceGetMetadata.RUnlock() + return calls +} + +// VgpuInstanceGetRuntimeStateSize calls VgpuInstanceGetRuntimeStateSizeFunc. +func (mock *Interface) VgpuInstanceGetRuntimeStateSize(vgpuInstance nvml.VgpuInstance) (nvml.VgpuRuntimeState, nvml.Return) { + if mock.VgpuInstanceGetRuntimeStateSizeFunc == nil { + panic("Interface.VgpuInstanceGetRuntimeStateSizeFunc: method is nil but Interface.VgpuInstanceGetRuntimeStateSize was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetRuntimeStateSize.Lock() + mock.calls.VgpuInstanceGetRuntimeStateSize = append(mock.calls.VgpuInstanceGetRuntimeStateSize, callInfo) + mock.lockVgpuInstanceGetRuntimeStateSize.Unlock() + return mock.VgpuInstanceGetRuntimeStateSizeFunc(vgpuInstance) +} + +// VgpuInstanceGetRuntimeStateSizeCalls gets all the calls that were made to VgpuInstanceGetRuntimeStateSize. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetRuntimeStateSizeCalls()) +func (mock *Interface) VgpuInstanceGetRuntimeStateSizeCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetRuntimeStateSize.RLock() + calls = mock.calls.VgpuInstanceGetRuntimeStateSize + mock.lockVgpuInstanceGetRuntimeStateSize.RUnlock() + return calls +} + +// VgpuInstanceGetType calls VgpuInstanceGetTypeFunc. +func (mock *Interface) VgpuInstanceGetType(vgpuInstance nvml.VgpuInstance) (nvml.VgpuTypeId, nvml.Return) { + if mock.VgpuInstanceGetTypeFunc == nil { + panic("Interface.VgpuInstanceGetTypeFunc: method is nil but Interface.VgpuInstanceGetType was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetType.Lock() + mock.calls.VgpuInstanceGetType = append(mock.calls.VgpuInstanceGetType, callInfo) + mock.lockVgpuInstanceGetType.Unlock() + return mock.VgpuInstanceGetTypeFunc(vgpuInstance) +} + +// VgpuInstanceGetTypeCalls gets all the calls that were made to VgpuInstanceGetType. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetTypeCalls()) +func (mock *Interface) VgpuInstanceGetTypeCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetType.RLock() + calls = mock.calls.VgpuInstanceGetType + mock.lockVgpuInstanceGetType.RUnlock() + return calls +} + +// VgpuInstanceGetUUID calls VgpuInstanceGetUUIDFunc. +func (mock *Interface) VgpuInstanceGetUUID(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { + if mock.VgpuInstanceGetUUIDFunc == nil { + panic("Interface.VgpuInstanceGetUUIDFunc: method is nil but Interface.VgpuInstanceGetUUID was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetUUID.Lock() + mock.calls.VgpuInstanceGetUUID = append(mock.calls.VgpuInstanceGetUUID, callInfo) + mock.lockVgpuInstanceGetUUID.Unlock() + return mock.VgpuInstanceGetUUIDFunc(vgpuInstance) +} + +// VgpuInstanceGetUUIDCalls gets all the calls that were made to VgpuInstanceGetUUID. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetUUIDCalls()) +func (mock *Interface) VgpuInstanceGetUUIDCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetUUID.RLock() + calls = mock.calls.VgpuInstanceGetUUID + mock.lockVgpuInstanceGetUUID.RUnlock() + return calls +} + +// VgpuInstanceGetVmDriverVersion calls VgpuInstanceGetVmDriverVersionFunc. +func (mock *Interface) VgpuInstanceGetVmDriverVersion(vgpuInstance nvml.VgpuInstance) (string, nvml.Return) { + if mock.VgpuInstanceGetVmDriverVersionFunc == nil { + panic("Interface.VgpuInstanceGetVmDriverVersionFunc: method is nil but Interface.VgpuInstanceGetVmDriverVersion was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetVmDriverVersion.Lock() + mock.calls.VgpuInstanceGetVmDriverVersion = append(mock.calls.VgpuInstanceGetVmDriverVersion, callInfo) + mock.lockVgpuInstanceGetVmDriverVersion.Unlock() + return mock.VgpuInstanceGetVmDriverVersionFunc(vgpuInstance) +} + +// VgpuInstanceGetVmDriverVersionCalls gets all the calls that were made to VgpuInstanceGetVmDriverVersion. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetVmDriverVersionCalls()) +func (mock *Interface) VgpuInstanceGetVmDriverVersionCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetVmDriverVersion.RLock() + calls = mock.calls.VgpuInstanceGetVmDriverVersion + mock.lockVgpuInstanceGetVmDriverVersion.RUnlock() + return calls +} + +// VgpuInstanceGetVmID calls VgpuInstanceGetVmIDFunc. +func (mock *Interface) VgpuInstanceGetVmID(vgpuInstance nvml.VgpuInstance) (string, nvml.VgpuVmIdType, nvml.Return) { + if mock.VgpuInstanceGetVmIDFunc == nil { + panic("Interface.VgpuInstanceGetVmIDFunc: method is nil but Interface.VgpuInstanceGetVmID was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + }{ + VgpuInstance: vgpuInstance, + } + mock.lockVgpuInstanceGetVmID.Lock() + mock.calls.VgpuInstanceGetVmID = append(mock.calls.VgpuInstanceGetVmID, callInfo) + mock.lockVgpuInstanceGetVmID.Unlock() + return mock.VgpuInstanceGetVmIDFunc(vgpuInstance) +} + +// VgpuInstanceGetVmIDCalls gets all the calls that were made to VgpuInstanceGetVmID. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceGetVmIDCalls()) +func (mock *Interface) VgpuInstanceGetVmIDCalls() []struct { + VgpuInstance nvml.VgpuInstance +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + } + mock.lockVgpuInstanceGetVmID.RLock() + calls = mock.calls.VgpuInstanceGetVmID + mock.lockVgpuInstanceGetVmID.RUnlock() + return calls +} + +// VgpuInstanceSetEncoderCapacity calls VgpuInstanceSetEncoderCapacityFunc. +func (mock *Interface) VgpuInstanceSetEncoderCapacity(vgpuInstance nvml.VgpuInstance, n int) nvml.Return { + if mock.VgpuInstanceSetEncoderCapacityFunc == nil { + panic("Interface.VgpuInstanceSetEncoderCapacityFunc: method is nil but Interface.VgpuInstanceSetEncoderCapacity was just called") + } + callInfo := struct { + VgpuInstance nvml.VgpuInstance + N int + }{ + VgpuInstance: vgpuInstance, + N: n, + } + mock.lockVgpuInstanceSetEncoderCapacity.Lock() + mock.calls.VgpuInstanceSetEncoderCapacity = append(mock.calls.VgpuInstanceSetEncoderCapacity, callInfo) + mock.lockVgpuInstanceSetEncoderCapacity.Unlock() + return mock.VgpuInstanceSetEncoderCapacityFunc(vgpuInstance, n) +} + +// VgpuInstanceSetEncoderCapacityCalls gets all the calls that were made to VgpuInstanceSetEncoderCapacity. +// Check the length with: +// +// len(mockedInterface.VgpuInstanceSetEncoderCapacityCalls()) +func (mock *Interface) VgpuInstanceSetEncoderCapacityCalls() []struct { + VgpuInstance nvml.VgpuInstance + N int +} { + var calls []struct { + VgpuInstance nvml.VgpuInstance + N int + } + mock.lockVgpuInstanceSetEncoderCapacity.RLock() + calls = mock.calls.VgpuInstanceSetEncoderCapacity + mock.lockVgpuInstanceSetEncoderCapacity.RUnlock() + return calls +} + +// VgpuTypeGetBAR1Info calls VgpuTypeGetBAR1InfoFunc. +func (mock *Interface) VgpuTypeGetBAR1Info(vgpuTypeId nvml.VgpuTypeId) (nvml.VgpuTypeBar1Info, nvml.Return) { + if mock.VgpuTypeGetBAR1InfoFunc == nil { + panic("Interface.VgpuTypeGetBAR1InfoFunc: method is nil but Interface.VgpuTypeGetBAR1Info was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetBAR1Info.Lock() + mock.calls.VgpuTypeGetBAR1Info = append(mock.calls.VgpuTypeGetBAR1Info, callInfo) + mock.lockVgpuTypeGetBAR1Info.Unlock() + return mock.VgpuTypeGetBAR1InfoFunc(vgpuTypeId) +} + +// VgpuTypeGetBAR1InfoCalls gets all the calls that were made to VgpuTypeGetBAR1Info. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetBAR1InfoCalls()) +func (mock *Interface) VgpuTypeGetBAR1InfoCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetBAR1Info.RLock() + calls = mock.calls.VgpuTypeGetBAR1Info + mock.lockVgpuTypeGetBAR1Info.RUnlock() + return calls +} + +// VgpuTypeGetCapabilities calls VgpuTypeGetCapabilitiesFunc. +func (mock *Interface) VgpuTypeGetCapabilities(vgpuTypeId nvml.VgpuTypeId, vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) { + if mock.VgpuTypeGetCapabilitiesFunc == nil { + panic("Interface.VgpuTypeGetCapabilitiesFunc: method is nil but Interface.VgpuTypeGetCapabilities was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + VgpuCapability nvml.VgpuCapability + }{ + VgpuTypeId: vgpuTypeId, + VgpuCapability: vgpuCapability, + } + mock.lockVgpuTypeGetCapabilities.Lock() + mock.calls.VgpuTypeGetCapabilities = append(mock.calls.VgpuTypeGetCapabilities, callInfo) + mock.lockVgpuTypeGetCapabilities.Unlock() + return mock.VgpuTypeGetCapabilitiesFunc(vgpuTypeId, vgpuCapability) +} + +// VgpuTypeGetCapabilitiesCalls gets all the calls that were made to VgpuTypeGetCapabilities. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetCapabilitiesCalls()) +func (mock *Interface) VgpuTypeGetCapabilitiesCalls() []struct { + VgpuTypeId nvml.VgpuTypeId + VgpuCapability nvml.VgpuCapability +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + VgpuCapability nvml.VgpuCapability + } + mock.lockVgpuTypeGetCapabilities.RLock() + calls = mock.calls.VgpuTypeGetCapabilities + mock.lockVgpuTypeGetCapabilities.RUnlock() + return calls +} + +// VgpuTypeGetClass calls VgpuTypeGetClassFunc. +func (mock *Interface) VgpuTypeGetClass(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { + if mock.VgpuTypeGetClassFunc == nil { + panic("Interface.VgpuTypeGetClassFunc: method is nil but Interface.VgpuTypeGetClass was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetClass.Lock() + mock.calls.VgpuTypeGetClass = append(mock.calls.VgpuTypeGetClass, callInfo) + mock.lockVgpuTypeGetClass.Unlock() + return mock.VgpuTypeGetClassFunc(vgpuTypeId) +} + +// VgpuTypeGetClassCalls gets all the calls that were made to VgpuTypeGetClass. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetClassCalls()) +func (mock *Interface) VgpuTypeGetClassCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetClass.RLock() + calls = mock.calls.VgpuTypeGetClass + mock.lockVgpuTypeGetClass.RUnlock() + return calls +} + +// VgpuTypeGetDeviceID calls VgpuTypeGetDeviceIDFunc. +func (mock *Interface) VgpuTypeGetDeviceID(vgpuTypeId nvml.VgpuTypeId) (uint64, uint64, nvml.Return) { + if mock.VgpuTypeGetDeviceIDFunc == nil { + panic("Interface.VgpuTypeGetDeviceIDFunc: method is nil but Interface.VgpuTypeGetDeviceID was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetDeviceID.Lock() + mock.calls.VgpuTypeGetDeviceID = append(mock.calls.VgpuTypeGetDeviceID, callInfo) + mock.lockVgpuTypeGetDeviceID.Unlock() + return mock.VgpuTypeGetDeviceIDFunc(vgpuTypeId) +} + +// VgpuTypeGetDeviceIDCalls gets all the calls that were made to VgpuTypeGetDeviceID. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetDeviceIDCalls()) +func (mock *Interface) VgpuTypeGetDeviceIDCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetDeviceID.RLock() + calls = mock.calls.VgpuTypeGetDeviceID + mock.lockVgpuTypeGetDeviceID.RUnlock() + return calls +} + +// VgpuTypeGetFrameRateLimit calls VgpuTypeGetFrameRateLimitFunc. +func (mock *Interface) VgpuTypeGetFrameRateLimit(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) { + if mock.VgpuTypeGetFrameRateLimitFunc == nil { + panic("Interface.VgpuTypeGetFrameRateLimitFunc: method is nil but Interface.VgpuTypeGetFrameRateLimit was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetFrameRateLimit.Lock() + mock.calls.VgpuTypeGetFrameRateLimit = append(mock.calls.VgpuTypeGetFrameRateLimit, callInfo) + mock.lockVgpuTypeGetFrameRateLimit.Unlock() + return mock.VgpuTypeGetFrameRateLimitFunc(vgpuTypeId) +} + +// VgpuTypeGetFrameRateLimitCalls gets all the calls that were made to VgpuTypeGetFrameRateLimit. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetFrameRateLimitCalls()) +func (mock *Interface) VgpuTypeGetFrameRateLimitCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetFrameRateLimit.RLock() + calls = mock.calls.VgpuTypeGetFrameRateLimit + mock.lockVgpuTypeGetFrameRateLimit.RUnlock() + return calls +} + +// VgpuTypeGetFramebufferSize calls VgpuTypeGetFramebufferSizeFunc. +func (mock *Interface) VgpuTypeGetFramebufferSize(vgpuTypeId nvml.VgpuTypeId) (uint64, nvml.Return) { + if mock.VgpuTypeGetFramebufferSizeFunc == nil { + panic("Interface.VgpuTypeGetFramebufferSizeFunc: method is nil but Interface.VgpuTypeGetFramebufferSize was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetFramebufferSize.Lock() + mock.calls.VgpuTypeGetFramebufferSize = append(mock.calls.VgpuTypeGetFramebufferSize, callInfo) + mock.lockVgpuTypeGetFramebufferSize.Unlock() + return mock.VgpuTypeGetFramebufferSizeFunc(vgpuTypeId) +} + +// VgpuTypeGetFramebufferSizeCalls gets all the calls that were made to VgpuTypeGetFramebufferSize. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetFramebufferSizeCalls()) +func (mock *Interface) VgpuTypeGetFramebufferSizeCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetFramebufferSize.RLock() + calls = mock.calls.VgpuTypeGetFramebufferSize + mock.lockVgpuTypeGetFramebufferSize.RUnlock() + return calls +} + +// VgpuTypeGetGpuInstanceProfileId calls VgpuTypeGetGpuInstanceProfileIdFunc. +func (mock *Interface) VgpuTypeGetGpuInstanceProfileId(vgpuTypeId nvml.VgpuTypeId) (uint32, nvml.Return) { + if mock.VgpuTypeGetGpuInstanceProfileIdFunc == nil { + panic("Interface.VgpuTypeGetGpuInstanceProfileIdFunc: method is nil but Interface.VgpuTypeGetGpuInstanceProfileId was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetGpuInstanceProfileId.Lock() + mock.calls.VgpuTypeGetGpuInstanceProfileId = append(mock.calls.VgpuTypeGetGpuInstanceProfileId, callInfo) + mock.lockVgpuTypeGetGpuInstanceProfileId.Unlock() + return mock.VgpuTypeGetGpuInstanceProfileIdFunc(vgpuTypeId) +} + +// VgpuTypeGetGpuInstanceProfileIdCalls gets all the calls that were made to VgpuTypeGetGpuInstanceProfileId. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetGpuInstanceProfileIdCalls()) +func (mock *Interface) VgpuTypeGetGpuInstanceProfileIdCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetGpuInstanceProfileId.RLock() + calls = mock.calls.VgpuTypeGetGpuInstanceProfileId + mock.lockVgpuTypeGetGpuInstanceProfileId.RUnlock() + return calls +} + +// VgpuTypeGetLicense calls VgpuTypeGetLicenseFunc. +func (mock *Interface) VgpuTypeGetLicense(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { + if mock.VgpuTypeGetLicenseFunc == nil { + panic("Interface.VgpuTypeGetLicenseFunc: method is nil but Interface.VgpuTypeGetLicense was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetLicense.Lock() + mock.calls.VgpuTypeGetLicense = append(mock.calls.VgpuTypeGetLicense, callInfo) + mock.lockVgpuTypeGetLicense.Unlock() + return mock.VgpuTypeGetLicenseFunc(vgpuTypeId) +} + +// VgpuTypeGetLicenseCalls gets all the calls that were made to VgpuTypeGetLicense. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetLicenseCalls()) +func (mock *Interface) VgpuTypeGetLicenseCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetLicense.RLock() + calls = mock.calls.VgpuTypeGetLicense + mock.lockVgpuTypeGetLicense.RUnlock() + return calls +} + +// VgpuTypeGetMaxInstances calls VgpuTypeGetMaxInstancesFunc. +func (mock *Interface) VgpuTypeGetMaxInstances(device nvml.Device, vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { + if mock.VgpuTypeGetMaxInstancesFunc == nil { + panic("Interface.VgpuTypeGetMaxInstancesFunc: method is nil but Interface.VgpuTypeGetMaxInstances was just called") + } + callInfo := struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + }{ + Device: device, + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetMaxInstances.Lock() + mock.calls.VgpuTypeGetMaxInstances = append(mock.calls.VgpuTypeGetMaxInstances, callInfo) + mock.lockVgpuTypeGetMaxInstances.Unlock() + return mock.VgpuTypeGetMaxInstancesFunc(device, vgpuTypeId) +} + +// VgpuTypeGetMaxInstancesCalls gets all the calls that were made to VgpuTypeGetMaxInstances. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetMaxInstancesCalls()) +func (mock *Interface) VgpuTypeGetMaxInstancesCalls() []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + Device nvml.Device + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetMaxInstances.RLock() + calls = mock.calls.VgpuTypeGetMaxInstances + mock.lockVgpuTypeGetMaxInstances.RUnlock() + return calls +} + +// VgpuTypeGetMaxInstancesPerGpuInstance calls VgpuTypeGetMaxInstancesPerGpuInstanceFunc. +func (mock *Interface) VgpuTypeGetMaxInstancesPerGpuInstance(vgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance) nvml.Return { + if mock.VgpuTypeGetMaxInstancesPerGpuInstanceFunc == nil { + panic("Interface.VgpuTypeGetMaxInstancesPerGpuInstanceFunc: method is nil but Interface.VgpuTypeGetMaxInstancesPerGpuInstance was just called") + } + callInfo := struct { + VgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance + }{ + VgpuTypeMaxInstance: vgpuTypeMaxInstance, + } + mock.lockVgpuTypeGetMaxInstancesPerGpuInstance.Lock() + mock.calls.VgpuTypeGetMaxInstancesPerGpuInstance = append(mock.calls.VgpuTypeGetMaxInstancesPerGpuInstance, callInfo) + mock.lockVgpuTypeGetMaxInstancesPerGpuInstance.Unlock() + return mock.VgpuTypeGetMaxInstancesPerGpuInstanceFunc(vgpuTypeMaxInstance) +} + +// VgpuTypeGetMaxInstancesPerGpuInstanceCalls gets all the calls that were made to VgpuTypeGetMaxInstancesPerGpuInstance. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetMaxInstancesPerGpuInstanceCalls()) +func (mock *Interface) VgpuTypeGetMaxInstancesPerGpuInstanceCalls() []struct { + VgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance +} { + var calls []struct { + VgpuTypeMaxInstance *nvml.VgpuTypeMaxInstance + } + mock.lockVgpuTypeGetMaxInstancesPerGpuInstance.RLock() + calls = mock.calls.VgpuTypeGetMaxInstancesPerGpuInstance + mock.lockVgpuTypeGetMaxInstancesPerGpuInstance.RUnlock() + return calls +} + +// VgpuTypeGetMaxInstancesPerVm calls VgpuTypeGetMaxInstancesPerVmFunc. +func (mock *Interface) VgpuTypeGetMaxInstancesPerVm(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { + if mock.VgpuTypeGetMaxInstancesPerVmFunc == nil { + panic("Interface.VgpuTypeGetMaxInstancesPerVmFunc: method is nil but Interface.VgpuTypeGetMaxInstancesPerVm was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetMaxInstancesPerVm.Lock() + mock.calls.VgpuTypeGetMaxInstancesPerVm = append(mock.calls.VgpuTypeGetMaxInstancesPerVm, callInfo) + mock.lockVgpuTypeGetMaxInstancesPerVm.Unlock() + return mock.VgpuTypeGetMaxInstancesPerVmFunc(vgpuTypeId) +} + +// VgpuTypeGetMaxInstancesPerVmCalls gets all the calls that were made to VgpuTypeGetMaxInstancesPerVm. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetMaxInstancesPerVmCalls()) +func (mock *Interface) VgpuTypeGetMaxInstancesPerVmCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetMaxInstancesPerVm.RLock() + calls = mock.calls.VgpuTypeGetMaxInstancesPerVm + mock.lockVgpuTypeGetMaxInstancesPerVm.RUnlock() + return calls +} + +// VgpuTypeGetName calls VgpuTypeGetNameFunc. +func (mock *Interface) VgpuTypeGetName(vgpuTypeId nvml.VgpuTypeId) (string, nvml.Return) { + if mock.VgpuTypeGetNameFunc == nil { + panic("Interface.VgpuTypeGetNameFunc: method is nil but Interface.VgpuTypeGetName was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetName.Lock() + mock.calls.VgpuTypeGetName = append(mock.calls.VgpuTypeGetName, callInfo) + mock.lockVgpuTypeGetName.Unlock() + return mock.VgpuTypeGetNameFunc(vgpuTypeId) +} + +// VgpuTypeGetNameCalls gets all the calls that were made to VgpuTypeGetName. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetNameCalls()) +func (mock *Interface) VgpuTypeGetNameCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetName.RLock() + calls = mock.calls.VgpuTypeGetName + mock.lockVgpuTypeGetName.RUnlock() + return calls +} + +// VgpuTypeGetNumDisplayHeads calls VgpuTypeGetNumDisplayHeadsFunc. +func (mock *Interface) VgpuTypeGetNumDisplayHeads(vgpuTypeId nvml.VgpuTypeId) (int, nvml.Return) { + if mock.VgpuTypeGetNumDisplayHeadsFunc == nil { + panic("Interface.VgpuTypeGetNumDisplayHeadsFunc: method is nil but Interface.VgpuTypeGetNumDisplayHeads was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + }{ + VgpuTypeId: vgpuTypeId, + } + mock.lockVgpuTypeGetNumDisplayHeads.Lock() + mock.calls.VgpuTypeGetNumDisplayHeads = append(mock.calls.VgpuTypeGetNumDisplayHeads, callInfo) + mock.lockVgpuTypeGetNumDisplayHeads.Unlock() + return mock.VgpuTypeGetNumDisplayHeadsFunc(vgpuTypeId) +} + +// VgpuTypeGetNumDisplayHeadsCalls gets all the calls that were made to VgpuTypeGetNumDisplayHeads. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetNumDisplayHeadsCalls()) +func (mock *Interface) VgpuTypeGetNumDisplayHeadsCalls() []struct { + VgpuTypeId nvml.VgpuTypeId +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + } + mock.lockVgpuTypeGetNumDisplayHeads.RLock() + calls = mock.calls.VgpuTypeGetNumDisplayHeads + mock.lockVgpuTypeGetNumDisplayHeads.RUnlock() + return calls +} + +// VgpuTypeGetResolution calls VgpuTypeGetResolutionFunc. +func (mock *Interface) VgpuTypeGetResolution(vgpuTypeId nvml.VgpuTypeId, n int) (uint32, uint32, nvml.Return) { + if mock.VgpuTypeGetResolutionFunc == nil { + panic("Interface.VgpuTypeGetResolutionFunc: method is nil but Interface.VgpuTypeGetResolution was just called") + } + callInfo := struct { + VgpuTypeId nvml.VgpuTypeId + N int + }{ + VgpuTypeId: vgpuTypeId, + N: n, + } + mock.lockVgpuTypeGetResolution.Lock() + mock.calls.VgpuTypeGetResolution = append(mock.calls.VgpuTypeGetResolution, callInfo) + mock.lockVgpuTypeGetResolution.Unlock() + return mock.VgpuTypeGetResolutionFunc(vgpuTypeId, n) +} + +// VgpuTypeGetResolutionCalls gets all the calls that were made to VgpuTypeGetResolution. +// Check the length with: +// +// len(mockedInterface.VgpuTypeGetResolutionCalls()) +func (mock *Interface) VgpuTypeGetResolutionCalls() []struct { + VgpuTypeId nvml.VgpuTypeId + N int +} { + var calls []struct { + VgpuTypeId nvml.VgpuTypeId + N int + } + mock.lockVgpuTypeGetResolution.RLock() + calls = mock.calls.VgpuTypeGetResolution + mock.lockVgpuTypeGetResolution.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/unit.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/unit.go new file mode 100644 index 00000000..64af542f --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/unit.go @@ -0,0 +1,304 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that Unit does implement nvml.Unit. +// If this is not the case, regenerate this file with moq. +var _ nvml.Unit = &Unit{} + +// Unit is a mock implementation of nvml.Unit. +// +// func TestSomethingThatUsesUnit(t *testing.T) { +// +// // make and configure a mocked nvml.Unit +// mockedUnit := &Unit{ +// GetDevicesFunc: func() ([]nvml.Device, nvml.Return) { +// panic("mock out the GetDevices method") +// }, +// GetFanSpeedInfoFunc: func() (nvml.UnitFanSpeeds, nvml.Return) { +// panic("mock out the GetFanSpeedInfo method") +// }, +// GetLedStateFunc: func() (nvml.LedState, nvml.Return) { +// panic("mock out the GetLedState method") +// }, +// GetPsuInfoFunc: func() (nvml.PSUInfo, nvml.Return) { +// panic("mock out the GetPsuInfo method") +// }, +// GetTemperatureFunc: func(n int) (uint32, nvml.Return) { +// panic("mock out the GetTemperature method") +// }, +// GetUnitInfoFunc: func() (nvml.UnitInfo, nvml.Return) { +// panic("mock out the GetUnitInfo method") +// }, +// SetLedStateFunc: func(ledColor nvml.LedColor) nvml.Return { +// panic("mock out the SetLedState method") +// }, +// } +// +// // use mockedUnit in code that requires nvml.Unit +// // and then make assertions. +// +// } +type Unit struct { + // GetDevicesFunc mocks the GetDevices method. + GetDevicesFunc func() ([]nvml.Device, nvml.Return) + + // GetFanSpeedInfoFunc mocks the GetFanSpeedInfo method. + GetFanSpeedInfoFunc func() (nvml.UnitFanSpeeds, nvml.Return) + + // GetLedStateFunc mocks the GetLedState method. + GetLedStateFunc func() (nvml.LedState, nvml.Return) + + // GetPsuInfoFunc mocks the GetPsuInfo method. + GetPsuInfoFunc func() (nvml.PSUInfo, nvml.Return) + + // GetTemperatureFunc mocks the GetTemperature method. + GetTemperatureFunc func(n int) (uint32, nvml.Return) + + // GetUnitInfoFunc mocks the GetUnitInfo method. + GetUnitInfoFunc func() (nvml.UnitInfo, nvml.Return) + + // SetLedStateFunc mocks the SetLedState method. + SetLedStateFunc func(ledColor nvml.LedColor) nvml.Return + + // calls tracks calls to the methods. + calls struct { + // GetDevices holds details about calls to the GetDevices method. + GetDevices []struct { + } + // GetFanSpeedInfo holds details about calls to the GetFanSpeedInfo method. + GetFanSpeedInfo []struct { + } + // GetLedState holds details about calls to the GetLedState method. + GetLedState []struct { + } + // GetPsuInfo holds details about calls to the GetPsuInfo method. + GetPsuInfo []struct { + } + // GetTemperature holds details about calls to the GetTemperature method. + GetTemperature []struct { + // N is the n argument value. + N int + } + // GetUnitInfo holds details about calls to the GetUnitInfo method. + GetUnitInfo []struct { + } + // SetLedState holds details about calls to the SetLedState method. + SetLedState []struct { + // LedColor is the ledColor argument value. + LedColor nvml.LedColor + } + } + lockGetDevices sync.RWMutex + lockGetFanSpeedInfo sync.RWMutex + lockGetLedState sync.RWMutex + lockGetPsuInfo sync.RWMutex + lockGetTemperature sync.RWMutex + lockGetUnitInfo sync.RWMutex + lockSetLedState sync.RWMutex +} + +// GetDevices calls GetDevicesFunc. +func (mock *Unit) GetDevices() ([]nvml.Device, nvml.Return) { + if mock.GetDevicesFunc == nil { + panic("Unit.GetDevicesFunc: method is nil but Unit.GetDevices was just called") + } + callInfo := struct { + }{} + mock.lockGetDevices.Lock() + mock.calls.GetDevices = append(mock.calls.GetDevices, callInfo) + mock.lockGetDevices.Unlock() + return mock.GetDevicesFunc() +} + +// GetDevicesCalls gets all the calls that were made to GetDevices. +// Check the length with: +// +// len(mockedUnit.GetDevicesCalls()) +func (mock *Unit) GetDevicesCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDevices.RLock() + calls = mock.calls.GetDevices + mock.lockGetDevices.RUnlock() + return calls +} + +// GetFanSpeedInfo calls GetFanSpeedInfoFunc. +func (mock *Unit) GetFanSpeedInfo() (nvml.UnitFanSpeeds, nvml.Return) { + if mock.GetFanSpeedInfoFunc == nil { + panic("Unit.GetFanSpeedInfoFunc: method is nil but Unit.GetFanSpeedInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetFanSpeedInfo.Lock() + mock.calls.GetFanSpeedInfo = append(mock.calls.GetFanSpeedInfo, callInfo) + mock.lockGetFanSpeedInfo.Unlock() + return mock.GetFanSpeedInfoFunc() +} + +// GetFanSpeedInfoCalls gets all the calls that were made to GetFanSpeedInfo. +// Check the length with: +// +// len(mockedUnit.GetFanSpeedInfoCalls()) +func (mock *Unit) GetFanSpeedInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFanSpeedInfo.RLock() + calls = mock.calls.GetFanSpeedInfo + mock.lockGetFanSpeedInfo.RUnlock() + return calls +} + +// GetLedState calls GetLedStateFunc. +func (mock *Unit) GetLedState() (nvml.LedState, nvml.Return) { + if mock.GetLedStateFunc == nil { + panic("Unit.GetLedStateFunc: method is nil but Unit.GetLedState was just called") + } + callInfo := struct { + }{} + mock.lockGetLedState.Lock() + mock.calls.GetLedState = append(mock.calls.GetLedState, callInfo) + mock.lockGetLedState.Unlock() + return mock.GetLedStateFunc() +} + +// GetLedStateCalls gets all the calls that were made to GetLedState. +// Check the length with: +// +// len(mockedUnit.GetLedStateCalls()) +func (mock *Unit) GetLedStateCalls() []struct { +} { + var calls []struct { + } + mock.lockGetLedState.RLock() + calls = mock.calls.GetLedState + mock.lockGetLedState.RUnlock() + return calls +} + +// GetPsuInfo calls GetPsuInfoFunc. +func (mock *Unit) GetPsuInfo() (nvml.PSUInfo, nvml.Return) { + if mock.GetPsuInfoFunc == nil { + panic("Unit.GetPsuInfoFunc: method is nil but Unit.GetPsuInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetPsuInfo.Lock() + mock.calls.GetPsuInfo = append(mock.calls.GetPsuInfo, callInfo) + mock.lockGetPsuInfo.Unlock() + return mock.GetPsuInfoFunc() +} + +// GetPsuInfoCalls gets all the calls that were made to GetPsuInfo. +// Check the length with: +// +// len(mockedUnit.GetPsuInfoCalls()) +func (mock *Unit) GetPsuInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetPsuInfo.RLock() + calls = mock.calls.GetPsuInfo + mock.lockGetPsuInfo.RUnlock() + return calls +} + +// GetTemperature calls GetTemperatureFunc. +func (mock *Unit) GetTemperature(n int) (uint32, nvml.Return) { + if mock.GetTemperatureFunc == nil { + panic("Unit.GetTemperatureFunc: method is nil but Unit.GetTemperature was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetTemperature.Lock() + mock.calls.GetTemperature = append(mock.calls.GetTemperature, callInfo) + mock.lockGetTemperature.Unlock() + return mock.GetTemperatureFunc(n) +} + +// GetTemperatureCalls gets all the calls that were made to GetTemperature. +// Check the length with: +// +// len(mockedUnit.GetTemperatureCalls()) +func (mock *Unit) GetTemperatureCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetTemperature.RLock() + calls = mock.calls.GetTemperature + mock.lockGetTemperature.RUnlock() + return calls +} + +// GetUnitInfo calls GetUnitInfoFunc. +func (mock *Unit) GetUnitInfo() (nvml.UnitInfo, nvml.Return) { + if mock.GetUnitInfoFunc == nil { + panic("Unit.GetUnitInfoFunc: method is nil but Unit.GetUnitInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetUnitInfo.Lock() + mock.calls.GetUnitInfo = append(mock.calls.GetUnitInfo, callInfo) + mock.lockGetUnitInfo.Unlock() + return mock.GetUnitInfoFunc() +} + +// GetUnitInfoCalls gets all the calls that were made to GetUnitInfo. +// Check the length with: +// +// len(mockedUnit.GetUnitInfoCalls()) +func (mock *Unit) GetUnitInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetUnitInfo.RLock() + calls = mock.calls.GetUnitInfo + mock.lockGetUnitInfo.RUnlock() + return calls +} + +// SetLedState calls SetLedStateFunc. +func (mock *Unit) SetLedState(ledColor nvml.LedColor) nvml.Return { + if mock.SetLedStateFunc == nil { + panic("Unit.SetLedStateFunc: method is nil but Unit.SetLedState was just called") + } + callInfo := struct { + LedColor nvml.LedColor + }{ + LedColor: ledColor, + } + mock.lockSetLedState.Lock() + mock.calls.SetLedState = append(mock.calls.SetLedState, callInfo) + mock.lockSetLedState.Unlock() + return mock.SetLedStateFunc(ledColor) +} + +// SetLedStateCalls gets all the calls that were made to SetLedState. +// Check the length with: +// +// len(mockedUnit.SetLedStateCalls()) +func (mock *Unit) SetLedStateCalls() []struct { + LedColor nvml.LedColor +} { + var calls []struct { + LedColor nvml.LedColor + } + mock.lockSetLedState.RLock() + calls = mock.calls.SetLedState + mock.lockSetLedState.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgpuinstance.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgpuinstance.go new file mode 100644 index 00000000..828f4233 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgpuinstance.go @@ -0,0 +1,933 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that VgpuInstance does implement nvml.VgpuInstance. +// If this is not the case, regenerate this file with moq. +var _ nvml.VgpuInstance = &VgpuInstance{} + +// VgpuInstance is a mock implementation of nvml.VgpuInstance. +// +// func TestSomethingThatUsesVgpuInstance(t *testing.T) { +// +// // make and configure a mocked nvml.VgpuInstance +// mockedVgpuInstance := &VgpuInstance{ +// ClearAccountingPidsFunc: func() nvml.Return { +// panic("mock out the ClearAccountingPids method") +// }, +// GetAccountingModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetAccountingMode method") +// }, +// GetAccountingPidsFunc: func() ([]int, nvml.Return) { +// panic("mock out the GetAccountingPids method") +// }, +// GetAccountingStatsFunc: func(n int) (nvml.AccountingStats, nvml.Return) { +// panic("mock out the GetAccountingStats method") +// }, +// GetEccModeFunc: func() (nvml.EnableState, nvml.Return) { +// panic("mock out the GetEccMode method") +// }, +// GetEncoderCapacityFunc: func() (int, nvml.Return) { +// panic("mock out the GetEncoderCapacity method") +// }, +// GetEncoderSessionsFunc: func() (int, nvml.EncoderSessionInfo, nvml.Return) { +// panic("mock out the GetEncoderSessions method") +// }, +// GetEncoderStatsFunc: func() (int, uint32, uint32, nvml.Return) { +// panic("mock out the GetEncoderStats method") +// }, +// GetFBCSessionsFunc: func() (int, nvml.FBCSessionInfo, nvml.Return) { +// panic("mock out the GetFBCSessions method") +// }, +// GetFBCStatsFunc: func() (nvml.FBCStats, nvml.Return) { +// panic("mock out the GetFBCStats method") +// }, +// GetFbUsageFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetFbUsage method") +// }, +// GetFrameRateLimitFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetFrameRateLimit method") +// }, +// GetGpuInstanceIdFunc: func() (int, nvml.Return) { +// panic("mock out the GetGpuInstanceId method") +// }, +// GetGpuPciIdFunc: func() (string, nvml.Return) { +// panic("mock out the GetGpuPciId method") +// }, +// GetLicenseInfoFunc: func() (nvml.VgpuLicenseInfo, nvml.Return) { +// panic("mock out the GetLicenseInfo method") +// }, +// GetLicenseStatusFunc: func() (int, nvml.Return) { +// panic("mock out the GetLicenseStatus method") +// }, +// GetMdevUUIDFunc: func() (string, nvml.Return) { +// panic("mock out the GetMdevUUID method") +// }, +// GetMetadataFunc: func() (nvml.VgpuMetadata, nvml.Return) { +// panic("mock out the GetMetadata method") +// }, +// GetRuntimeStateSizeFunc: func() (nvml.VgpuRuntimeState, nvml.Return) { +// panic("mock out the GetRuntimeStateSize method") +// }, +// GetTypeFunc: func() (nvml.VgpuTypeId, nvml.Return) { +// panic("mock out the GetType method") +// }, +// GetUUIDFunc: func() (string, nvml.Return) { +// panic("mock out the GetUUID method") +// }, +// GetVmDriverVersionFunc: func() (string, nvml.Return) { +// panic("mock out the GetVmDriverVersion method") +// }, +// GetVmIDFunc: func() (string, nvml.VgpuVmIdType, nvml.Return) { +// panic("mock out the GetVmID method") +// }, +// SetEncoderCapacityFunc: func(n int) nvml.Return { +// panic("mock out the SetEncoderCapacity method") +// }, +// } +// +// // use mockedVgpuInstance in code that requires nvml.VgpuInstance +// // and then make assertions. +// +// } +type VgpuInstance struct { + // ClearAccountingPidsFunc mocks the ClearAccountingPids method. + ClearAccountingPidsFunc func() nvml.Return + + // GetAccountingModeFunc mocks the GetAccountingMode method. + GetAccountingModeFunc func() (nvml.EnableState, nvml.Return) + + // GetAccountingPidsFunc mocks the GetAccountingPids method. + GetAccountingPidsFunc func() ([]int, nvml.Return) + + // GetAccountingStatsFunc mocks the GetAccountingStats method. + GetAccountingStatsFunc func(n int) (nvml.AccountingStats, nvml.Return) + + // GetEccModeFunc mocks the GetEccMode method. + GetEccModeFunc func() (nvml.EnableState, nvml.Return) + + // GetEncoderCapacityFunc mocks the GetEncoderCapacity method. + GetEncoderCapacityFunc func() (int, nvml.Return) + + // GetEncoderSessionsFunc mocks the GetEncoderSessions method. + GetEncoderSessionsFunc func() (int, nvml.EncoderSessionInfo, nvml.Return) + + // GetEncoderStatsFunc mocks the GetEncoderStats method. + GetEncoderStatsFunc func() (int, uint32, uint32, nvml.Return) + + // GetFBCSessionsFunc mocks the GetFBCSessions method. + GetFBCSessionsFunc func() (int, nvml.FBCSessionInfo, nvml.Return) + + // GetFBCStatsFunc mocks the GetFBCStats method. + GetFBCStatsFunc func() (nvml.FBCStats, nvml.Return) + + // GetFbUsageFunc mocks the GetFbUsage method. + GetFbUsageFunc func() (uint64, nvml.Return) + + // GetFrameRateLimitFunc mocks the GetFrameRateLimit method. + GetFrameRateLimitFunc func() (uint32, nvml.Return) + + // GetGpuInstanceIdFunc mocks the GetGpuInstanceId method. + GetGpuInstanceIdFunc func() (int, nvml.Return) + + // GetGpuPciIdFunc mocks the GetGpuPciId method. + GetGpuPciIdFunc func() (string, nvml.Return) + + // GetLicenseInfoFunc mocks the GetLicenseInfo method. + GetLicenseInfoFunc func() (nvml.VgpuLicenseInfo, nvml.Return) + + // GetLicenseStatusFunc mocks the GetLicenseStatus method. + GetLicenseStatusFunc func() (int, nvml.Return) + + // GetMdevUUIDFunc mocks the GetMdevUUID method. + GetMdevUUIDFunc func() (string, nvml.Return) + + // GetMetadataFunc mocks the GetMetadata method. + GetMetadataFunc func() (nvml.VgpuMetadata, nvml.Return) + + // GetRuntimeStateSizeFunc mocks the GetRuntimeStateSize method. + GetRuntimeStateSizeFunc func() (nvml.VgpuRuntimeState, nvml.Return) + + // GetTypeFunc mocks the GetType method. + GetTypeFunc func() (nvml.VgpuTypeId, nvml.Return) + + // GetUUIDFunc mocks the GetUUID method. + GetUUIDFunc func() (string, nvml.Return) + + // GetVmDriverVersionFunc mocks the GetVmDriverVersion method. + GetVmDriverVersionFunc func() (string, nvml.Return) + + // GetVmIDFunc mocks the GetVmID method. + GetVmIDFunc func() (string, nvml.VgpuVmIdType, nvml.Return) + + // SetEncoderCapacityFunc mocks the SetEncoderCapacity method. + SetEncoderCapacityFunc func(n int) nvml.Return + + // calls tracks calls to the methods. + calls struct { + // ClearAccountingPids holds details about calls to the ClearAccountingPids method. + ClearAccountingPids []struct { + } + // GetAccountingMode holds details about calls to the GetAccountingMode method. + GetAccountingMode []struct { + } + // GetAccountingPids holds details about calls to the GetAccountingPids method. + GetAccountingPids []struct { + } + // GetAccountingStats holds details about calls to the GetAccountingStats method. + GetAccountingStats []struct { + // N is the n argument value. + N int + } + // GetEccMode holds details about calls to the GetEccMode method. + GetEccMode []struct { + } + // GetEncoderCapacity holds details about calls to the GetEncoderCapacity method. + GetEncoderCapacity []struct { + } + // GetEncoderSessions holds details about calls to the GetEncoderSessions method. + GetEncoderSessions []struct { + } + // GetEncoderStats holds details about calls to the GetEncoderStats method. + GetEncoderStats []struct { + } + // GetFBCSessions holds details about calls to the GetFBCSessions method. + GetFBCSessions []struct { + } + // GetFBCStats holds details about calls to the GetFBCStats method. + GetFBCStats []struct { + } + // GetFbUsage holds details about calls to the GetFbUsage method. + GetFbUsage []struct { + } + // GetFrameRateLimit holds details about calls to the GetFrameRateLimit method. + GetFrameRateLimit []struct { + } + // GetGpuInstanceId holds details about calls to the GetGpuInstanceId method. + GetGpuInstanceId []struct { + } + // GetGpuPciId holds details about calls to the GetGpuPciId method. + GetGpuPciId []struct { + } + // GetLicenseInfo holds details about calls to the GetLicenseInfo method. + GetLicenseInfo []struct { + } + // GetLicenseStatus holds details about calls to the GetLicenseStatus method. + GetLicenseStatus []struct { + } + // GetMdevUUID holds details about calls to the GetMdevUUID method. + GetMdevUUID []struct { + } + // GetMetadata holds details about calls to the GetMetadata method. + GetMetadata []struct { + } + // GetRuntimeStateSize holds details about calls to the GetRuntimeStateSize method. + GetRuntimeStateSize []struct { + } + // GetType holds details about calls to the GetType method. + GetType []struct { + } + // GetUUID holds details about calls to the GetUUID method. + GetUUID []struct { + } + // GetVmDriverVersion holds details about calls to the GetVmDriverVersion method. + GetVmDriverVersion []struct { + } + // GetVmID holds details about calls to the GetVmID method. + GetVmID []struct { + } + // SetEncoderCapacity holds details about calls to the SetEncoderCapacity method. + SetEncoderCapacity []struct { + // N is the n argument value. + N int + } + } + lockClearAccountingPids sync.RWMutex + lockGetAccountingMode sync.RWMutex + lockGetAccountingPids sync.RWMutex + lockGetAccountingStats sync.RWMutex + lockGetEccMode sync.RWMutex + lockGetEncoderCapacity sync.RWMutex + lockGetEncoderSessions sync.RWMutex + lockGetEncoderStats sync.RWMutex + lockGetFBCSessions sync.RWMutex + lockGetFBCStats sync.RWMutex + lockGetFbUsage sync.RWMutex + lockGetFrameRateLimit sync.RWMutex + lockGetGpuInstanceId sync.RWMutex + lockGetGpuPciId sync.RWMutex + lockGetLicenseInfo sync.RWMutex + lockGetLicenseStatus sync.RWMutex + lockGetMdevUUID sync.RWMutex + lockGetMetadata sync.RWMutex + lockGetRuntimeStateSize sync.RWMutex + lockGetType sync.RWMutex + lockGetUUID sync.RWMutex + lockGetVmDriverVersion sync.RWMutex + lockGetVmID sync.RWMutex + lockSetEncoderCapacity sync.RWMutex +} + +// ClearAccountingPids calls ClearAccountingPidsFunc. +func (mock *VgpuInstance) ClearAccountingPids() nvml.Return { + if mock.ClearAccountingPidsFunc == nil { + panic("VgpuInstance.ClearAccountingPidsFunc: method is nil but VgpuInstance.ClearAccountingPids was just called") + } + callInfo := struct { + }{} + mock.lockClearAccountingPids.Lock() + mock.calls.ClearAccountingPids = append(mock.calls.ClearAccountingPids, callInfo) + mock.lockClearAccountingPids.Unlock() + return mock.ClearAccountingPidsFunc() +} + +// ClearAccountingPidsCalls gets all the calls that were made to ClearAccountingPids. +// Check the length with: +// +// len(mockedVgpuInstance.ClearAccountingPidsCalls()) +func (mock *VgpuInstance) ClearAccountingPidsCalls() []struct { +} { + var calls []struct { + } + mock.lockClearAccountingPids.RLock() + calls = mock.calls.ClearAccountingPids + mock.lockClearAccountingPids.RUnlock() + return calls +} + +// GetAccountingMode calls GetAccountingModeFunc. +func (mock *VgpuInstance) GetAccountingMode() (nvml.EnableState, nvml.Return) { + if mock.GetAccountingModeFunc == nil { + panic("VgpuInstance.GetAccountingModeFunc: method is nil but VgpuInstance.GetAccountingMode was just called") + } + callInfo := struct { + }{} + mock.lockGetAccountingMode.Lock() + mock.calls.GetAccountingMode = append(mock.calls.GetAccountingMode, callInfo) + mock.lockGetAccountingMode.Unlock() + return mock.GetAccountingModeFunc() +} + +// GetAccountingModeCalls gets all the calls that were made to GetAccountingMode. +// Check the length with: +// +// len(mockedVgpuInstance.GetAccountingModeCalls()) +func (mock *VgpuInstance) GetAccountingModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAccountingMode.RLock() + calls = mock.calls.GetAccountingMode + mock.lockGetAccountingMode.RUnlock() + return calls +} + +// GetAccountingPids calls GetAccountingPidsFunc. +func (mock *VgpuInstance) GetAccountingPids() ([]int, nvml.Return) { + if mock.GetAccountingPidsFunc == nil { + panic("VgpuInstance.GetAccountingPidsFunc: method is nil but VgpuInstance.GetAccountingPids was just called") + } + callInfo := struct { + }{} + mock.lockGetAccountingPids.Lock() + mock.calls.GetAccountingPids = append(mock.calls.GetAccountingPids, callInfo) + mock.lockGetAccountingPids.Unlock() + return mock.GetAccountingPidsFunc() +} + +// GetAccountingPidsCalls gets all the calls that were made to GetAccountingPids. +// Check the length with: +// +// len(mockedVgpuInstance.GetAccountingPidsCalls()) +func (mock *VgpuInstance) GetAccountingPidsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetAccountingPids.RLock() + calls = mock.calls.GetAccountingPids + mock.lockGetAccountingPids.RUnlock() + return calls +} + +// GetAccountingStats calls GetAccountingStatsFunc. +func (mock *VgpuInstance) GetAccountingStats(n int) (nvml.AccountingStats, nvml.Return) { + if mock.GetAccountingStatsFunc == nil { + panic("VgpuInstance.GetAccountingStatsFunc: method is nil but VgpuInstance.GetAccountingStats was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetAccountingStats.Lock() + mock.calls.GetAccountingStats = append(mock.calls.GetAccountingStats, callInfo) + mock.lockGetAccountingStats.Unlock() + return mock.GetAccountingStatsFunc(n) +} + +// GetAccountingStatsCalls gets all the calls that were made to GetAccountingStats. +// Check the length with: +// +// len(mockedVgpuInstance.GetAccountingStatsCalls()) +func (mock *VgpuInstance) GetAccountingStatsCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetAccountingStats.RLock() + calls = mock.calls.GetAccountingStats + mock.lockGetAccountingStats.RUnlock() + return calls +} + +// GetEccMode calls GetEccModeFunc. +func (mock *VgpuInstance) GetEccMode() (nvml.EnableState, nvml.Return) { + if mock.GetEccModeFunc == nil { + panic("VgpuInstance.GetEccModeFunc: method is nil but VgpuInstance.GetEccMode was just called") + } + callInfo := struct { + }{} + mock.lockGetEccMode.Lock() + mock.calls.GetEccMode = append(mock.calls.GetEccMode, callInfo) + mock.lockGetEccMode.Unlock() + return mock.GetEccModeFunc() +} + +// GetEccModeCalls gets all the calls that were made to GetEccMode. +// Check the length with: +// +// len(mockedVgpuInstance.GetEccModeCalls()) +func (mock *VgpuInstance) GetEccModeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEccMode.RLock() + calls = mock.calls.GetEccMode + mock.lockGetEccMode.RUnlock() + return calls +} + +// GetEncoderCapacity calls GetEncoderCapacityFunc. +func (mock *VgpuInstance) GetEncoderCapacity() (int, nvml.Return) { + if mock.GetEncoderCapacityFunc == nil { + panic("VgpuInstance.GetEncoderCapacityFunc: method is nil but VgpuInstance.GetEncoderCapacity was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderCapacity.Lock() + mock.calls.GetEncoderCapacity = append(mock.calls.GetEncoderCapacity, callInfo) + mock.lockGetEncoderCapacity.Unlock() + return mock.GetEncoderCapacityFunc() +} + +// GetEncoderCapacityCalls gets all the calls that were made to GetEncoderCapacity. +// Check the length with: +// +// len(mockedVgpuInstance.GetEncoderCapacityCalls()) +func (mock *VgpuInstance) GetEncoderCapacityCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderCapacity.RLock() + calls = mock.calls.GetEncoderCapacity + mock.lockGetEncoderCapacity.RUnlock() + return calls +} + +// GetEncoderSessions calls GetEncoderSessionsFunc. +func (mock *VgpuInstance) GetEncoderSessions() (int, nvml.EncoderSessionInfo, nvml.Return) { + if mock.GetEncoderSessionsFunc == nil { + panic("VgpuInstance.GetEncoderSessionsFunc: method is nil but VgpuInstance.GetEncoderSessions was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderSessions.Lock() + mock.calls.GetEncoderSessions = append(mock.calls.GetEncoderSessions, callInfo) + mock.lockGetEncoderSessions.Unlock() + return mock.GetEncoderSessionsFunc() +} + +// GetEncoderSessionsCalls gets all the calls that were made to GetEncoderSessions. +// Check the length with: +// +// len(mockedVgpuInstance.GetEncoderSessionsCalls()) +func (mock *VgpuInstance) GetEncoderSessionsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderSessions.RLock() + calls = mock.calls.GetEncoderSessions + mock.lockGetEncoderSessions.RUnlock() + return calls +} + +// GetEncoderStats calls GetEncoderStatsFunc. +func (mock *VgpuInstance) GetEncoderStats() (int, uint32, uint32, nvml.Return) { + if mock.GetEncoderStatsFunc == nil { + panic("VgpuInstance.GetEncoderStatsFunc: method is nil but VgpuInstance.GetEncoderStats was just called") + } + callInfo := struct { + }{} + mock.lockGetEncoderStats.Lock() + mock.calls.GetEncoderStats = append(mock.calls.GetEncoderStats, callInfo) + mock.lockGetEncoderStats.Unlock() + return mock.GetEncoderStatsFunc() +} + +// GetEncoderStatsCalls gets all the calls that were made to GetEncoderStats. +// Check the length with: +// +// len(mockedVgpuInstance.GetEncoderStatsCalls()) +func (mock *VgpuInstance) GetEncoderStatsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetEncoderStats.RLock() + calls = mock.calls.GetEncoderStats + mock.lockGetEncoderStats.RUnlock() + return calls +} + +// GetFBCSessions calls GetFBCSessionsFunc. +func (mock *VgpuInstance) GetFBCSessions() (int, nvml.FBCSessionInfo, nvml.Return) { + if mock.GetFBCSessionsFunc == nil { + panic("VgpuInstance.GetFBCSessionsFunc: method is nil but VgpuInstance.GetFBCSessions was just called") + } + callInfo := struct { + }{} + mock.lockGetFBCSessions.Lock() + mock.calls.GetFBCSessions = append(mock.calls.GetFBCSessions, callInfo) + mock.lockGetFBCSessions.Unlock() + return mock.GetFBCSessionsFunc() +} + +// GetFBCSessionsCalls gets all the calls that were made to GetFBCSessions. +// Check the length with: +// +// len(mockedVgpuInstance.GetFBCSessionsCalls()) +func (mock *VgpuInstance) GetFBCSessionsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFBCSessions.RLock() + calls = mock.calls.GetFBCSessions + mock.lockGetFBCSessions.RUnlock() + return calls +} + +// GetFBCStats calls GetFBCStatsFunc. +func (mock *VgpuInstance) GetFBCStats() (nvml.FBCStats, nvml.Return) { + if mock.GetFBCStatsFunc == nil { + panic("VgpuInstance.GetFBCStatsFunc: method is nil but VgpuInstance.GetFBCStats was just called") + } + callInfo := struct { + }{} + mock.lockGetFBCStats.Lock() + mock.calls.GetFBCStats = append(mock.calls.GetFBCStats, callInfo) + mock.lockGetFBCStats.Unlock() + return mock.GetFBCStatsFunc() +} + +// GetFBCStatsCalls gets all the calls that were made to GetFBCStats. +// Check the length with: +// +// len(mockedVgpuInstance.GetFBCStatsCalls()) +func (mock *VgpuInstance) GetFBCStatsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFBCStats.RLock() + calls = mock.calls.GetFBCStats + mock.lockGetFBCStats.RUnlock() + return calls +} + +// GetFbUsage calls GetFbUsageFunc. +func (mock *VgpuInstance) GetFbUsage() (uint64, nvml.Return) { + if mock.GetFbUsageFunc == nil { + panic("VgpuInstance.GetFbUsageFunc: method is nil but VgpuInstance.GetFbUsage was just called") + } + callInfo := struct { + }{} + mock.lockGetFbUsage.Lock() + mock.calls.GetFbUsage = append(mock.calls.GetFbUsage, callInfo) + mock.lockGetFbUsage.Unlock() + return mock.GetFbUsageFunc() +} + +// GetFbUsageCalls gets all the calls that were made to GetFbUsage. +// Check the length with: +// +// len(mockedVgpuInstance.GetFbUsageCalls()) +func (mock *VgpuInstance) GetFbUsageCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFbUsage.RLock() + calls = mock.calls.GetFbUsage + mock.lockGetFbUsage.RUnlock() + return calls +} + +// GetFrameRateLimit calls GetFrameRateLimitFunc. +func (mock *VgpuInstance) GetFrameRateLimit() (uint32, nvml.Return) { + if mock.GetFrameRateLimitFunc == nil { + panic("VgpuInstance.GetFrameRateLimitFunc: method is nil but VgpuInstance.GetFrameRateLimit was just called") + } + callInfo := struct { + }{} + mock.lockGetFrameRateLimit.Lock() + mock.calls.GetFrameRateLimit = append(mock.calls.GetFrameRateLimit, callInfo) + mock.lockGetFrameRateLimit.Unlock() + return mock.GetFrameRateLimitFunc() +} + +// GetFrameRateLimitCalls gets all the calls that were made to GetFrameRateLimit. +// Check the length with: +// +// len(mockedVgpuInstance.GetFrameRateLimitCalls()) +func (mock *VgpuInstance) GetFrameRateLimitCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFrameRateLimit.RLock() + calls = mock.calls.GetFrameRateLimit + mock.lockGetFrameRateLimit.RUnlock() + return calls +} + +// GetGpuInstanceId calls GetGpuInstanceIdFunc. +func (mock *VgpuInstance) GetGpuInstanceId() (int, nvml.Return) { + if mock.GetGpuInstanceIdFunc == nil { + panic("VgpuInstance.GetGpuInstanceIdFunc: method is nil but VgpuInstance.GetGpuInstanceId was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuInstanceId.Lock() + mock.calls.GetGpuInstanceId = append(mock.calls.GetGpuInstanceId, callInfo) + mock.lockGetGpuInstanceId.Unlock() + return mock.GetGpuInstanceIdFunc() +} + +// GetGpuInstanceIdCalls gets all the calls that were made to GetGpuInstanceId. +// Check the length with: +// +// len(mockedVgpuInstance.GetGpuInstanceIdCalls()) +func (mock *VgpuInstance) GetGpuInstanceIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuInstanceId.RLock() + calls = mock.calls.GetGpuInstanceId + mock.lockGetGpuInstanceId.RUnlock() + return calls +} + +// GetGpuPciId calls GetGpuPciIdFunc. +func (mock *VgpuInstance) GetGpuPciId() (string, nvml.Return) { + if mock.GetGpuPciIdFunc == nil { + panic("VgpuInstance.GetGpuPciIdFunc: method is nil but VgpuInstance.GetGpuPciId was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuPciId.Lock() + mock.calls.GetGpuPciId = append(mock.calls.GetGpuPciId, callInfo) + mock.lockGetGpuPciId.Unlock() + return mock.GetGpuPciIdFunc() +} + +// GetGpuPciIdCalls gets all the calls that were made to GetGpuPciId. +// Check the length with: +// +// len(mockedVgpuInstance.GetGpuPciIdCalls()) +func (mock *VgpuInstance) GetGpuPciIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuPciId.RLock() + calls = mock.calls.GetGpuPciId + mock.lockGetGpuPciId.RUnlock() + return calls +} + +// GetLicenseInfo calls GetLicenseInfoFunc. +func (mock *VgpuInstance) GetLicenseInfo() (nvml.VgpuLicenseInfo, nvml.Return) { + if mock.GetLicenseInfoFunc == nil { + panic("VgpuInstance.GetLicenseInfoFunc: method is nil but VgpuInstance.GetLicenseInfo was just called") + } + callInfo := struct { + }{} + mock.lockGetLicenseInfo.Lock() + mock.calls.GetLicenseInfo = append(mock.calls.GetLicenseInfo, callInfo) + mock.lockGetLicenseInfo.Unlock() + return mock.GetLicenseInfoFunc() +} + +// GetLicenseInfoCalls gets all the calls that were made to GetLicenseInfo. +// Check the length with: +// +// len(mockedVgpuInstance.GetLicenseInfoCalls()) +func (mock *VgpuInstance) GetLicenseInfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetLicenseInfo.RLock() + calls = mock.calls.GetLicenseInfo + mock.lockGetLicenseInfo.RUnlock() + return calls +} + +// GetLicenseStatus calls GetLicenseStatusFunc. +func (mock *VgpuInstance) GetLicenseStatus() (int, nvml.Return) { + if mock.GetLicenseStatusFunc == nil { + panic("VgpuInstance.GetLicenseStatusFunc: method is nil but VgpuInstance.GetLicenseStatus was just called") + } + callInfo := struct { + }{} + mock.lockGetLicenseStatus.Lock() + mock.calls.GetLicenseStatus = append(mock.calls.GetLicenseStatus, callInfo) + mock.lockGetLicenseStatus.Unlock() + return mock.GetLicenseStatusFunc() +} + +// GetLicenseStatusCalls gets all the calls that were made to GetLicenseStatus. +// Check the length with: +// +// len(mockedVgpuInstance.GetLicenseStatusCalls()) +func (mock *VgpuInstance) GetLicenseStatusCalls() []struct { +} { + var calls []struct { + } + mock.lockGetLicenseStatus.RLock() + calls = mock.calls.GetLicenseStatus + mock.lockGetLicenseStatus.RUnlock() + return calls +} + +// GetMdevUUID calls GetMdevUUIDFunc. +func (mock *VgpuInstance) GetMdevUUID() (string, nvml.Return) { + if mock.GetMdevUUIDFunc == nil { + panic("VgpuInstance.GetMdevUUIDFunc: method is nil but VgpuInstance.GetMdevUUID was just called") + } + callInfo := struct { + }{} + mock.lockGetMdevUUID.Lock() + mock.calls.GetMdevUUID = append(mock.calls.GetMdevUUID, callInfo) + mock.lockGetMdevUUID.Unlock() + return mock.GetMdevUUIDFunc() +} + +// GetMdevUUIDCalls gets all the calls that were made to GetMdevUUID. +// Check the length with: +// +// len(mockedVgpuInstance.GetMdevUUIDCalls()) +func (mock *VgpuInstance) GetMdevUUIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMdevUUID.RLock() + calls = mock.calls.GetMdevUUID + mock.lockGetMdevUUID.RUnlock() + return calls +} + +// GetMetadata calls GetMetadataFunc. +func (mock *VgpuInstance) GetMetadata() (nvml.VgpuMetadata, nvml.Return) { + if mock.GetMetadataFunc == nil { + panic("VgpuInstance.GetMetadataFunc: method is nil but VgpuInstance.GetMetadata was just called") + } + callInfo := struct { + }{} + mock.lockGetMetadata.Lock() + mock.calls.GetMetadata = append(mock.calls.GetMetadata, callInfo) + mock.lockGetMetadata.Unlock() + return mock.GetMetadataFunc() +} + +// GetMetadataCalls gets all the calls that were made to GetMetadata. +// Check the length with: +// +// len(mockedVgpuInstance.GetMetadataCalls()) +func (mock *VgpuInstance) GetMetadataCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMetadata.RLock() + calls = mock.calls.GetMetadata + mock.lockGetMetadata.RUnlock() + return calls +} + +// GetRuntimeStateSize calls GetRuntimeStateSizeFunc. +func (mock *VgpuInstance) GetRuntimeStateSize() (nvml.VgpuRuntimeState, nvml.Return) { + if mock.GetRuntimeStateSizeFunc == nil { + panic("VgpuInstance.GetRuntimeStateSizeFunc: method is nil but VgpuInstance.GetRuntimeStateSize was just called") + } + callInfo := struct { + }{} + mock.lockGetRuntimeStateSize.Lock() + mock.calls.GetRuntimeStateSize = append(mock.calls.GetRuntimeStateSize, callInfo) + mock.lockGetRuntimeStateSize.Unlock() + return mock.GetRuntimeStateSizeFunc() +} + +// GetRuntimeStateSizeCalls gets all the calls that were made to GetRuntimeStateSize. +// Check the length with: +// +// len(mockedVgpuInstance.GetRuntimeStateSizeCalls()) +func (mock *VgpuInstance) GetRuntimeStateSizeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetRuntimeStateSize.RLock() + calls = mock.calls.GetRuntimeStateSize + mock.lockGetRuntimeStateSize.RUnlock() + return calls +} + +// GetType calls GetTypeFunc. +func (mock *VgpuInstance) GetType() (nvml.VgpuTypeId, nvml.Return) { + if mock.GetTypeFunc == nil { + panic("VgpuInstance.GetTypeFunc: method is nil but VgpuInstance.GetType was just called") + } + callInfo := struct { + }{} + mock.lockGetType.Lock() + mock.calls.GetType = append(mock.calls.GetType, callInfo) + mock.lockGetType.Unlock() + return mock.GetTypeFunc() +} + +// GetTypeCalls gets all the calls that were made to GetType. +// Check the length with: +// +// len(mockedVgpuInstance.GetTypeCalls()) +func (mock *VgpuInstance) GetTypeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetType.RLock() + calls = mock.calls.GetType + mock.lockGetType.RUnlock() + return calls +} + +// GetUUID calls GetUUIDFunc. +func (mock *VgpuInstance) GetUUID() (string, nvml.Return) { + if mock.GetUUIDFunc == nil { + panic("VgpuInstance.GetUUIDFunc: method is nil but VgpuInstance.GetUUID was just called") + } + callInfo := struct { + }{} + mock.lockGetUUID.Lock() + mock.calls.GetUUID = append(mock.calls.GetUUID, callInfo) + mock.lockGetUUID.Unlock() + return mock.GetUUIDFunc() +} + +// GetUUIDCalls gets all the calls that were made to GetUUID. +// Check the length with: +// +// len(mockedVgpuInstance.GetUUIDCalls()) +func (mock *VgpuInstance) GetUUIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetUUID.RLock() + calls = mock.calls.GetUUID + mock.lockGetUUID.RUnlock() + return calls +} + +// GetVmDriverVersion calls GetVmDriverVersionFunc. +func (mock *VgpuInstance) GetVmDriverVersion() (string, nvml.Return) { + if mock.GetVmDriverVersionFunc == nil { + panic("VgpuInstance.GetVmDriverVersionFunc: method is nil but VgpuInstance.GetVmDriverVersion was just called") + } + callInfo := struct { + }{} + mock.lockGetVmDriverVersion.Lock() + mock.calls.GetVmDriverVersion = append(mock.calls.GetVmDriverVersion, callInfo) + mock.lockGetVmDriverVersion.Unlock() + return mock.GetVmDriverVersionFunc() +} + +// GetVmDriverVersionCalls gets all the calls that were made to GetVmDriverVersion. +// Check the length with: +// +// len(mockedVgpuInstance.GetVmDriverVersionCalls()) +func (mock *VgpuInstance) GetVmDriverVersionCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVmDriverVersion.RLock() + calls = mock.calls.GetVmDriverVersion + mock.lockGetVmDriverVersion.RUnlock() + return calls +} + +// GetVmID calls GetVmIDFunc. +func (mock *VgpuInstance) GetVmID() (string, nvml.VgpuVmIdType, nvml.Return) { + if mock.GetVmIDFunc == nil { + panic("VgpuInstance.GetVmIDFunc: method is nil but VgpuInstance.GetVmID was just called") + } + callInfo := struct { + }{} + mock.lockGetVmID.Lock() + mock.calls.GetVmID = append(mock.calls.GetVmID, callInfo) + mock.lockGetVmID.Unlock() + return mock.GetVmIDFunc() +} + +// GetVmIDCalls gets all the calls that were made to GetVmID. +// Check the length with: +// +// len(mockedVgpuInstance.GetVmIDCalls()) +func (mock *VgpuInstance) GetVmIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetVmID.RLock() + calls = mock.calls.GetVmID + mock.lockGetVmID.RUnlock() + return calls +} + +// SetEncoderCapacity calls SetEncoderCapacityFunc. +func (mock *VgpuInstance) SetEncoderCapacity(n int) nvml.Return { + if mock.SetEncoderCapacityFunc == nil { + panic("VgpuInstance.SetEncoderCapacityFunc: method is nil but VgpuInstance.SetEncoderCapacity was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockSetEncoderCapacity.Lock() + mock.calls.SetEncoderCapacity = append(mock.calls.SetEncoderCapacity, callInfo) + mock.lockSetEncoderCapacity.Unlock() + return mock.SetEncoderCapacityFunc(n) +} + +// SetEncoderCapacityCalls gets all the calls that were made to SetEncoderCapacity. +// Check the length with: +// +// len(mockedVgpuInstance.SetEncoderCapacityCalls()) +func (mock *VgpuInstance) SetEncoderCapacityCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockSetEncoderCapacity.RLock() + calls = mock.calls.SetEncoderCapacity + mock.lockSetEncoderCapacity.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgputypeid.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgputypeid.go new file mode 100644 index 00000000..467d7468 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/mock/vgputypeid.go @@ -0,0 +1,621 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package mock + +import ( + "github.com/NVIDIA/go-nvml/pkg/nvml" + "sync" +) + +// Ensure, that VgpuTypeId does implement nvml.VgpuTypeId. +// If this is not the case, regenerate this file with moq. +var _ nvml.VgpuTypeId = &VgpuTypeId{} + +// VgpuTypeId is a mock implementation of nvml.VgpuTypeId. +// +// func TestSomethingThatUsesVgpuTypeId(t *testing.T) { +// +// // make and configure a mocked nvml.VgpuTypeId +// mockedVgpuTypeId := &VgpuTypeId{ +// GetBAR1InfoFunc: func() (nvml.VgpuTypeBar1Info, nvml.Return) { +// panic("mock out the GetBAR1Info method") +// }, +// GetCapabilitiesFunc: func(vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) { +// panic("mock out the GetCapabilities method") +// }, +// GetClassFunc: func() (string, nvml.Return) { +// panic("mock out the GetClass method") +// }, +// GetCreatablePlacementsFunc: func(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the GetCreatablePlacements method") +// }, +// GetDeviceIDFunc: func() (uint64, uint64, nvml.Return) { +// panic("mock out the GetDeviceID method") +// }, +// GetFrameRateLimitFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetFrameRateLimit method") +// }, +// GetFramebufferSizeFunc: func() (uint64, nvml.Return) { +// panic("mock out the GetFramebufferSize method") +// }, +// GetGpuInstanceProfileIdFunc: func() (uint32, nvml.Return) { +// panic("mock out the GetGpuInstanceProfileId method") +// }, +// GetLicenseFunc: func() (string, nvml.Return) { +// panic("mock out the GetLicense method") +// }, +// GetMaxInstancesFunc: func(device nvml.Device) (int, nvml.Return) { +// panic("mock out the GetMaxInstances method") +// }, +// GetMaxInstancesPerVmFunc: func() (int, nvml.Return) { +// panic("mock out the GetMaxInstancesPerVm method") +// }, +// GetNameFunc: func() (string, nvml.Return) { +// panic("mock out the GetName method") +// }, +// GetNumDisplayHeadsFunc: func() (int, nvml.Return) { +// panic("mock out the GetNumDisplayHeads method") +// }, +// GetResolutionFunc: func(n int) (uint32, uint32, nvml.Return) { +// panic("mock out the GetResolution method") +// }, +// GetSupportedPlacementsFunc: func(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) { +// panic("mock out the GetSupportedPlacements method") +// }, +// } +// +// // use mockedVgpuTypeId in code that requires nvml.VgpuTypeId +// // and then make assertions. +// +// } +type VgpuTypeId struct { + // GetBAR1InfoFunc mocks the GetBAR1Info method. + GetBAR1InfoFunc func() (nvml.VgpuTypeBar1Info, nvml.Return) + + // GetCapabilitiesFunc mocks the GetCapabilities method. + GetCapabilitiesFunc func(vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) + + // GetClassFunc mocks the GetClass method. + GetClassFunc func() (string, nvml.Return) + + // GetCreatablePlacementsFunc mocks the GetCreatablePlacements method. + GetCreatablePlacementsFunc func(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) + + // GetDeviceIDFunc mocks the GetDeviceID method. + GetDeviceIDFunc func() (uint64, uint64, nvml.Return) + + // GetFrameRateLimitFunc mocks the GetFrameRateLimit method. + GetFrameRateLimitFunc func() (uint32, nvml.Return) + + // GetFramebufferSizeFunc mocks the GetFramebufferSize method. + GetFramebufferSizeFunc func() (uint64, nvml.Return) + + // GetGpuInstanceProfileIdFunc mocks the GetGpuInstanceProfileId method. + GetGpuInstanceProfileIdFunc func() (uint32, nvml.Return) + + // GetLicenseFunc mocks the GetLicense method. + GetLicenseFunc func() (string, nvml.Return) + + // GetMaxInstancesFunc mocks the GetMaxInstances method. + GetMaxInstancesFunc func(device nvml.Device) (int, nvml.Return) + + // GetMaxInstancesPerVmFunc mocks the GetMaxInstancesPerVm method. + GetMaxInstancesPerVmFunc func() (int, nvml.Return) + + // GetNameFunc mocks the GetName method. + GetNameFunc func() (string, nvml.Return) + + // GetNumDisplayHeadsFunc mocks the GetNumDisplayHeads method. + GetNumDisplayHeadsFunc func() (int, nvml.Return) + + // GetResolutionFunc mocks the GetResolution method. + GetResolutionFunc func(n int) (uint32, uint32, nvml.Return) + + // GetSupportedPlacementsFunc mocks the GetSupportedPlacements method. + GetSupportedPlacementsFunc func(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) + + // calls tracks calls to the methods. + calls struct { + // GetBAR1Info holds details about calls to the GetBAR1Info method. + GetBAR1Info []struct { + } + // GetCapabilities holds details about calls to the GetCapabilities method. + GetCapabilities []struct { + // VgpuCapability is the vgpuCapability argument value. + VgpuCapability nvml.VgpuCapability + } + // GetClass holds details about calls to the GetClass method. + GetClass []struct { + } + // GetCreatablePlacements holds details about calls to the GetCreatablePlacements method. + GetCreatablePlacements []struct { + // Device is the device argument value. + Device nvml.Device + } + // GetDeviceID holds details about calls to the GetDeviceID method. + GetDeviceID []struct { + } + // GetFrameRateLimit holds details about calls to the GetFrameRateLimit method. + GetFrameRateLimit []struct { + } + // GetFramebufferSize holds details about calls to the GetFramebufferSize method. + GetFramebufferSize []struct { + } + // GetGpuInstanceProfileId holds details about calls to the GetGpuInstanceProfileId method. + GetGpuInstanceProfileId []struct { + } + // GetLicense holds details about calls to the GetLicense method. + GetLicense []struct { + } + // GetMaxInstances holds details about calls to the GetMaxInstances method. + GetMaxInstances []struct { + // Device is the device argument value. + Device nvml.Device + } + // GetMaxInstancesPerVm holds details about calls to the GetMaxInstancesPerVm method. + GetMaxInstancesPerVm []struct { + } + // GetName holds details about calls to the GetName method. + GetName []struct { + } + // GetNumDisplayHeads holds details about calls to the GetNumDisplayHeads method. + GetNumDisplayHeads []struct { + } + // GetResolution holds details about calls to the GetResolution method. + GetResolution []struct { + // N is the n argument value. + N int + } + // GetSupportedPlacements holds details about calls to the GetSupportedPlacements method. + GetSupportedPlacements []struct { + // Device is the device argument value. + Device nvml.Device + } + } + lockGetBAR1Info sync.RWMutex + lockGetCapabilities sync.RWMutex + lockGetClass sync.RWMutex + lockGetCreatablePlacements sync.RWMutex + lockGetDeviceID sync.RWMutex + lockGetFrameRateLimit sync.RWMutex + lockGetFramebufferSize sync.RWMutex + lockGetGpuInstanceProfileId sync.RWMutex + lockGetLicense sync.RWMutex + lockGetMaxInstances sync.RWMutex + lockGetMaxInstancesPerVm sync.RWMutex + lockGetName sync.RWMutex + lockGetNumDisplayHeads sync.RWMutex + lockGetResolution sync.RWMutex + lockGetSupportedPlacements sync.RWMutex +} + +// GetBAR1Info calls GetBAR1InfoFunc. +func (mock *VgpuTypeId) GetBAR1Info() (nvml.VgpuTypeBar1Info, nvml.Return) { + if mock.GetBAR1InfoFunc == nil { + panic("VgpuTypeId.GetBAR1InfoFunc: method is nil but VgpuTypeId.GetBAR1Info was just called") + } + callInfo := struct { + }{} + mock.lockGetBAR1Info.Lock() + mock.calls.GetBAR1Info = append(mock.calls.GetBAR1Info, callInfo) + mock.lockGetBAR1Info.Unlock() + return mock.GetBAR1InfoFunc() +} + +// GetBAR1InfoCalls gets all the calls that were made to GetBAR1Info. +// Check the length with: +// +// len(mockedVgpuTypeId.GetBAR1InfoCalls()) +func (mock *VgpuTypeId) GetBAR1InfoCalls() []struct { +} { + var calls []struct { + } + mock.lockGetBAR1Info.RLock() + calls = mock.calls.GetBAR1Info + mock.lockGetBAR1Info.RUnlock() + return calls +} + +// GetCapabilities calls GetCapabilitiesFunc. +func (mock *VgpuTypeId) GetCapabilities(vgpuCapability nvml.VgpuCapability) (bool, nvml.Return) { + if mock.GetCapabilitiesFunc == nil { + panic("VgpuTypeId.GetCapabilitiesFunc: method is nil but VgpuTypeId.GetCapabilities was just called") + } + callInfo := struct { + VgpuCapability nvml.VgpuCapability + }{ + VgpuCapability: vgpuCapability, + } + mock.lockGetCapabilities.Lock() + mock.calls.GetCapabilities = append(mock.calls.GetCapabilities, callInfo) + mock.lockGetCapabilities.Unlock() + return mock.GetCapabilitiesFunc(vgpuCapability) +} + +// GetCapabilitiesCalls gets all the calls that were made to GetCapabilities. +// Check the length with: +// +// len(mockedVgpuTypeId.GetCapabilitiesCalls()) +func (mock *VgpuTypeId) GetCapabilitiesCalls() []struct { + VgpuCapability nvml.VgpuCapability +} { + var calls []struct { + VgpuCapability nvml.VgpuCapability + } + mock.lockGetCapabilities.RLock() + calls = mock.calls.GetCapabilities + mock.lockGetCapabilities.RUnlock() + return calls +} + +// GetClass calls GetClassFunc. +func (mock *VgpuTypeId) GetClass() (string, nvml.Return) { + if mock.GetClassFunc == nil { + panic("VgpuTypeId.GetClassFunc: method is nil but VgpuTypeId.GetClass was just called") + } + callInfo := struct { + }{} + mock.lockGetClass.Lock() + mock.calls.GetClass = append(mock.calls.GetClass, callInfo) + mock.lockGetClass.Unlock() + return mock.GetClassFunc() +} + +// GetClassCalls gets all the calls that were made to GetClass. +// Check the length with: +// +// len(mockedVgpuTypeId.GetClassCalls()) +func (mock *VgpuTypeId) GetClassCalls() []struct { +} { + var calls []struct { + } + mock.lockGetClass.RLock() + calls = mock.calls.GetClass + mock.lockGetClass.RUnlock() + return calls +} + +// GetCreatablePlacements calls GetCreatablePlacementsFunc. +func (mock *VgpuTypeId) GetCreatablePlacements(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) { + if mock.GetCreatablePlacementsFunc == nil { + panic("VgpuTypeId.GetCreatablePlacementsFunc: method is nil but VgpuTypeId.GetCreatablePlacements was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGetCreatablePlacements.Lock() + mock.calls.GetCreatablePlacements = append(mock.calls.GetCreatablePlacements, callInfo) + mock.lockGetCreatablePlacements.Unlock() + return mock.GetCreatablePlacementsFunc(device) +} + +// GetCreatablePlacementsCalls gets all the calls that were made to GetCreatablePlacements. +// Check the length with: +// +// len(mockedVgpuTypeId.GetCreatablePlacementsCalls()) +func (mock *VgpuTypeId) GetCreatablePlacementsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGetCreatablePlacements.RLock() + calls = mock.calls.GetCreatablePlacements + mock.lockGetCreatablePlacements.RUnlock() + return calls +} + +// GetDeviceID calls GetDeviceIDFunc. +func (mock *VgpuTypeId) GetDeviceID() (uint64, uint64, nvml.Return) { + if mock.GetDeviceIDFunc == nil { + panic("VgpuTypeId.GetDeviceIDFunc: method is nil but VgpuTypeId.GetDeviceID was just called") + } + callInfo := struct { + }{} + mock.lockGetDeviceID.Lock() + mock.calls.GetDeviceID = append(mock.calls.GetDeviceID, callInfo) + mock.lockGetDeviceID.Unlock() + return mock.GetDeviceIDFunc() +} + +// GetDeviceIDCalls gets all the calls that were made to GetDeviceID. +// Check the length with: +// +// len(mockedVgpuTypeId.GetDeviceIDCalls()) +func (mock *VgpuTypeId) GetDeviceIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetDeviceID.RLock() + calls = mock.calls.GetDeviceID + mock.lockGetDeviceID.RUnlock() + return calls +} + +// GetFrameRateLimit calls GetFrameRateLimitFunc. +func (mock *VgpuTypeId) GetFrameRateLimit() (uint32, nvml.Return) { + if mock.GetFrameRateLimitFunc == nil { + panic("VgpuTypeId.GetFrameRateLimitFunc: method is nil but VgpuTypeId.GetFrameRateLimit was just called") + } + callInfo := struct { + }{} + mock.lockGetFrameRateLimit.Lock() + mock.calls.GetFrameRateLimit = append(mock.calls.GetFrameRateLimit, callInfo) + mock.lockGetFrameRateLimit.Unlock() + return mock.GetFrameRateLimitFunc() +} + +// GetFrameRateLimitCalls gets all the calls that were made to GetFrameRateLimit. +// Check the length with: +// +// len(mockedVgpuTypeId.GetFrameRateLimitCalls()) +func (mock *VgpuTypeId) GetFrameRateLimitCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFrameRateLimit.RLock() + calls = mock.calls.GetFrameRateLimit + mock.lockGetFrameRateLimit.RUnlock() + return calls +} + +// GetFramebufferSize calls GetFramebufferSizeFunc. +func (mock *VgpuTypeId) GetFramebufferSize() (uint64, nvml.Return) { + if mock.GetFramebufferSizeFunc == nil { + panic("VgpuTypeId.GetFramebufferSizeFunc: method is nil but VgpuTypeId.GetFramebufferSize was just called") + } + callInfo := struct { + }{} + mock.lockGetFramebufferSize.Lock() + mock.calls.GetFramebufferSize = append(mock.calls.GetFramebufferSize, callInfo) + mock.lockGetFramebufferSize.Unlock() + return mock.GetFramebufferSizeFunc() +} + +// GetFramebufferSizeCalls gets all the calls that were made to GetFramebufferSize. +// Check the length with: +// +// len(mockedVgpuTypeId.GetFramebufferSizeCalls()) +func (mock *VgpuTypeId) GetFramebufferSizeCalls() []struct { +} { + var calls []struct { + } + mock.lockGetFramebufferSize.RLock() + calls = mock.calls.GetFramebufferSize + mock.lockGetFramebufferSize.RUnlock() + return calls +} + +// GetGpuInstanceProfileId calls GetGpuInstanceProfileIdFunc. +func (mock *VgpuTypeId) GetGpuInstanceProfileId() (uint32, nvml.Return) { + if mock.GetGpuInstanceProfileIdFunc == nil { + panic("VgpuTypeId.GetGpuInstanceProfileIdFunc: method is nil but VgpuTypeId.GetGpuInstanceProfileId was just called") + } + callInfo := struct { + }{} + mock.lockGetGpuInstanceProfileId.Lock() + mock.calls.GetGpuInstanceProfileId = append(mock.calls.GetGpuInstanceProfileId, callInfo) + mock.lockGetGpuInstanceProfileId.Unlock() + return mock.GetGpuInstanceProfileIdFunc() +} + +// GetGpuInstanceProfileIdCalls gets all the calls that were made to GetGpuInstanceProfileId. +// Check the length with: +// +// len(mockedVgpuTypeId.GetGpuInstanceProfileIdCalls()) +func (mock *VgpuTypeId) GetGpuInstanceProfileIdCalls() []struct { +} { + var calls []struct { + } + mock.lockGetGpuInstanceProfileId.RLock() + calls = mock.calls.GetGpuInstanceProfileId + mock.lockGetGpuInstanceProfileId.RUnlock() + return calls +} + +// GetLicense calls GetLicenseFunc. +func (mock *VgpuTypeId) GetLicense() (string, nvml.Return) { + if mock.GetLicenseFunc == nil { + panic("VgpuTypeId.GetLicenseFunc: method is nil but VgpuTypeId.GetLicense was just called") + } + callInfo := struct { + }{} + mock.lockGetLicense.Lock() + mock.calls.GetLicense = append(mock.calls.GetLicense, callInfo) + mock.lockGetLicense.Unlock() + return mock.GetLicenseFunc() +} + +// GetLicenseCalls gets all the calls that were made to GetLicense. +// Check the length with: +// +// len(mockedVgpuTypeId.GetLicenseCalls()) +func (mock *VgpuTypeId) GetLicenseCalls() []struct { +} { + var calls []struct { + } + mock.lockGetLicense.RLock() + calls = mock.calls.GetLicense + mock.lockGetLicense.RUnlock() + return calls +} + +// GetMaxInstances calls GetMaxInstancesFunc. +func (mock *VgpuTypeId) GetMaxInstances(device nvml.Device) (int, nvml.Return) { + if mock.GetMaxInstancesFunc == nil { + panic("VgpuTypeId.GetMaxInstancesFunc: method is nil but VgpuTypeId.GetMaxInstances was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGetMaxInstances.Lock() + mock.calls.GetMaxInstances = append(mock.calls.GetMaxInstances, callInfo) + mock.lockGetMaxInstances.Unlock() + return mock.GetMaxInstancesFunc(device) +} + +// GetMaxInstancesCalls gets all the calls that were made to GetMaxInstances. +// Check the length with: +// +// len(mockedVgpuTypeId.GetMaxInstancesCalls()) +func (mock *VgpuTypeId) GetMaxInstancesCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGetMaxInstances.RLock() + calls = mock.calls.GetMaxInstances + mock.lockGetMaxInstances.RUnlock() + return calls +} + +// GetMaxInstancesPerVm calls GetMaxInstancesPerVmFunc. +func (mock *VgpuTypeId) GetMaxInstancesPerVm() (int, nvml.Return) { + if mock.GetMaxInstancesPerVmFunc == nil { + panic("VgpuTypeId.GetMaxInstancesPerVmFunc: method is nil but VgpuTypeId.GetMaxInstancesPerVm was just called") + } + callInfo := struct { + }{} + mock.lockGetMaxInstancesPerVm.Lock() + mock.calls.GetMaxInstancesPerVm = append(mock.calls.GetMaxInstancesPerVm, callInfo) + mock.lockGetMaxInstancesPerVm.Unlock() + return mock.GetMaxInstancesPerVmFunc() +} + +// GetMaxInstancesPerVmCalls gets all the calls that were made to GetMaxInstancesPerVm. +// Check the length with: +// +// len(mockedVgpuTypeId.GetMaxInstancesPerVmCalls()) +func (mock *VgpuTypeId) GetMaxInstancesPerVmCalls() []struct { +} { + var calls []struct { + } + mock.lockGetMaxInstancesPerVm.RLock() + calls = mock.calls.GetMaxInstancesPerVm + mock.lockGetMaxInstancesPerVm.RUnlock() + return calls +} + +// GetName calls GetNameFunc. +func (mock *VgpuTypeId) GetName() (string, nvml.Return) { + if mock.GetNameFunc == nil { + panic("VgpuTypeId.GetNameFunc: method is nil but VgpuTypeId.GetName was just called") + } + callInfo := struct { + }{} + mock.lockGetName.Lock() + mock.calls.GetName = append(mock.calls.GetName, callInfo) + mock.lockGetName.Unlock() + return mock.GetNameFunc() +} + +// GetNameCalls gets all the calls that were made to GetName. +// Check the length with: +// +// len(mockedVgpuTypeId.GetNameCalls()) +func (mock *VgpuTypeId) GetNameCalls() []struct { +} { + var calls []struct { + } + mock.lockGetName.RLock() + calls = mock.calls.GetName + mock.lockGetName.RUnlock() + return calls +} + +// GetNumDisplayHeads calls GetNumDisplayHeadsFunc. +func (mock *VgpuTypeId) GetNumDisplayHeads() (int, nvml.Return) { + if mock.GetNumDisplayHeadsFunc == nil { + panic("VgpuTypeId.GetNumDisplayHeadsFunc: method is nil but VgpuTypeId.GetNumDisplayHeads was just called") + } + callInfo := struct { + }{} + mock.lockGetNumDisplayHeads.Lock() + mock.calls.GetNumDisplayHeads = append(mock.calls.GetNumDisplayHeads, callInfo) + mock.lockGetNumDisplayHeads.Unlock() + return mock.GetNumDisplayHeadsFunc() +} + +// GetNumDisplayHeadsCalls gets all the calls that were made to GetNumDisplayHeads. +// Check the length with: +// +// len(mockedVgpuTypeId.GetNumDisplayHeadsCalls()) +func (mock *VgpuTypeId) GetNumDisplayHeadsCalls() []struct { +} { + var calls []struct { + } + mock.lockGetNumDisplayHeads.RLock() + calls = mock.calls.GetNumDisplayHeads + mock.lockGetNumDisplayHeads.RUnlock() + return calls +} + +// GetResolution calls GetResolutionFunc. +func (mock *VgpuTypeId) GetResolution(n int) (uint32, uint32, nvml.Return) { + if mock.GetResolutionFunc == nil { + panic("VgpuTypeId.GetResolutionFunc: method is nil but VgpuTypeId.GetResolution was just called") + } + callInfo := struct { + N int + }{ + N: n, + } + mock.lockGetResolution.Lock() + mock.calls.GetResolution = append(mock.calls.GetResolution, callInfo) + mock.lockGetResolution.Unlock() + return mock.GetResolutionFunc(n) +} + +// GetResolutionCalls gets all the calls that were made to GetResolution. +// Check the length with: +// +// len(mockedVgpuTypeId.GetResolutionCalls()) +func (mock *VgpuTypeId) GetResolutionCalls() []struct { + N int +} { + var calls []struct { + N int + } + mock.lockGetResolution.RLock() + calls = mock.calls.GetResolution + mock.lockGetResolution.RUnlock() + return calls +} + +// GetSupportedPlacements calls GetSupportedPlacementsFunc. +func (mock *VgpuTypeId) GetSupportedPlacements(device nvml.Device) (nvml.VgpuPlacementList, nvml.Return) { + if mock.GetSupportedPlacementsFunc == nil { + panic("VgpuTypeId.GetSupportedPlacementsFunc: method is nil but VgpuTypeId.GetSupportedPlacements was just called") + } + callInfo := struct { + Device nvml.Device + }{ + Device: device, + } + mock.lockGetSupportedPlacements.Lock() + mock.calls.GetSupportedPlacements = append(mock.calls.GetSupportedPlacements, callInfo) + mock.lockGetSupportedPlacements.Unlock() + return mock.GetSupportedPlacementsFunc(device) +} + +// GetSupportedPlacementsCalls gets all the calls that were made to GetSupportedPlacements. +// Check the length with: +// +// len(mockedVgpuTypeId.GetSupportedPlacementsCalls()) +func (mock *VgpuTypeId) GetSupportedPlacementsCalls() []struct { + Device nvml.Device +} { + var calls []struct { + Device nvml.Device + } + mock.lockGetSupportedPlacements.RLock() + calls = mock.calls.GetSupportedPlacements + mock.lockGetSupportedPlacements.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.go new file mode 100644 index 00000000..38123a96 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.go @@ -0,0 +1,3749 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +package nvml + +/* +#cgo linux LDFLAGS: -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files +#cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup +#cgo CFLAGS: -DNVML_NO_UNVERSIONED_FUNC_DEFS=1 +#include "nvml.h" +#include +#include "cgo_helpers.h" +*/ +import "C" +import "unsafe" + +// nvmlInit_v2 function as declared in nvml/nvml.h +func nvmlInit_v2() Return { + __ret := C.nvmlInit_v2() + __v := (Return)(__ret) + return __v +} + +// nvmlInitWithFlags function as declared in nvml/nvml.h +func nvmlInitWithFlags(Flags uint32) Return { + cFlags, _ := (C.uint)(Flags), cgoAllocsUnknown + __ret := C.nvmlInitWithFlags(cFlags) + __v := (Return)(__ret) + return __v +} + +// nvmlShutdown function as declared in nvml/nvml.h +func nvmlShutdown() Return { + __ret := C.nvmlShutdown() + __v := (Return)(__ret) + return __v +} + +// nvmlErrorString function as declared in nvml/nvml.h +func nvmlErrorString(Result Return) string { + cResult, _ := (C.nvmlReturn_t)(Result), cgoAllocsUnknown + __ret := C.nvmlErrorString(cResult) + __v := packPCharString(__ret) + return __v +} + +// nvmlSystemGetDriverVersion function as declared in nvml/nvml.h +func nvmlSystemGetDriverVersion(Version *byte, Length uint32) Return { + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlSystemGetDriverVersion(cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetNVMLVersion function as declared in nvml/nvml.h +func nvmlSystemGetNVMLVersion(Version *byte, Length uint32) Return { + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlSystemGetNVMLVersion(cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetCudaDriverVersion function as declared in nvml/nvml.h +func nvmlSystemGetCudaDriverVersion(CudaDriverVersion *int32) Return { + cCudaDriverVersion, _ := (*C.int)(unsafe.Pointer(CudaDriverVersion)), cgoAllocsUnknown + __ret := C.nvmlSystemGetCudaDriverVersion(cCudaDriverVersion) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetCudaDriverVersion_v2 function as declared in nvml/nvml.h +func nvmlSystemGetCudaDriverVersion_v2(CudaDriverVersion *int32) Return { + cCudaDriverVersion, _ := (*C.int)(unsafe.Pointer(CudaDriverVersion)), cgoAllocsUnknown + __ret := C.nvmlSystemGetCudaDriverVersion_v2(cCudaDriverVersion) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetProcessName function as declared in nvml/nvml.h +func nvmlSystemGetProcessName(Pid uint32, Name *byte, Length uint32) Return { + cPid, _ := (C.uint)(Pid), cgoAllocsUnknown + cName, _ := (*C.char)(unsafe.Pointer(Name)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlSystemGetProcessName(cPid, cName, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetHicVersion function as declared in nvml/nvml.h +func nvmlSystemGetHicVersion(HwbcCount *uint32, HwbcEntries *HwbcEntry) Return { + cHwbcCount, _ := (*C.uint)(unsafe.Pointer(HwbcCount)), cgoAllocsUnknown + cHwbcEntries, _ := (*C.nvmlHwbcEntry_t)(unsafe.Pointer(HwbcEntries)), cgoAllocsUnknown + __ret := C.nvmlSystemGetHicVersion(cHwbcCount, cHwbcEntries) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetTopologyGpuSet function as declared in nvml/nvml.h +func nvmlSystemGetTopologyGpuSet(CpuNumber uint32, Count *uint32, DeviceArray *nvmlDevice) Return { + cCpuNumber, _ := (C.uint)(CpuNumber), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cDeviceArray, _ := (*C.nvmlDevice_t)(unsafe.Pointer(DeviceArray)), cgoAllocsUnknown + __ret := C.nvmlSystemGetTopologyGpuSet(cCpuNumber, cCount, cDeviceArray) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetDriverBranch function as declared in nvml/nvml.h +func nvmlSystemGetDriverBranch(BranchInfo *SystemDriverBranchInfo, Length uint32) Return { + cBranchInfo, _ := (*C.nvmlSystemDriverBranchInfo_t)(unsafe.Pointer(BranchInfo)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlSystemGetDriverBranch(cBranchInfo, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetCount function as declared in nvml/nvml.h +func nvmlUnitGetCount(UnitCount *uint32) Return { + cUnitCount, _ := (*C.uint)(unsafe.Pointer(UnitCount)), cgoAllocsUnknown + __ret := C.nvmlUnitGetCount(cUnitCount) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetHandleByIndex function as declared in nvml/nvml.h +func nvmlUnitGetHandleByIndex(Index uint32, nvmlUnit *nvmlUnit) Return { + cIndex, _ := (C.uint)(Index), cgoAllocsUnknown + cnvmlUnit, _ := (*C.nvmlUnit_t)(unsafe.Pointer(nvmlUnit)), cgoAllocsUnknown + __ret := C.nvmlUnitGetHandleByIndex(cIndex, cnvmlUnit) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetUnitInfo function as declared in nvml/nvml.h +func nvmlUnitGetUnitInfo(nvmlUnit nvmlUnit, Info *UnitInfo) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlUnitInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlUnitGetUnitInfo(cnvmlUnit, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetLedState function as declared in nvml/nvml.h +func nvmlUnitGetLedState(nvmlUnit nvmlUnit, State *LedState) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cState, _ := (*C.nvmlLedState_t)(unsafe.Pointer(State)), cgoAllocsUnknown + __ret := C.nvmlUnitGetLedState(cnvmlUnit, cState) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetPsuInfo function as declared in nvml/nvml.h +func nvmlUnitGetPsuInfo(nvmlUnit nvmlUnit, Psu *PSUInfo) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cPsu, _ := (*C.nvmlPSUInfo_t)(unsafe.Pointer(Psu)), cgoAllocsUnknown + __ret := C.nvmlUnitGetPsuInfo(cnvmlUnit, cPsu) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetTemperature function as declared in nvml/nvml.h +func nvmlUnitGetTemperature(nvmlUnit nvmlUnit, _type uint32, Temp *uint32) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + c_type, _ := (C.uint)(_type), cgoAllocsUnknown + cTemp, _ := (*C.uint)(unsafe.Pointer(Temp)), cgoAllocsUnknown + __ret := C.nvmlUnitGetTemperature(cnvmlUnit, c_type, cTemp) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetFanSpeedInfo function as declared in nvml/nvml.h +func nvmlUnitGetFanSpeedInfo(nvmlUnit nvmlUnit, FanSpeeds *UnitFanSpeeds) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cFanSpeeds, _ := (*C.nvmlUnitFanSpeeds_t)(unsafe.Pointer(FanSpeeds)), cgoAllocsUnknown + __ret := C.nvmlUnitGetFanSpeedInfo(cnvmlUnit, cFanSpeeds) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitGetDevices function as declared in nvml/nvml.h +func nvmlUnitGetDevices(nvmlUnit nvmlUnit, DeviceCount *uint32, Devices *nvmlDevice) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cDeviceCount, _ := (*C.uint)(unsafe.Pointer(DeviceCount)), cgoAllocsUnknown + cDevices, _ := (*C.nvmlDevice_t)(unsafe.Pointer(Devices)), cgoAllocsUnknown + __ret := C.nvmlUnitGetDevices(cnvmlUnit, cDeviceCount, cDevices) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCount_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetCount_v2(DeviceCount *uint32) Return { + cDeviceCount, _ := (*C.uint)(unsafe.Pointer(DeviceCount)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCount_v2(cDeviceCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAttributes_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetAttributes_v2(nvmlDevice nvmlDevice, Attributes *DeviceAttributes) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cAttributes, _ := (*C.nvmlDeviceAttributes_t)(unsafe.Pointer(Attributes)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAttributes_v2(cnvmlDevice, cAttributes) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByIndex_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByIndex_v2(Index uint32, nvmlDevice *nvmlDevice) Return { + cIndex, _ := (C.uint)(Index), cgoAllocsUnknown + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByIndex_v2(cIndex, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleBySerial function as declared in nvml/nvml.h +func nvmlDeviceGetHandleBySerial(Serial string, nvmlDevice *nvmlDevice) Return { + cSerial, _ := unpackPCharString(Serial) + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleBySerial(cSerial, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByUUID function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByUUID(Uuid string, nvmlDevice *nvmlDevice) Return { + cUuid, _ := unpackPCharString(Uuid) + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByUUID(cUuid, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByUUIDV function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByUUIDV(Uuid *UUID, nvmlDevice *nvmlDevice) Return { + cUuid, _ := (*C.nvmlUUID_t)(unsafe.Pointer(Uuid)), cgoAllocsUnknown + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByUUIDV(cUuid, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByPciBusId_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByPciBusId_v2(PciBusId string, nvmlDevice *nvmlDevice) Return { + cPciBusId, _ := unpackPCharString(PciBusId) + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByPciBusId_v2(cPciBusId, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetName function as declared in nvml/nvml.h +func nvmlDeviceGetName(nvmlDevice nvmlDevice, Name *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cName, _ := (*C.char)(unsafe.Pointer(Name)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetName(cnvmlDevice, cName, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBrand function as declared in nvml/nvml.h +func nvmlDeviceGetBrand(nvmlDevice nvmlDevice, _type *BrandType) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (*C.nvmlBrandType_t)(unsafe.Pointer(_type)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBrand(cnvmlDevice, c_type) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetIndex function as declared in nvml/nvml.h +func nvmlDeviceGetIndex(nvmlDevice nvmlDevice, Index *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIndex, _ := (*C.uint)(unsafe.Pointer(Index)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetIndex(cnvmlDevice, cIndex) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSerial function as declared in nvml/nvml.h +func nvmlDeviceGetSerial(nvmlDevice nvmlDevice, Serial *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSerial, _ := (*C.char)(unsafe.Pointer(Serial)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSerial(cnvmlDevice, cSerial, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetModuleId function as declared in nvml/nvml.h +func nvmlDeviceGetModuleId(nvmlDevice nvmlDevice, ModuleId *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cModuleId, _ := (*C.uint)(unsafe.Pointer(ModuleId)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetModuleId(cnvmlDevice, cModuleId) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetC2cModeInfoV function as declared in nvml/nvml.h +func nvmlDeviceGetC2cModeInfoV(nvmlDevice nvmlDevice, C2cModeInfo *C2cModeInfo_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cC2cModeInfo, _ := (*C.nvmlC2cModeInfo_v1_t)(unsafe.Pointer(C2cModeInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetC2cModeInfoV(cnvmlDevice, cC2cModeInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemoryAffinity function as declared in nvml/nvml.h +func nvmlDeviceGetMemoryAffinity(nvmlDevice nvmlDevice, NodeSetSize uint32, NodeSet *uint, Scope AffinityScope) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cNodeSetSize, _ := (C.uint)(NodeSetSize), cgoAllocsUnknown + cNodeSet, _ := (*C.ulong)(unsafe.Pointer(NodeSet)), cgoAllocsUnknown + cScope, _ := (C.nvmlAffinityScope_t)(Scope), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemoryAffinity(cnvmlDevice, cNodeSetSize, cNodeSet, cScope) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCpuAffinityWithinScope function as declared in nvml/nvml.h +func nvmlDeviceGetCpuAffinityWithinScope(nvmlDevice nvmlDevice, CpuSetSize uint32, CpuSet *uint, Scope AffinityScope) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCpuSetSize, _ := (C.uint)(CpuSetSize), cgoAllocsUnknown + cCpuSet, _ := (*C.ulong)(unsafe.Pointer(CpuSet)), cgoAllocsUnknown + cScope, _ := (C.nvmlAffinityScope_t)(Scope), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCpuAffinityWithinScope(cnvmlDevice, cCpuSetSize, cCpuSet, cScope) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCpuAffinity function as declared in nvml/nvml.h +func nvmlDeviceGetCpuAffinity(nvmlDevice nvmlDevice, CpuSetSize uint32, CpuSet *uint) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCpuSetSize, _ := (C.uint)(CpuSetSize), cgoAllocsUnknown + cCpuSet, _ := (*C.ulong)(unsafe.Pointer(CpuSet)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCpuAffinity(cnvmlDevice, cCpuSetSize, cCpuSet) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetCpuAffinity function as declared in nvml/nvml.h +func nvmlDeviceSetCpuAffinity(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetCpuAffinity(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceClearCpuAffinity function as declared in nvml/nvml.h +func nvmlDeviceClearCpuAffinity(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceClearCpuAffinity(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNumaNodeId function as declared in nvml/nvml.h +func nvmlDeviceGetNumaNodeId(nvmlDevice nvmlDevice, Node *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cNode, _ := (*C.uint)(unsafe.Pointer(Node)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNumaNodeId(cnvmlDevice, cNode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAddressingMode function as declared in nvml/nvml.h +func nvmlDeviceGetAddressingMode(nvmlDevice nvmlDevice, Mode *DeviceAddressingMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (*C.nvmlDeviceAddressingMode_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAddressingMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRepairStatus function as declared in nvml/nvml.h +func nvmlDeviceGetRepairStatus(nvmlDevice nvmlDevice, RepairStatus *RepairStatus) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cRepairStatus, _ := (*C.nvmlRepairStatus_t)(unsafe.Pointer(RepairStatus)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRepairStatus(cnvmlDevice, cRepairStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTopologyCommonAncestor function as declared in nvml/nvml.h +func nvmlDeviceGetTopologyCommonAncestor(Device1 nvmlDevice, Device2 nvmlDevice, PathInfo *GpuTopologyLevel) Return { + cDevice1, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device1)), cgoAllocsUnknown + cDevice2, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device2)), cgoAllocsUnknown + cPathInfo, _ := (*C.nvmlGpuTopologyLevel_t)(unsafe.Pointer(PathInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTopologyCommonAncestor(cDevice1, cDevice2, cPathInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTopologyNearestGpus function as declared in nvml/nvml.h +func nvmlDeviceGetTopologyNearestGpus(nvmlDevice nvmlDevice, Level GpuTopologyLevel, Count *uint32, DeviceArray *nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLevel, _ := (C.nvmlGpuTopologyLevel_t)(Level), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cDeviceArray, _ := (*C.nvmlDevice_t)(unsafe.Pointer(DeviceArray)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTopologyNearestGpus(cnvmlDevice, cLevel, cCount, cDeviceArray) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetP2PStatus function as declared in nvml/nvml.h +func nvmlDeviceGetP2PStatus(Device1 nvmlDevice, Device2 nvmlDevice, P2pIndex GpuP2PCapsIndex, P2pStatus *GpuP2PStatus) Return { + cDevice1, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device1)), cgoAllocsUnknown + cDevice2, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device2)), cgoAllocsUnknown + cP2pIndex, _ := (C.nvmlGpuP2PCapsIndex_t)(P2pIndex), cgoAllocsUnknown + cP2pStatus, _ := (*C.nvmlGpuP2PStatus_t)(unsafe.Pointer(P2pStatus)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetP2PStatus(cDevice1, cDevice2, cP2pIndex, cP2pStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetUUID function as declared in nvml/nvml.h +func nvmlDeviceGetUUID(nvmlDevice nvmlDevice, Uuid *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUuid, _ := (*C.char)(unsafe.Pointer(Uuid)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetUUID(cnvmlDevice, cUuid, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMinorNumber function as declared in nvml/nvml.h +func nvmlDeviceGetMinorNumber(nvmlDevice nvmlDevice, MinorNumber *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinorNumber, _ := (*C.uint)(unsafe.Pointer(MinorNumber)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMinorNumber(cnvmlDevice, cMinorNumber) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBoardPartNumber function as declared in nvml/nvml.h +func nvmlDeviceGetBoardPartNumber(nvmlDevice nvmlDevice, PartNumber *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPartNumber, _ := (*C.char)(unsafe.Pointer(PartNumber)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBoardPartNumber(cnvmlDevice, cPartNumber, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetInforomVersion function as declared in nvml/nvml.h +func nvmlDeviceGetInforomVersion(nvmlDevice nvmlDevice, Object InforomObject, Version *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cObject, _ := (C.nvmlInforomObject_t)(Object), cgoAllocsUnknown + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetInforomVersion(cnvmlDevice, cObject, cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetInforomImageVersion function as declared in nvml/nvml.h +func nvmlDeviceGetInforomImageVersion(nvmlDevice nvmlDevice, Version *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetInforomImageVersion(cnvmlDevice, cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetInforomConfigurationChecksum function as declared in nvml/nvml.h +func nvmlDeviceGetInforomConfigurationChecksum(nvmlDevice nvmlDevice, Checksum *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cChecksum, _ := (*C.uint)(unsafe.Pointer(Checksum)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetInforomConfigurationChecksum(cnvmlDevice, cChecksum) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceValidateInforom function as declared in nvml/nvml.h +func nvmlDeviceValidateInforom(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceValidateInforom(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetLastBBXFlushTime function as declared in nvml/nvml.h +func nvmlDeviceGetLastBBXFlushTime(nvmlDevice nvmlDevice, Timestamp *uint64, DurationUs *uint) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cTimestamp, _ := (*C.ulonglong)(unsafe.Pointer(Timestamp)), cgoAllocsUnknown + cDurationUs, _ := (*C.ulong)(unsafe.Pointer(DurationUs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetLastBBXFlushTime(cnvmlDevice, cTimestamp, cDurationUs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDisplayMode function as declared in nvml/nvml.h +func nvmlDeviceGetDisplayMode(nvmlDevice nvmlDevice, Display *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cDisplay, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Display)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDisplayMode(cnvmlDevice, cDisplay) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDisplayActive function as declared in nvml/nvml.h +func nvmlDeviceGetDisplayActive(nvmlDevice nvmlDevice, IsActive *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIsActive, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(IsActive)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDisplayActive(cnvmlDevice, cIsActive) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPersistenceMode function as declared in nvml/nvml.h +func nvmlDeviceGetPersistenceMode(nvmlDevice nvmlDevice, Mode *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPersistenceMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPciInfoExt function as declared in nvml/nvml.h +func nvmlDeviceGetPciInfoExt(nvmlDevice nvmlDevice, Pci *PciInfoExt) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfoExt_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPciInfoExt(cnvmlDevice, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPciInfo_v3 function as declared in nvml/nvml.h +func nvmlDeviceGetPciInfo_v3(nvmlDevice nvmlDevice, Pci *PciInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPciInfo_v3(cnvmlDevice, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMaxPcieLinkGeneration function as declared in nvml/nvml.h +func nvmlDeviceGetMaxPcieLinkGeneration(nvmlDevice nvmlDevice, MaxLinkGen *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMaxLinkGen, _ := (*C.uint)(unsafe.Pointer(MaxLinkGen)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMaxPcieLinkGeneration(cnvmlDevice, cMaxLinkGen) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuMaxPcieLinkGeneration function as declared in nvml/nvml.h +func nvmlDeviceGetGpuMaxPcieLinkGeneration(nvmlDevice nvmlDevice, MaxLinkGenDevice *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMaxLinkGenDevice, _ := (*C.uint)(unsafe.Pointer(MaxLinkGenDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuMaxPcieLinkGeneration(cnvmlDevice, cMaxLinkGenDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMaxPcieLinkWidth function as declared in nvml/nvml.h +func nvmlDeviceGetMaxPcieLinkWidth(nvmlDevice nvmlDevice, MaxLinkWidth *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMaxLinkWidth, _ := (*C.uint)(unsafe.Pointer(MaxLinkWidth)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMaxPcieLinkWidth(cnvmlDevice, cMaxLinkWidth) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCurrPcieLinkGeneration function as declared in nvml/nvml.h +func nvmlDeviceGetCurrPcieLinkGeneration(nvmlDevice nvmlDevice, CurrLinkGen *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrLinkGen, _ := (*C.uint)(unsafe.Pointer(CurrLinkGen)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCurrPcieLinkGeneration(cnvmlDevice, cCurrLinkGen) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCurrPcieLinkWidth function as declared in nvml/nvml.h +func nvmlDeviceGetCurrPcieLinkWidth(nvmlDevice nvmlDevice, CurrLinkWidth *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrLinkWidth, _ := (*C.uint)(unsafe.Pointer(CurrLinkWidth)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCurrPcieLinkWidth(cnvmlDevice, cCurrLinkWidth) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPcieThroughput function as declared in nvml/nvml.h +func nvmlDeviceGetPcieThroughput(nvmlDevice nvmlDevice, Counter PcieUtilCounter, Value *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCounter, _ := (C.nvmlPcieUtilCounter_t)(Counter), cgoAllocsUnknown + cValue, _ := (*C.uint)(unsafe.Pointer(Value)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPcieThroughput(cnvmlDevice, cCounter, cValue) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPcieReplayCounter function as declared in nvml/nvml.h +func nvmlDeviceGetPcieReplayCounter(nvmlDevice nvmlDevice, Value *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cValue, _ := (*C.uint)(unsafe.Pointer(Value)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPcieReplayCounter(cnvmlDevice, cValue) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetClockInfo function as declared in nvml/nvml.h +func nvmlDeviceGetClockInfo(nvmlDevice nvmlDevice, _type ClockType, Clock *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (C.nvmlClockType_t)(_type), cgoAllocsUnknown + cClock, _ := (*C.uint)(unsafe.Pointer(Clock)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetClockInfo(cnvmlDevice, c_type, cClock) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMaxClockInfo function as declared in nvml/nvml.h +func nvmlDeviceGetMaxClockInfo(nvmlDevice nvmlDevice, _type ClockType, Clock *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (C.nvmlClockType_t)(_type), cgoAllocsUnknown + cClock, _ := (*C.uint)(unsafe.Pointer(Clock)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMaxClockInfo(cnvmlDevice, c_type, cClock) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpcClkVfOffset function as declared in nvml/nvml.h +func nvmlDeviceGetGpcClkVfOffset(nvmlDevice nvmlDevice, Offset *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cOffset, _ := (*C.int)(unsafe.Pointer(Offset)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpcClkVfOffset(cnvmlDevice, cOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetApplicationsClock function as declared in nvml/nvml.h +func nvmlDeviceGetApplicationsClock(nvmlDevice nvmlDevice, ClockType ClockType, ClockMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClockType, _ := (C.nvmlClockType_t)(ClockType), cgoAllocsUnknown + cClockMHz, _ := (*C.uint)(unsafe.Pointer(ClockMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetApplicationsClock(cnvmlDevice, cClockType, cClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDefaultApplicationsClock function as declared in nvml/nvml.h +func nvmlDeviceGetDefaultApplicationsClock(nvmlDevice nvmlDevice, ClockType ClockType, ClockMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClockType, _ := (C.nvmlClockType_t)(ClockType), cgoAllocsUnknown + cClockMHz, _ := (*C.uint)(unsafe.Pointer(ClockMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDefaultApplicationsClock(cnvmlDevice, cClockType, cClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetClock function as declared in nvml/nvml.h +func nvmlDeviceGetClock(nvmlDevice nvmlDevice, ClockType ClockType, ClockId ClockId, ClockMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClockType, _ := (C.nvmlClockType_t)(ClockType), cgoAllocsUnknown + cClockId, _ := (C.nvmlClockId_t)(ClockId), cgoAllocsUnknown + cClockMHz, _ := (*C.uint)(unsafe.Pointer(ClockMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetClock(cnvmlDevice, cClockType, cClockId, cClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMaxCustomerBoostClock function as declared in nvml/nvml.h +func nvmlDeviceGetMaxCustomerBoostClock(nvmlDevice nvmlDevice, ClockType ClockType, ClockMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClockType, _ := (C.nvmlClockType_t)(ClockType), cgoAllocsUnknown + cClockMHz, _ := (*C.uint)(unsafe.Pointer(ClockMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMaxCustomerBoostClock(cnvmlDevice, cClockType, cClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedMemoryClocks function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedMemoryClocks(nvmlDevice nvmlDevice, Count *uint32, ClocksMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cClocksMHz, _ := (*C.uint)(unsafe.Pointer(ClocksMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedMemoryClocks(cnvmlDevice, cCount, cClocksMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedGraphicsClocks function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedGraphicsClocks(nvmlDevice nvmlDevice, MemoryClockMHz uint32, Count *uint32, ClocksMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemoryClockMHz, _ := (C.uint)(MemoryClockMHz), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cClocksMHz, _ := (*C.uint)(unsafe.Pointer(ClocksMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedGraphicsClocks(cnvmlDevice, cMemoryClockMHz, cCount, cClocksMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAutoBoostedClocksEnabled function as declared in nvml/nvml.h +func nvmlDeviceGetAutoBoostedClocksEnabled(nvmlDevice nvmlDevice, IsEnabled *EnableState, DefaultIsEnabled *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIsEnabled, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(IsEnabled)), cgoAllocsUnknown + cDefaultIsEnabled, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(DefaultIsEnabled)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAutoBoostedClocksEnabled(cnvmlDevice, cIsEnabled, cDefaultIsEnabled) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFanSpeed function as declared in nvml/nvml.h +func nvmlDeviceGetFanSpeed(nvmlDevice nvmlDevice, Speed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSpeed, _ := (*C.uint)(unsafe.Pointer(Speed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFanSpeed(cnvmlDevice, cSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFanSpeed_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetFanSpeed_v2(nvmlDevice nvmlDevice, Fan uint32, Speed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + cSpeed, _ := (*C.uint)(unsafe.Pointer(Speed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFanSpeed_v2(cnvmlDevice, cFan, cSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFanSpeedRPM function as declared in nvml/nvml.h +func nvmlDeviceGetFanSpeedRPM(nvmlDevice nvmlDevice, FanSpeed *FanSpeedInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFanSpeed, _ := (*C.nvmlFanSpeedInfo_t)(unsafe.Pointer(FanSpeed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFanSpeedRPM(cnvmlDevice, cFanSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTargetFanSpeed function as declared in nvml/nvml.h +func nvmlDeviceGetTargetFanSpeed(nvmlDevice nvmlDevice, Fan uint32, TargetSpeed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + cTargetSpeed, _ := (*C.uint)(unsafe.Pointer(TargetSpeed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTargetFanSpeed(cnvmlDevice, cFan, cTargetSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMinMaxFanSpeed function as declared in nvml/nvml.h +func nvmlDeviceGetMinMaxFanSpeed(nvmlDevice nvmlDevice, MinSpeed *uint32, MaxSpeed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinSpeed, _ := (*C.uint)(unsafe.Pointer(MinSpeed)), cgoAllocsUnknown + cMaxSpeed, _ := (*C.uint)(unsafe.Pointer(MaxSpeed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMinMaxFanSpeed(cnvmlDevice, cMinSpeed, cMaxSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFanControlPolicy_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetFanControlPolicy_v2(nvmlDevice nvmlDevice, Fan uint32, Policy *FanControlPolicy) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + cPolicy, _ := (*C.nvmlFanControlPolicy_t)(unsafe.Pointer(Policy)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFanControlPolicy_v2(cnvmlDevice, cFan, cPolicy) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNumFans function as declared in nvml/nvml.h +func nvmlDeviceGetNumFans(nvmlDevice nvmlDevice, NumFans *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cNumFans, _ := (*C.uint)(unsafe.Pointer(NumFans)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNumFans(cnvmlDevice, cNumFans) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTemperature function as declared in nvml/nvml.h +func nvmlDeviceGetTemperature(nvmlDevice nvmlDevice, SensorType TemperatureSensors, Temp *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSensorType, _ := (C.nvmlTemperatureSensors_t)(SensorType), cgoAllocsUnknown + cTemp, _ := (*C.uint)(unsafe.Pointer(Temp)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTemperature(cnvmlDevice, cSensorType, cTemp) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCoolerInfo function as declared in nvml/nvml.h +func nvmlDeviceGetCoolerInfo(nvmlDevice nvmlDevice, CoolerInfo *CoolerInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCoolerInfo, _ := (*C.nvmlCoolerInfo_t)(unsafe.Pointer(CoolerInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCoolerInfo(cnvmlDevice, cCoolerInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTemperatureV function as declared in nvml/nvml.h +func nvmlDeviceGetTemperatureV(nvmlDevice nvmlDevice, Temperature *Temperature) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cTemperature, _ := (*C.nvmlTemperature_t)(unsafe.Pointer(Temperature)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTemperatureV(cnvmlDevice, cTemperature) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTemperatureThreshold function as declared in nvml/nvml.h +func nvmlDeviceGetTemperatureThreshold(nvmlDevice nvmlDevice, ThresholdType TemperatureThresholds, Temp *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cThresholdType, _ := (C.nvmlTemperatureThresholds_t)(ThresholdType), cgoAllocsUnknown + cTemp, _ := (*C.uint)(unsafe.Pointer(Temp)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTemperatureThreshold(cnvmlDevice, cThresholdType, cTemp) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMarginTemperature function as declared in nvml/nvml.h +func nvmlDeviceGetMarginTemperature(nvmlDevice nvmlDevice, MarginTempInfo *MarginTemperature) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMarginTempInfo, _ := (*C.nvmlMarginTemperature_t)(unsafe.Pointer(MarginTempInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMarginTemperature(cnvmlDevice, cMarginTempInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetThermalSettings function as declared in nvml/nvml.h +func nvmlDeviceGetThermalSettings(nvmlDevice nvmlDevice, SensorIndex uint32, PThermalSettings *GpuThermalSettings) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSensorIndex, _ := (C.uint)(SensorIndex), cgoAllocsUnknown + cPThermalSettings, _ := (*C.nvmlGpuThermalSettings_t)(unsafe.Pointer(PThermalSettings)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetThermalSettings(cnvmlDevice, cSensorIndex, cPThermalSettings) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPerformanceState function as declared in nvml/nvml.h +func nvmlDeviceGetPerformanceState(nvmlDevice nvmlDevice, PState *Pstates) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPState, _ := (*C.nvmlPstates_t)(unsafe.Pointer(PState)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPerformanceState(cnvmlDevice, cPState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCurrentClocksEventReasons function as declared in nvml/nvml.h +func nvmlDeviceGetCurrentClocksEventReasons(nvmlDevice nvmlDevice, ClocksEventReasons *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClocksEventReasons, _ := (*C.ulonglong)(unsafe.Pointer(ClocksEventReasons)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCurrentClocksEventReasons(cnvmlDevice, cClocksEventReasons) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCurrentClocksThrottleReasons function as declared in nvml/nvml.h +func nvmlDeviceGetCurrentClocksThrottleReasons(nvmlDevice nvmlDevice, ClocksThrottleReasons *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cClocksThrottleReasons, _ := (*C.ulonglong)(unsafe.Pointer(ClocksThrottleReasons)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCurrentClocksThrottleReasons(cnvmlDevice, cClocksThrottleReasons) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedClocksEventReasons function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedClocksEventReasons(nvmlDevice nvmlDevice, SupportedClocksEventReasons *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSupportedClocksEventReasons, _ := (*C.ulonglong)(unsafe.Pointer(SupportedClocksEventReasons)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedClocksEventReasons(cnvmlDevice, cSupportedClocksEventReasons) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedClocksThrottleReasons function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedClocksThrottleReasons(nvmlDevice nvmlDevice, SupportedClocksThrottleReasons *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSupportedClocksThrottleReasons, _ := (*C.ulonglong)(unsafe.Pointer(SupportedClocksThrottleReasons)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedClocksThrottleReasons(cnvmlDevice, cSupportedClocksThrottleReasons) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerState function as declared in nvml/nvml.h +func nvmlDeviceGetPowerState(nvmlDevice nvmlDevice, PState *Pstates) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPState, _ := (*C.nvmlPstates_t)(unsafe.Pointer(PState)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerState(cnvmlDevice, cPState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDynamicPstatesInfo function as declared in nvml/nvml.h +func nvmlDeviceGetDynamicPstatesInfo(nvmlDevice nvmlDevice, PDynamicPstatesInfo *GpuDynamicPstatesInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPDynamicPstatesInfo, _ := (*C.nvmlGpuDynamicPstatesInfo_t)(unsafe.Pointer(PDynamicPstatesInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDynamicPstatesInfo(cnvmlDevice, cPDynamicPstatesInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemClkVfOffset function as declared in nvml/nvml.h +func nvmlDeviceGetMemClkVfOffset(nvmlDevice nvmlDevice, Offset *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cOffset, _ := (*C.int)(unsafe.Pointer(Offset)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemClkVfOffset(cnvmlDevice, cOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMinMaxClockOfPState function as declared in nvml/nvml.h +func nvmlDeviceGetMinMaxClockOfPState(nvmlDevice nvmlDevice, _type ClockType, Pstate Pstates, MinClockMHz *uint32, MaxClockMHz *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (C.nvmlClockType_t)(_type), cgoAllocsUnknown + cPstate, _ := (C.nvmlPstates_t)(Pstate), cgoAllocsUnknown + cMinClockMHz, _ := (*C.uint)(unsafe.Pointer(MinClockMHz)), cgoAllocsUnknown + cMaxClockMHz, _ := (*C.uint)(unsafe.Pointer(MaxClockMHz)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMinMaxClockOfPState(cnvmlDevice, c_type, cPstate, cMinClockMHz, cMaxClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedPerformanceStates function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedPerformanceStates(nvmlDevice nvmlDevice, Pstates *Pstates, Size uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPstates, _ := (*C.nvmlPstates_t)(unsafe.Pointer(Pstates)), cgoAllocsUnknown + cSize, _ := (C.uint)(Size), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedPerformanceStates(cnvmlDevice, cPstates, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpcClkMinMaxVfOffset function as declared in nvml/nvml.h +func nvmlDeviceGetGpcClkMinMaxVfOffset(nvmlDevice nvmlDevice, MinOffset *int32, MaxOffset *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinOffset, _ := (*C.int)(unsafe.Pointer(MinOffset)), cgoAllocsUnknown + cMaxOffset, _ := (*C.int)(unsafe.Pointer(MaxOffset)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpcClkMinMaxVfOffset(cnvmlDevice, cMinOffset, cMaxOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemClkMinMaxVfOffset function as declared in nvml/nvml.h +func nvmlDeviceGetMemClkMinMaxVfOffset(nvmlDevice nvmlDevice, MinOffset *int32, MaxOffset *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinOffset, _ := (*C.int)(unsafe.Pointer(MinOffset)), cgoAllocsUnknown + cMaxOffset, _ := (*C.int)(unsafe.Pointer(MaxOffset)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemClkMinMaxVfOffset(cnvmlDevice, cMinOffset, cMaxOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetClockOffsets function as declared in nvml/nvml.h +func nvmlDeviceGetClockOffsets(nvmlDevice nvmlDevice, Info *ClockOffset) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlClockOffset_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetClockOffsets(cnvmlDevice, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetClockOffsets function as declared in nvml/nvml.h +func nvmlDeviceSetClockOffsets(nvmlDevice nvmlDevice, Info *ClockOffset) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlClockOffset_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetClockOffsets(cnvmlDevice, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPerformanceModes function as declared in nvml/nvml.h +func nvmlDeviceGetPerformanceModes(nvmlDevice nvmlDevice, PerfModes *DevicePerfModes) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPerfModes, _ := (*C.nvmlDevicePerfModes_t)(unsafe.Pointer(PerfModes)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPerformanceModes(cnvmlDevice, cPerfModes) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCurrentClockFreqs function as declared in nvml/nvml.h +func nvmlDeviceGetCurrentClockFreqs(nvmlDevice nvmlDevice, CurrentClockFreqs *DeviceCurrentClockFreqs) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrentClockFreqs, _ := (*C.nvmlDeviceCurrentClockFreqs_t)(unsafe.Pointer(CurrentClockFreqs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCurrentClockFreqs(cnvmlDevice, cCurrentClockFreqs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerManagementMode function as declared in nvml/nvml.h +func nvmlDeviceGetPowerManagementMode(nvmlDevice nvmlDevice, Mode *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerManagementMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerManagementLimit function as declared in nvml/nvml.h +func nvmlDeviceGetPowerManagementLimit(nvmlDevice nvmlDevice, Limit *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLimit, _ := (*C.uint)(unsafe.Pointer(Limit)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerManagementLimit(cnvmlDevice, cLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerManagementLimitConstraints function as declared in nvml/nvml.h +func nvmlDeviceGetPowerManagementLimitConstraints(nvmlDevice nvmlDevice, MinLimit *uint32, MaxLimit *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinLimit, _ := (*C.uint)(unsafe.Pointer(MinLimit)), cgoAllocsUnknown + cMaxLimit, _ := (*C.uint)(unsafe.Pointer(MaxLimit)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerManagementLimitConstraints(cnvmlDevice, cMinLimit, cMaxLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerManagementDefaultLimit function as declared in nvml/nvml.h +func nvmlDeviceGetPowerManagementDefaultLimit(nvmlDevice nvmlDevice, DefaultLimit *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cDefaultLimit, _ := (*C.uint)(unsafe.Pointer(DefaultLimit)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerManagementDefaultLimit(cnvmlDevice, cDefaultLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerUsage function as declared in nvml/nvml.h +func nvmlDeviceGetPowerUsage(nvmlDevice nvmlDevice, Power *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPower, _ := (*C.uint)(unsafe.Pointer(Power)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerUsage(cnvmlDevice, cPower) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerMizerMode_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetPowerMizerMode_v1(nvmlDevice nvmlDevice, PowerMizerMode *DevicePowerMizerModes_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPowerMizerMode, _ := (*C.nvmlDevicePowerMizerModes_v1_t)(unsafe.Pointer(PowerMizerMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerMizerMode_v1(cnvmlDevice, cPowerMizerMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetPowerMizerMode_v1 function as declared in nvml/nvml.h +func nvmlDeviceSetPowerMizerMode_v1(nvmlDevice nvmlDevice, PowerMizerMode *DevicePowerMizerModes_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPowerMizerMode, _ := (*C.nvmlDevicePowerMizerModes_v1_t)(unsafe.Pointer(PowerMizerMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetPowerMizerMode_v1(cnvmlDevice, cPowerMizerMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTotalEnergyConsumption function as declared in nvml/nvml.h +func nvmlDeviceGetTotalEnergyConsumption(nvmlDevice nvmlDevice, Energy *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEnergy, _ := (*C.ulonglong)(unsafe.Pointer(Energy)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTotalEnergyConsumption(cnvmlDevice, cEnergy) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEnforcedPowerLimit function as declared in nvml/nvml.h +func nvmlDeviceGetEnforcedPowerLimit(nvmlDevice nvmlDevice, Limit *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLimit, _ := (*C.uint)(unsafe.Pointer(Limit)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEnforcedPowerLimit(cnvmlDevice, cLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuOperationMode function as declared in nvml/nvml.h +func nvmlDeviceGetGpuOperationMode(nvmlDevice nvmlDevice, Current *GpuOperationMode, Pending *GpuOperationMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlGpuOperationMode_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + cPending, _ := (*C.nvmlGpuOperationMode_t)(unsafe.Pointer(Pending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuOperationMode(cnvmlDevice, cCurrent, cPending) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemoryInfo function as declared in nvml/nvml.h +func nvmlDeviceGetMemoryInfo(nvmlDevice nvmlDevice, Memory *Memory) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemory, _ := (*C.nvmlMemory_t)(unsafe.Pointer(Memory)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemoryInfo(cnvmlDevice, cMemory) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemoryInfo_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetMemoryInfo_v2(nvmlDevice nvmlDevice, Memory *Memory_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemory, _ := (*C.nvmlMemory_v2_t)(unsafe.Pointer(Memory)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemoryInfo_v2(cnvmlDevice, cMemory) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetComputeMode function as declared in nvml/nvml.h +func nvmlDeviceGetComputeMode(nvmlDevice nvmlDevice, Mode *ComputeMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (*C.nvmlComputeMode_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetComputeMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCudaComputeCapability function as declared in nvml/nvml.h +func nvmlDeviceGetCudaComputeCapability(nvmlDevice nvmlDevice, Major *int32, Minor *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMajor, _ := (*C.int)(unsafe.Pointer(Major)), cgoAllocsUnknown + cMinor, _ := (*C.int)(unsafe.Pointer(Minor)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCudaComputeCapability(cnvmlDevice, cMajor, cMinor) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDramEncryptionMode function as declared in nvml/nvml.h +func nvmlDeviceGetDramEncryptionMode(nvmlDevice nvmlDevice, Current *DramEncryptionInfo, Pending *DramEncryptionInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlDramEncryptionInfo_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + cPending, _ := (*C.nvmlDramEncryptionInfo_t)(unsafe.Pointer(Pending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDramEncryptionMode(cnvmlDevice, cCurrent, cPending) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetDramEncryptionMode function as declared in nvml/nvml.h +func nvmlDeviceSetDramEncryptionMode(nvmlDevice nvmlDevice, DramEncryption *DramEncryptionInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cDramEncryption, _ := (*C.nvmlDramEncryptionInfo_t)(unsafe.Pointer(DramEncryption)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetDramEncryptionMode(cnvmlDevice, cDramEncryption) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEccMode function as declared in nvml/nvml.h +func nvmlDeviceGetEccMode(nvmlDevice nvmlDevice, Current *EnableState, Pending *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + cPending, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Pending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEccMode(cnvmlDevice, cCurrent, cPending) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDefaultEccMode function as declared in nvml/nvml.h +func nvmlDeviceGetDefaultEccMode(nvmlDevice nvmlDevice, DefaultMode *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cDefaultMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(DefaultMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDefaultEccMode(cnvmlDevice, cDefaultMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBoardId function as declared in nvml/nvml.h +func nvmlDeviceGetBoardId(nvmlDevice nvmlDevice, BoardId *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBoardId, _ := (*C.uint)(unsafe.Pointer(BoardId)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBoardId(cnvmlDevice, cBoardId) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMultiGpuBoard function as declared in nvml/nvml.h +func nvmlDeviceGetMultiGpuBoard(nvmlDevice nvmlDevice, MultiGpuBool *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMultiGpuBool, _ := (*C.uint)(unsafe.Pointer(MultiGpuBool)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMultiGpuBoard(cnvmlDevice, cMultiGpuBool) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetTotalEccErrors function as declared in nvml/nvml.h +func nvmlDeviceGetTotalEccErrors(nvmlDevice nvmlDevice, ErrorType MemoryErrorType, CounterType EccCounterType, EccCounts *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cErrorType, _ := (C.nvmlMemoryErrorType_t)(ErrorType), cgoAllocsUnknown + cCounterType, _ := (C.nvmlEccCounterType_t)(CounterType), cgoAllocsUnknown + cEccCounts, _ := (*C.ulonglong)(unsafe.Pointer(EccCounts)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetTotalEccErrors(cnvmlDevice, cErrorType, cCounterType, cEccCounts) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDetailedEccErrors function as declared in nvml/nvml.h +func nvmlDeviceGetDetailedEccErrors(nvmlDevice nvmlDevice, ErrorType MemoryErrorType, CounterType EccCounterType, EccCounts *EccErrorCounts) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cErrorType, _ := (C.nvmlMemoryErrorType_t)(ErrorType), cgoAllocsUnknown + cCounterType, _ := (C.nvmlEccCounterType_t)(CounterType), cgoAllocsUnknown + cEccCounts, _ := (*C.nvmlEccErrorCounts_t)(unsafe.Pointer(EccCounts)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDetailedEccErrors(cnvmlDevice, cErrorType, cCounterType, cEccCounts) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemoryErrorCounter function as declared in nvml/nvml.h +func nvmlDeviceGetMemoryErrorCounter(nvmlDevice nvmlDevice, ErrorType MemoryErrorType, CounterType EccCounterType, LocationType MemoryLocation, Count *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cErrorType, _ := (C.nvmlMemoryErrorType_t)(ErrorType), cgoAllocsUnknown + cCounterType, _ := (C.nvmlEccCounterType_t)(CounterType), cgoAllocsUnknown + cLocationType, _ := (C.nvmlMemoryLocation_t)(LocationType), cgoAllocsUnknown + cCount, _ := (*C.ulonglong)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemoryErrorCounter(cnvmlDevice, cErrorType, cCounterType, cLocationType, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetUtilizationRates function as declared in nvml/nvml.h +func nvmlDeviceGetUtilizationRates(nvmlDevice nvmlDevice, Utilization *Utilization) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.nvmlUtilization_t)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetUtilizationRates(cnvmlDevice, cUtilization) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEncoderUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetEncoderUtilization(nvmlDevice nvmlDevice, Utilization *uint32, SamplingPeriodUs *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.uint)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + cSamplingPeriodUs, _ := (*C.uint)(unsafe.Pointer(SamplingPeriodUs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEncoderUtilization(cnvmlDevice, cUtilization, cSamplingPeriodUs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEncoderCapacity function as declared in nvml/nvml.h +func nvmlDeviceGetEncoderCapacity(nvmlDevice nvmlDevice, EncoderQueryType EncoderType, EncoderCapacity *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEncoderQueryType, _ := (C.nvmlEncoderType_t)(EncoderQueryType), cgoAllocsUnknown + cEncoderCapacity, _ := (*C.uint)(unsafe.Pointer(EncoderCapacity)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEncoderCapacity(cnvmlDevice, cEncoderQueryType, cEncoderCapacity) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEncoderStats function as declared in nvml/nvml.h +func nvmlDeviceGetEncoderStats(nvmlDevice nvmlDevice, SessionCount *uint32, AverageFps *uint32, AverageLatency *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cAverageFps, _ := (*C.uint)(unsafe.Pointer(AverageFps)), cgoAllocsUnknown + cAverageLatency, _ := (*C.uint)(unsafe.Pointer(AverageLatency)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEncoderStats(cnvmlDevice, cSessionCount, cAverageFps, cAverageLatency) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetEncoderSessions function as declared in nvml/nvml.h +func nvmlDeviceGetEncoderSessions(nvmlDevice nvmlDevice, SessionCount *uint32, SessionInfos *EncoderSessionInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cSessionInfos, _ := (*C.nvmlEncoderSessionInfo_t)(unsafe.Pointer(SessionInfos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetEncoderSessions(cnvmlDevice, cSessionCount, cSessionInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDecoderUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetDecoderUtilization(nvmlDevice nvmlDevice, Utilization *uint32, SamplingPeriodUs *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.uint)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + cSamplingPeriodUs, _ := (*C.uint)(unsafe.Pointer(SamplingPeriodUs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDecoderUtilization(cnvmlDevice, cUtilization, cSamplingPeriodUs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetJpgUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetJpgUtilization(nvmlDevice nvmlDevice, Utilization *uint32, SamplingPeriodUs *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.uint)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + cSamplingPeriodUs, _ := (*C.uint)(unsafe.Pointer(SamplingPeriodUs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetJpgUtilization(cnvmlDevice, cUtilization, cSamplingPeriodUs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetOfaUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetOfaUtilization(nvmlDevice nvmlDevice, Utilization *uint32, SamplingPeriodUs *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.uint)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + cSamplingPeriodUs, _ := (*C.uint)(unsafe.Pointer(SamplingPeriodUs)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetOfaUtilization(cnvmlDevice, cUtilization, cSamplingPeriodUs) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFBCStats function as declared in nvml/nvml.h +func nvmlDeviceGetFBCStats(nvmlDevice nvmlDevice, FbcStats *FBCStats) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFbcStats, _ := (*C.nvmlFBCStats_t)(unsafe.Pointer(FbcStats)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFBCStats(cnvmlDevice, cFbcStats) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFBCSessions function as declared in nvml/nvml.h +func nvmlDeviceGetFBCSessions(nvmlDevice nvmlDevice, SessionCount *uint32, SessionInfo *FBCSessionInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cSessionInfo, _ := (*C.nvmlFBCSessionInfo_t)(unsafe.Pointer(SessionInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFBCSessions(cnvmlDevice, cSessionCount, cSessionInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDriverModel_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetDriverModel_v2(nvmlDevice nvmlDevice, Current *DriverModel, Pending *DriverModel) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlDriverModel_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + cPending, _ := (*C.nvmlDriverModel_t)(unsafe.Pointer(Pending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDriverModel_v2(cnvmlDevice, cCurrent, cPending) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVbiosVersion function as declared in nvml/nvml.h +func nvmlDeviceGetVbiosVersion(nvmlDevice nvmlDevice, Version *byte, Length uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVbiosVersion(cnvmlDevice, cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBridgeChipInfo function as declared in nvml/nvml.h +func nvmlDeviceGetBridgeChipInfo(nvmlDevice nvmlDevice, BridgeHierarchy *BridgeChipHierarchy) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBridgeHierarchy, _ := (*C.nvmlBridgeChipHierarchy_t)(unsafe.Pointer(BridgeHierarchy)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBridgeChipInfo(cnvmlDevice, cBridgeHierarchy) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetComputeRunningProcesses_v3 function as declared in nvml/nvml.h +func nvmlDeviceGetComputeRunningProcesses_v3(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetComputeRunningProcesses_v3(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGraphicsRunningProcesses_v3 function as declared in nvml/nvml.h +func nvmlDeviceGetGraphicsRunningProcesses_v3(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGraphicsRunningProcesses_v3(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMPSComputeRunningProcesses_v3 function as declared in nvml/nvml.h +func nvmlDeviceGetMPSComputeRunningProcesses_v3(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMPSComputeRunningProcesses_v3(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRunningProcessDetailList function as declared in nvml/nvml.h +func nvmlDeviceGetRunningProcessDetailList(nvmlDevice nvmlDevice, Plist *ProcessDetailList) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPlist, _ := (*C.nvmlProcessDetailList_t)(unsafe.Pointer(Plist)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRunningProcessDetailList(cnvmlDevice, cPlist) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceOnSameBoard function as declared in nvml/nvml.h +func nvmlDeviceOnSameBoard(Device1 nvmlDevice, Device2 nvmlDevice, OnSameBoard *int32) Return { + cDevice1, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device1)), cgoAllocsUnknown + cDevice2, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&Device2)), cgoAllocsUnknown + cOnSameBoard, _ := (*C.int)(unsafe.Pointer(OnSameBoard)), cgoAllocsUnknown + __ret := C.nvmlDeviceOnSameBoard(cDevice1, cDevice2, cOnSameBoard) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAPIRestriction function as declared in nvml/nvml.h +func nvmlDeviceGetAPIRestriction(nvmlDevice nvmlDevice, ApiType RestrictedAPI, IsRestricted *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cApiType, _ := (C.nvmlRestrictedAPI_t)(ApiType), cgoAllocsUnknown + cIsRestricted, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(IsRestricted)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAPIRestriction(cnvmlDevice, cApiType, cIsRestricted) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSamples function as declared in nvml/nvml.h +func nvmlDeviceGetSamples(nvmlDevice nvmlDevice, _type SamplingType, LastSeenTimeStamp uint64, SampleValType *ValueType, SampleCount *uint32, Samples *Sample) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (C.nvmlSamplingType_t)(_type), cgoAllocsUnknown + cLastSeenTimeStamp, _ := (C.ulonglong)(LastSeenTimeStamp), cgoAllocsUnknown + cSampleValType, _ := (*C.nvmlValueType_t)(unsafe.Pointer(SampleValType)), cgoAllocsUnknown + cSampleCount, _ := (*C.uint)(unsafe.Pointer(SampleCount)), cgoAllocsUnknown + cSamples, _ := (*C.nvmlSample_t)(unsafe.Pointer(Samples)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSamples(cnvmlDevice, c_type, cLastSeenTimeStamp, cSampleValType, cSampleCount, cSamples) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBAR1MemoryInfo function as declared in nvml/nvml.h +func nvmlDeviceGetBAR1MemoryInfo(nvmlDevice nvmlDevice, Bar1Memory *BAR1Memory) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBar1Memory, _ := (*C.nvmlBAR1Memory_t)(unsafe.Pointer(Bar1Memory)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBAR1MemoryInfo(cnvmlDevice, cBar1Memory) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetViolationStatus function as declared in nvml/nvml.h +func nvmlDeviceGetViolationStatus(nvmlDevice nvmlDevice, PerfPolicyType PerfPolicyType, ViolTime *ViolationTime) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPerfPolicyType, _ := (C.nvmlPerfPolicyType_t)(PerfPolicyType), cgoAllocsUnknown + cViolTime, _ := (*C.nvmlViolationTime_t)(unsafe.Pointer(ViolTime)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetViolationStatus(cnvmlDevice, cPerfPolicyType, cViolTime) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetIrqNum function as declared in nvml/nvml.h +func nvmlDeviceGetIrqNum(nvmlDevice nvmlDevice, IrqNum *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIrqNum, _ := (*C.uint)(unsafe.Pointer(IrqNum)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetIrqNum(cnvmlDevice, cIrqNum) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNumGpuCores function as declared in nvml/nvml.h +func nvmlDeviceGetNumGpuCores(nvmlDevice nvmlDevice, NumCores *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cNumCores, _ := (*C.uint)(unsafe.Pointer(NumCores)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNumGpuCores(cnvmlDevice, cNumCores) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPowerSource function as declared in nvml/nvml.h +func nvmlDeviceGetPowerSource(nvmlDevice nvmlDevice, PowerSource *PowerSource) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPowerSource, _ := (*C.nvmlPowerSource_t)(unsafe.Pointer(PowerSource)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPowerSource(cnvmlDevice, cPowerSource) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMemoryBusWidth function as declared in nvml/nvml.h +func nvmlDeviceGetMemoryBusWidth(nvmlDevice nvmlDevice, BusWidth *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBusWidth, _ := (*C.uint)(unsafe.Pointer(BusWidth)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMemoryBusWidth(cnvmlDevice, cBusWidth) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPcieLinkMaxSpeed function as declared in nvml/nvml.h +func nvmlDeviceGetPcieLinkMaxSpeed(nvmlDevice nvmlDevice, MaxSpeed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMaxSpeed, _ := (*C.uint)(unsafe.Pointer(MaxSpeed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPcieLinkMaxSpeed(cnvmlDevice, cMaxSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPcieSpeed function as declared in nvml/nvml.h +func nvmlDeviceGetPcieSpeed(nvmlDevice nvmlDevice, PcieSpeed *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPcieSpeed, _ := (*C.uint)(unsafe.Pointer(PcieSpeed)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPcieSpeed(cnvmlDevice, cPcieSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAdaptiveClockInfoStatus function as declared in nvml/nvml.h +func nvmlDeviceGetAdaptiveClockInfoStatus(nvmlDevice nvmlDevice, AdaptiveClockStatus *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cAdaptiveClockStatus, _ := (*C.uint)(unsafe.Pointer(AdaptiveClockStatus)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAdaptiveClockInfoStatus(cnvmlDevice, cAdaptiveClockStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetBusType function as declared in nvml/nvml.h +func nvmlDeviceGetBusType(nvmlDevice nvmlDevice, _type *BusType) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + c_type, _ := (*C.nvmlBusType_t)(unsafe.Pointer(_type)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetBusType(cnvmlDevice, c_type) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuFabricInfo function as declared in nvml/nvml.h +func nvmlDeviceGetGpuFabricInfo(nvmlDevice nvmlDevice, GpuFabricInfo *GpuFabricInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpuFabricInfo, _ := (*C.nvmlGpuFabricInfo_t)(unsafe.Pointer(GpuFabricInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuFabricInfo(cnvmlDevice, cGpuFabricInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuFabricInfoV function as declared in nvml/nvml.h +func nvmlDeviceGetGpuFabricInfoV(nvmlDevice nvmlDevice, GpuFabricInfo *GpuFabricInfoV) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpuFabricInfo, _ := (*C.nvmlGpuFabricInfoV_t)(unsafe.Pointer(GpuFabricInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuFabricInfoV(cnvmlDevice, cGpuFabricInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetConfComputeCapabilities function as declared in nvml/nvml.h +func nvmlSystemGetConfComputeCapabilities(Capabilities *ConfComputeSystemCaps) Return { + cCapabilities, _ := (*C.nvmlConfComputeSystemCaps_t)(unsafe.Pointer(Capabilities)), cgoAllocsUnknown + __ret := C.nvmlSystemGetConfComputeCapabilities(cCapabilities) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetConfComputeState function as declared in nvml/nvml.h +func nvmlSystemGetConfComputeState(State *ConfComputeSystemState) Return { + cState, _ := (*C.nvmlConfComputeSystemState_t)(unsafe.Pointer(State)), cgoAllocsUnknown + __ret := C.nvmlSystemGetConfComputeState(cState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetConfComputeMemSizeInfo function as declared in nvml/nvml.h +func nvmlDeviceGetConfComputeMemSizeInfo(nvmlDevice nvmlDevice, MemInfo *ConfComputeMemSizeInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemInfo, _ := (*C.nvmlConfComputeMemSizeInfo_t)(unsafe.Pointer(MemInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetConfComputeMemSizeInfo(cnvmlDevice, cMemInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetConfComputeGpusReadyState function as declared in nvml/nvml.h +func nvmlSystemGetConfComputeGpusReadyState(IsAcceptingWork *uint32) Return { + cIsAcceptingWork, _ := (*C.uint)(unsafe.Pointer(IsAcceptingWork)), cgoAllocsUnknown + __ret := C.nvmlSystemGetConfComputeGpusReadyState(cIsAcceptingWork) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetConfComputeProtectedMemoryUsage function as declared in nvml/nvml.h +func nvmlDeviceGetConfComputeProtectedMemoryUsage(nvmlDevice nvmlDevice, Memory *Memory) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemory, _ := (*C.nvmlMemory_t)(unsafe.Pointer(Memory)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetConfComputeProtectedMemoryUsage(cnvmlDevice, cMemory) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetConfComputeGpuCertificate function as declared in nvml/nvml.h +func nvmlDeviceGetConfComputeGpuCertificate(nvmlDevice nvmlDevice, GpuCert *ConfComputeGpuCertificate) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpuCert, _ := (*C.nvmlConfComputeGpuCertificate_t)(unsafe.Pointer(GpuCert)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetConfComputeGpuCertificate(cnvmlDevice, cGpuCert) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetConfComputeGpuAttestationReport function as declared in nvml/nvml.h +func nvmlDeviceGetConfComputeGpuAttestationReport(nvmlDevice nvmlDevice, GpuAtstReport *ConfComputeGpuAttestationReport) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpuAtstReport, _ := (*C.nvmlConfComputeGpuAttestationReport_t)(unsafe.Pointer(GpuAtstReport)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetConfComputeGpuAttestationReport(cnvmlDevice, cGpuAtstReport) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetConfComputeKeyRotationThresholdInfo function as declared in nvml/nvml.h +func nvmlSystemGetConfComputeKeyRotationThresholdInfo(PKeyRotationThrInfo *ConfComputeGetKeyRotationThresholdInfo) Return { + cPKeyRotationThrInfo, _ := (*C.nvmlConfComputeGetKeyRotationThresholdInfo_t)(unsafe.Pointer(PKeyRotationThrInfo)), cgoAllocsUnknown + __ret := C.nvmlSystemGetConfComputeKeyRotationThresholdInfo(cPKeyRotationThrInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetConfComputeUnprotectedMemSize function as declared in nvml/nvml.h +func nvmlDeviceSetConfComputeUnprotectedMemSize(nvmlDevice nvmlDevice, SizeKiB uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSizeKiB, _ := (C.ulonglong)(SizeKiB), cgoAllocsUnknown + __ret := C.nvmlDeviceSetConfComputeUnprotectedMemSize(cnvmlDevice, cSizeKiB) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemSetConfComputeGpusReadyState function as declared in nvml/nvml.h +func nvmlSystemSetConfComputeGpusReadyState(IsAcceptingWork uint32) Return { + cIsAcceptingWork, _ := (C.uint)(IsAcceptingWork), cgoAllocsUnknown + __ret := C.nvmlSystemSetConfComputeGpusReadyState(cIsAcceptingWork) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemSetConfComputeKeyRotationThresholdInfo function as declared in nvml/nvml.h +func nvmlSystemSetConfComputeKeyRotationThresholdInfo(PKeyRotationThrInfo *ConfComputeSetKeyRotationThresholdInfo) Return { + cPKeyRotationThrInfo, _ := (*C.nvmlConfComputeSetKeyRotationThresholdInfo_t)(unsafe.Pointer(PKeyRotationThrInfo)), cgoAllocsUnknown + __ret := C.nvmlSystemSetConfComputeKeyRotationThresholdInfo(cPKeyRotationThrInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetConfComputeSettings function as declared in nvml/nvml.h +func nvmlSystemGetConfComputeSettings(Settings *SystemConfComputeSettings) Return { + cSettings, _ := (*C.nvmlSystemConfComputeSettings_t)(unsafe.Pointer(Settings)), cgoAllocsUnknown + __ret := C.nvmlSystemGetConfComputeSettings(cSettings) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGspFirmwareVersion function as declared in nvml/nvml.h +func nvmlDeviceGetGspFirmwareVersion(nvmlDevice nvmlDevice, Version *byte) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGspFirmwareVersion(cnvmlDevice, cVersion) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGspFirmwareMode function as declared in nvml/nvml.h +func nvmlDeviceGetGspFirmwareMode(nvmlDevice nvmlDevice, IsEnabled *uint32, DefaultMode *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIsEnabled, _ := (*C.uint)(unsafe.Pointer(IsEnabled)), cgoAllocsUnknown + cDefaultMode, _ := (*C.uint)(unsafe.Pointer(DefaultMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGspFirmwareMode(cnvmlDevice, cIsEnabled, cDefaultMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSramEccErrorStatus function as declared in nvml/nvml.h +func nvmlDeviceGetSramEccErrorStatus(nvmlDevice nvmlDevice, Status *EccSramErrorStatus) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cStatus, _ := (*C.nvmlEccSramErrorStatus_t)(unsafe.Pointer(Status)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSramEccErrorStatus(cnvmlDevice, cStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetPowerManagementLimit_v2 function as declared in nvml/nvml.h +func nvmlDeviceSetPowerManagementLimit_v2(nvmlDevice nvmlDevice, PowerValue *PowerValue_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPowerValue, _ := (*C.nvmlPowerValue_v2_t)(unsafe.Pointer(PowerValue)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetPowerManagementLimit_v2(cnvmlDevice, cPowerValue) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAccountingMode function as declared in nvml/nvml.h +func nvmlDeviceGetAccountingMode(nvmlDevice nvmlDevice, Mode *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAccountingMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAccountingStats function as declared in nvml/nvml.h +func nvmlDeviceGetAccountingStats(nvmlDevice nvmlDevice, Pid uint32, Stats *AccountingStats) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPid, _ := (C.uint)(Pid), cgoAllocsUnknown + cStats, _ := (*C.nvmlAccountingStats_t)(unsafe.Pointer(Stats)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAccountingStats(cnvmlDevice, cPid, cStats) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAccountingPids function as declared in nvml/nvml.h +func nvmlDeviceGetAccountingPids(nvmlDevice nvmlDevice, Count *uint32, Pids *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cPids, _ := (*C.uint)(unsafe.Pointer(Pids)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAccountingPids(cnvmlDevice, cCount, cPids) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAccountingBufferSize function as declared in nvml/nvml.h +func nvmlDeviceGetAccountingBufferSize(nvmlDevice nvmlDevice, BufferSize *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBufferSize, _ := (*C.uint)(unsafe.Pointer(BufferSize)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAccountingBufferSize(cnvmlDevice, cBufferSize) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRetiredPages function as declared in nvml/nvml.h +func nvmlDeviceGetRetiredPages(nvmlDevice nvmlDevice, Cause PageRetirementCause, PageCount *uint32, Addresses *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCause, _ := (C.nvmlPageRetirementCause_t)(Cause), cgoAllocsUnknown + cPageCount, _ := (*C.uint)(unsafe.Pointer(PageCount)), cgoAllocsUnknown + cAddresses, _ := (*C.ulonglong)(unsafe.Pointer(Addresses)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRetiredPages(cnvmlDevice, cCause, cPageCount, cAddresses) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRetiredPages_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetRetiredPages_v2(nvmlDevice nvmlDevice, Cause PageRetirementCause, PageCount *uint32, Addresses *uint64, Timestamps *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCause, _ := (C.nvmlPageRetirementCause_t)(Cause), cgoAllocsUnknown + cPageCount, _ := (*C.uint)(unsafe.Pointer(PageCount)), cgoAllocsUnknown + cAddresses, _ := (*C.ulonglong)(unsafe.Pointer(Addresses)), cgoAllocsUnknown + cTimestamps, _ := (*C.ulonglong)(unsafe.Pointer(Timestamps)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRetiredPages_v2(cnvmlDevice, cCause, cPageCount, cAddresses, cTimestamps) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRetiredPagesPendingStatus function as declared in nvml/nvml.h +func nvmlDeviceGetRetiredPagesPendingStatus(nvmlDevice nvmlDevice, IsPending *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIsPending, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(IsPending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRetiredPagesPendingStatus(cnvmlDevice, cIsPending) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRemappedRows function as declared in nvml/nvml.h +func nvmlDeviceGetRemappedRows(nvmlDevice nvmlDevice, CorrRows *uint32, UncRows *uint32, IsPending *uint32, FailureOccurred *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCorrRows, _ := (*C.uint)(unsafe.Pointer(CorrRows)), cgoAllocsUnknown + cUncRows, _ := (*C.uint)(unsafe.Pointer(UncRows)), cgoAllocsUnknown + cIsPending, _ := (*C.uint)(unsafe.Pointer(IsPending)), cgoAllocsUnknown + cFailureOccurred, _ := (*C.uint)(unsafe.Pointer(FailureOccurred)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRemappedRows(cnvmlDevice, cCorrRows, cUncRows, cIsPending, cFailureOccurred) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetRowRemapperHistogram function as declared in nvml/nvml.h +func nvmlDeviceGetRowRemapperHistogram(nvmlDevice nvmlDevice, Values *RowRemapperHistogramValues) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cValues, _ := (*C.nvmlRowRemapperHistogramValues_t)(unsafe.Pointer(Values)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetRowRemapperHistogram(cnvmlDevice, cValues) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetArchitecture function as declared in nvml/nvml.h +func nvmlDeviceGetArchitecture(nvmlDevice nvmlDevice, Arch *DeviceArchitecture) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cArch, _ := (*C.nvmlDeviceArchitecture_t)(unsafe.Pointer(Arch)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetArchitecture(cnvmlDevice, cArch) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetClkMonStatus function as declared in nvml/nvml.h +func nvmlDeviceGetClkMonStatus(nvmlDevice nvmlDevice, Status *ClkMonStatus) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cStatus, _ := (*C.nvmlClkMonStatus_t)(unsafe.Pointer(Status)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetClkMonStatus(cnvmlDevice, cStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetProcessUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetProcessUtilization(nvmlDevice nvmlDevice, Utilization *ProcessUtilizationSample, ProcessSamplesCount *uint32, LastSeenTimeStamp uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cUtilization, _ := (*C.nvmlProcessUtilizationSample_t)(unsafe.Pointer(Utilization)), cgoAllocsUnknown + cProcessSamplesCount, _ := (*C.uint)(unsafe.Pointer(ProcessSamplesCount)), cgoAllocsUnknown + cLastSeenTimeStamp, _ := (C.ulonglong)(LastSeenTimeStamp), cgoAllocsUnknown + __ret := C.nvmlDeviceGetProcessUtilization(cnvmlDevice, cUtilization, cProcessSamplesCount, cLastSeenTimeStamp) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetProcessesUtilizationInfo function as declared in nvml/nvml.h +func nvmlDeviceGetProcessesUtilizationInfo(nvmlDevice nvmlDevice, ProcesesUtilInfo *ProcessesUtilizationInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProcesesUtilInfo, _ := (*C.nvmlProcessesUtilizationInfo_t)(unsafe.Pointer(ProcesesUtilInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetProcessesUtilizationInfo(cnvmlDevice, cProcesesUtilInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPlatformInfo function as declared in nvml/nvml.h +func nvmlDeviceGetPlatformInfo(nvmlDevice nvmlDevice, PlatformInfo *PlatformInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPlatformInfo, _ := (*C.nvmlPlatformInfo_t)(unsafe.Pointer(PlatformInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPlatformInfo(cnvmlDevice, cPlatformInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPdi function as declared in nvml/nvml.h +func nvmlDeviceGetPdi(nvmlDevice nvmlDevice, Pdi *Pdi) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPdi, _ := (*C.nvmlPdi_t)(unsafe.Pointer(Pdi)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPdi(cnvmlDevice, cPdi) + __v := (Return)(__ret) + return __v +} + +// nvmlUnitSetLedState function as declared in nvml/nvml.h +func nvmlUnitSetLedState(nvmlUnit nvmlUnit, Color LedColor) Return { + cnvmlUnit, _ := *(*C.nvmlUnit_t)(unsafe.Pointer(&nvmlUnit)), cgoAllocsUnknown + cColor, _ := (C.nvmlLedColor_t)(Color), cgoAllocsUnknown + __ret := C.nvmlUnitSetLedState(cnvmlUnit, cColor) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetPersistenceMode function as declared in nvml/nvml.h +func nvmlDeviceSetPersistenceMode(nvmlDevice nvmlDevice, Mode EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (C.nvmlEnableState_t)(Mode), cgoAllocsUnknown + __ret := C.nvmlDeviceSetPersistenceMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetComputeMode function as declared in nvml/nvml.h +func nvmlDeviceSetComputeMode(nvmlDevice nvmlDevice, Mode ComputeMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (C.nvmlComputeMode_t)(Mode), cgoAllocsUnknown + __ret := C.nvmlDeviceSetComputeMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetEccMode function as declared in nvml/nvml.h +func nvmlDeviceSetEccMode(nvmlDevice nvmlDevice, Ecc EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEcc, _ := (C.nvmlEnableState_t)(Ecc), cgoAllocsUnknown + __ret := C.nvmlDeviceSetEccMode(cnvmlDevice, cEcc) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceClearEccErrorCounts function as declared in nvml/nvml.h +func nvmlDeviceClearEccErrorCounts(nvmlDevice nvmlDevice, CounterType EccCounterType) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCounterType, _ := (C.nvmlEccCounterType_t)(CounterType), cgoAllocsUnknown + __ret := C.nvmlDeviceClearEccErrorCounts(cnvmlDevice, cCounterType) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetDriverModel function as declared in nvml/nvml.h +func nvmlDeviceSetDriverModel(nvmlDevice nvmlDevice, DriverModel DriverModel, Flags uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cDriverModel, _ := (C.nvmlDriverModel_t)(DriverModel), cgoAllocsUnknown + cFlags, _ := (C.uint)(Flags), cgoAllocsUnknown + __ret := C.nvmlDeviceSetDriverModel(cnvmlDevice, cDriverModel, cFlags) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetGpuLockedClocks function as declared in nvml/nvml.h +func nvmlDeviceSetGpuLockedClocks(nvmlDevice nvmlDevice, MinGpuClockMHz uint32, MaxGpuClockMHz uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinGpuClockMHz, _ := (C.uint)(MinGpuClockMHz), cgoAllocsUnknown + cMaxGpuClockMHz, _ := (C.uint)(MaxGpuClockMHz), cgoAllocsUnknown + __ret := C.nvmlDeviceSetGpuLockedClocks(cnvmlDevice, cMinGpuClockMHz, cMaxGpuClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceResetGpuLockedClocks function as declared in nvml/nvml.h +func nvmlDeviceResetGpuLockedClocks(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceResetGpuLockedClocks(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetMemoryLockedClocks function as declared in nvml/nvml.h +func nvmlDeviceSetMemoryLockedClocks(nvmlDevice nvmlDevice, MinMemClockMHz uint32, MaxMemClockMHz uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMinMemClockMHz, _ := (C.uint)(MinMemClockMHz), cgoAllocsUnknown + cMaxMemClockMHz, _ := (C.uint)(MaxMemClockMHz), cgoAllocsUnknown + __ret := C.nvmlDeviceSetMemoryLockedClocks(cnvmlDevice, cMinMemClockMHz, cMaxMemClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceResetMemoryLockedClocks function as declared in nvml/nvml.h +func nvmlDeviceResetMemoryLockedClocks(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceResetMemoryLockedClocks(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetApplicationsClocks function as declared in nvml/nvml.h +func nvmlDeviceSetApplicationsClocks(nvmlDevice nvmlDevice, MemClockMHz uint32, GraphicsClockMHz uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMemClockMHz, _ := (C.uint)(MemClockMHz), cgoAllocsUnknown + cGraphicsClockMHz, _ := (C.uint)(GraphicsClockMHz), cgoAllocsUnknown + __ret := C.nvmlDeviceSetApplicationsClocks(cnvmlDevice, cMemClockMHz, cGraphicsClockMHz) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceResetApplicationsClocks function as declared in nvml/nvml.h +func nvmlDeviceResetApplicationsClocks(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceResetApplicationsClocks(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetAutoBoostedClocksEnabled function as declared in nvml/nvml.h +func nvmlDeviceSetAutoBoostedClocksEnabled(nvmlDevice nvmlDevice, Enabled EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEnabled, _ := (C.nvmlEnableState_t)(Enabled), cgoAllocsUnknown + __ret := C.nvmlDeviceSetAutoBoostedClocksEnabled(cnvmlDevice, cEnabled) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetDefaultAutoBoostedClocksEnabled function as declared in nvml/nvml.h +func nvmlDeviceSetDefaultAutoBoostedClocksEnabled(nvmlDevice nvmlDevice, Enabled EnableState, Flags uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEnabled, _ := (C.nvmlEnableState_t)(Enabled), cgoAllocsUnknown + cFlags, _ := (C.uint)(Flags), cgoAllocsUnknown + __ret := C.nvmlDeviceSetDefaultAutoBoostedClocksEnabled(cnvmlDevice, cEnabled, cFlags) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetDefaultFanSpeed_v2 function as declared in nvml/nvml.h +func nvmlDeviceSetDefaultFanSpeed_v2(nvmlDevice nvmlDevice, Fan uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + __ret := C.nvmlDeviceSetDefaultFanSpeed_v2(cnvmlDevice, cFan) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetFanControlPolicy function as declared in nvml/nvml.h +func nvmlDeviceSetFanControlPolicy(nvmlDevice nvmlDevice, Fan uint32, Policy FanControlPolicy) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + cPolicy, _ := (C.nvmlFanControlPolicy_t)(Policy), cgoAllocsUnknown + __ret := C.nvmlDeviceSetFanControlPolicy(cnvmlDevice, cFan, cPolicy) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetTemperatureThreshold function as declared in nvml/nvml.h +func nvmlDeviceSetTemperatureThreshold(nvmlDevice nvmlDevice, ThresholdType TemperatureThresholds, Temp *int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cThresholdType, _ := (C.nvmlTemperatureThresholds_t)(ThresholdType), cgoAllocsUnknown + cTemp, _ := (*C.int)(unsafe.Pointer(Temp)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetTemperatureThreshold(cnvmlDevice, cThresholdType, cTemp) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetPowerManagementLimit function as declared in nvml/nvml.h +func nvmlDeviceSetPowerManagementLimit(nvmlDevice nvmlDevice, Limit uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLimit, _ := (C.uint)(Limit), cgoAllocsUnknown + __ret := C.nvmlDeviceSetPowerManagementLimit(cnvmlDevice, cLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetGpuOperationMode function as declared in nvml/nvml.h +func nvmlDeviceSetGpuOperationMode(nvmlDevice nvmlDevice, Mode GpuOperationMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (C.nvmlGpuOperationMode_t)(Mode), cgoAllocsUnknown + __ret := C.nvmlDeviceSetGpuOperationMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetAPIRestriction function as declared in nvml/nvml.h +func nvmlDeviceSetAPIRestriction(nvmlDevice nvmlDevice, ApiType RestrictedAPI, IsRestricted EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cApiType, _ := (C.nvmlRestrictedAPI_t)(ApiType), cgoAllocsUnknown + cIsRestricted, _ := (C.nvmlEnableState_t)(IsRestricted), cgoAllocsUnknown + __ret := C.nvmlDeviceSetAPIRestriction(cnvmlDevice, cApiType, cIsRestricted) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetFanSpeed_v2 function as declared in nvml/nvml.h +func nvmlDeviceSetFanSpeed_v2(nvmlDevice nvmlDevice, Fan uint32, Speed uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cFan, _ := (C.uint)(Fan), cgoAllocsUnknown + cSpeed, _ := (C.uint)(Speed), cgoAllocsUnknown + __ret := C.nvmlDeviceSetFanSpeed_v2(cnvmlDevice, cFan, cSpeed) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetGpcClkVfOffset function as declared in nvml/nvml.h +func nvmlDeviceSetGpcClkVfOffset(nvmlDevice nvmlDevice, Offset int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cOffset, _ := (C.int)(Offset), cgoAllocsUnknown + __ret := C.nvmlDeviceSetGpcClkVfOffset(cnvmlDevice, cOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetMemClkVfOffset function as declared in nvml/nvml.h +func nvmlDeviceSetMemClkVfOffset(nvmlDevice nvmlDevice, Offset int32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cOffset, _ := (C.int)(Offset), cgoAllocsUnknown + __ret := C.nvmlDeviceSetMemClkVfOffset(cnvmlDevice, cOffset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetAccountingMode function as declared in nvml/nvml.h +func nvmlDeviceSetAccountingMode(nvmlDevice nvmlDevice, Mode EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (C.nvmlEnableState_t)(Mode), cgoAllocsUnknown + __ret := C.nvmlDeviceSetAccountingMode(cnvmlDevice, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceClearAccountingPids function as declared in nvml/nvml.h +func nvmlDeviceClearAccountingPids(nvmlDevice nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceClearAccountingPids(cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkState function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkState(nvmlDevice nvmlDevice, Link uint32, IsActive *EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cIsActive, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(IsActive)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkState(cnvmlDevice, cLink, cIsActive) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkVersion function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkVersion(nvmlDevice nvmlDevice, Link uint32, Version *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cVersion, _ := (*C.uint)(unsafe.Pointer(Version)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkVersion(cnvmlDevice, cLink, cVersion) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkCapability function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkCapability(nvmlDevice nvmlDevice, Link uint32, Capability NvLinkCapability, CapResult *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCapability, _ := (C.nvmlNvLinkCapability_t)(Capability), cgoAllocsUnknown + cCapResult, _ := (*C.uint)(unsafe.Pointer(CapResult)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkCapability(cnvmlDevice, cLink, cCapability, cCapResult) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkRemotePciInfo_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkRemotePciInfo_v2(nvmlDevice nvmlDevice, Link uint32, Pci *PciInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkRemotePciInfo_v2(cnvmlDevice, cLink, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkErrorCounter function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkErrorCounter(nvmlDevice nvmlDevice, Link uint32, Counter NvLinkErrorCounter, CounterValue *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.nvmlNvLinkErrorCounter_t)(Counter), cgoAllocsUnknown + cCounterValue, _ := (*C.ulonglong)(unsafe.Pointer(CounterValue)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkErrorCounter(cnvmlDevice, cLink, cCounter, cCounterValue) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceResetNvLinkErrorCounters function as declared in nvml/nvml.h +func nvmlDeviceResetNvLinkErrorCounters(nvmlDevice nvmlDevice, Link uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + __ret := C.nvmlDeviceResetNvLinkErrorCounters(cnvmlDevice, cLink) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetNvLinkUtilizationControl function as declared in nvml/nvml.h +func nvmlDeviceSetNvLinkUtilizationControl(nvmlDevice nvmlDevice, Link uint32, Counter uint32, Control *NvLinkUtilizationControl, Reset uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.uint)(Counter), cgoAllocsUnknown + cControl, _ := (*C.nvmlNvLinkUtilizationControl_t)(unsafe.Pointer(Control)), cgoAllocsUnknown + cReset, _ := (C.uint)(Reset), cgoAllocsUnknown + __ret := C.nvmlDeviceSetNvLinkUtilizationControl(cnvmlDevice, cLink, cCounter, cControl, cReset) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkUtilizationControl function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkUtilizationControl(nvmlDevice nvmlDevice, Link uint32, Counter uint32, Control *NvLinkUtilizationControl) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.uint)(Counter), cgoAllocsUnknown + cControl, _ := (*C.nvmlNvLinkUtilizationControl_t)(unsafe.Pointer(Control)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkUtilizationControl(cnvmlDevice, cLink, cCounter, cControl) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkUtilizationCounter function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkUtilizationCounter(nvmlDevice nvmlDevice, Link uint32, Counter uint32, Rxcounter *uint64, Txcounter *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.uint)(Counter), cgoAllocsUnknown + cRxcounter, _ := (*C.ulonglong)(unsafe.Pointer(Rxcounter)), cgoAllocsUnknown + cTxcounter, _ := (*C.ulonglong)(unsafe.Pointer(Txcounter)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkUtilizationCounter(cnvmlDevice, cLink, cCounter, cRxcounter, cTxcounter) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceFreezeNvLinkUtilizationCounter function as declared in nvml/nvml.h +func nvmlDeviceFreezeNvLinkUtilizationCounter(nvmlDevice nvmlDevice, Link uint32, Counter uint32, Freeze EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.uint)(Counter), cgoAllocsUnknown + cFreeze, _ := (C.nvmlEnableState_t)(Freeze), cgoAllocsUnknown + __ret := C.nvmlDeviceFreezeNvLinkUtilizationCounter(cnvmlDevice, cLink, cCounter, cFreeze) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceResetNvLinkUtilizationCounter function as declared in nvml/nvml.h +func nvmlDeviceResetNvLinkUtilizationCounter(nvmlDevice nvmlDevice, Link uint32, Counter uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cCounter, _ := (C.uint)(Counter), cgoAllocsUnknown + __ret := C.nvmlDeviceResetNvLinkUtilizationCounter(cnvmlDevice, cLink, cCounter) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkRemoteDeviceType function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkRemoteDeviceType(nvmlDevice nvmlDevice, Link uint32, PNvLinkDeviceType *IntNvLinkDeviceType) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cPNvLinkDeviceType, _ := (*C.nvmlIntNvLinkDeviceType_t)(unsafe.Pointer(PNvLinkDeviceType)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkRemoteDeviceType(cnvmlDevice, cLink, cPNvLinkDeviceType) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetNvLinkDeviceLowPowerThreshold function as declared in nvml/nvml.h +func nvmlDeviceSetNvLinkDeviceLowPowerThreshold(nvmlDevice nvmlDevice, Info *NvLinkPowerThres) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlNvLinkPowerThres_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetNvLinkDeviceLowPowerThreshold(cnvmlDevice, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemSetNvlinkBwMode function as declared in nvml/nvml.h +func nvmlSystemSetNvlinkBwMode(NvlinkBwMode uint32) Return { + cNvlinkBwMode, _ := (C.uint)(NvlinkBwMode), cgoAllocsUnknown + __ret := C.nvmlSystemSetNvlinkBwMode(cNvlinkBwMode) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemGetNvlinkBwMode function as declared in nvml/nvml.h +func nvmlSystemGetNvlinkBwMode(NvlinkBwMode *uint32) Return { + cNvlinkBwMode, _ := (*C.uint)(unsafe.Pointer(NvlinkBwMode)), cgoAllocsUnknown + __ret := C.nvmlSystemGetNvlinkBwMode(cNvlinkBwMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvlinkSupportedBwModes function as declared in nvml/nvml.h +func nvmlDeviceGetNvlinkSupportedBwModes(nvmlDevice nvmlDevice, SupportedBwMode *NvlinkSupportedBwModes) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSupportedBwMode, _ := (*C.nvmlNvlinkSupportedBwModes_t)(unsafe.Pointer(SupportedBwMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvlinkSupportedBwModes(cnvmlDevice, cSupportedBwMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvlinkBwMode function as declared in nvml/nvml.h +func nvmlDeviceGetNvlinkBwMode(nvmlDevice nvmlDevice, GetBwMode *NvlinkGetBwMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGetBwMode, _ := (*C.nvmlNvlinkGetBwMode_t)(unsafe.Pointer(GetBwMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvlinkBwMode(cnvmlDevice, cGetBwMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetNvlinkBwMode function as declared in nvml/nvml.h +func nvmlDeviceSetNvlinkBwMode(nvmlDevice nvmlDevice, SetBwMode *NvlinkSetBwMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cSetBwMode, _ := (*C.nvmlNvlinkSetBwMode_t)(unsafe.Pointer(SetBwMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetNvlinkBwMode(cnvmlDevice, cSetBwMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkInfo function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkInfo(nvmlDevice nvmlDevice, Info *NvLinkInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlNvLinkInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkInfo(cnvmlDevice, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlEventSetCreate function as declared in nvml/nvml.h +func nvmlEventSetCreate(Set *nvmlEventSet) Return { + cSet, _ := (*C.nvmlEventSet_t)(unsafe.Pointer(Set)), cgoAllocsUnknown + __ret := C.nvmlEventSetCreate(cSet) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceRegisterEvents function as declared in nvml/nvml.h +func nvmlDeviceRegisterEvents(nvmlDevice nvmlDevice, EventTypes uint64, Set nvmlEventSet) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEventTypes, _ := (C.ulonglong)(EventTypes), cgoAllocsUnknown + cSet, _ := *(*C.nvmlEventSet_t)(unsafe.Pointer(&Set)), cgoAllocsUnknown + __ret := C.nvmlDeviceRegisterEvents(cnvmlDevice, cEventTypes, cSet) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedEventTypes function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedEventTypes(nvmlDevice nvmlDevice, EventTypes *uint64) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cEventTypes, _ := (*C.ulonglong)(unsafe.Pointer(EventTypes)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedEventTypes(cnvmlDevice, cEventTypes) + __v := (Return)(__ret) + return __v +} + +// nvmlEventSetWait_v2 function as declared in nvml/nvml.h +func nvmlEventSetWait_v2(Set nvmlEventSet, Data *nvmlEventData, Timeoutms uint32) Return { + cSet, _ := *(*C.nvmlEventSet_t)(unsafe.Pointer(&Set)), cgoAllocsUnknown + cData, _ := (*C.nvmlEventData_t)(unsafe.Pointer(Data)), cgoAllocsUnknown + cTimeoutms, _ := (C.uint)(Timeoutms), cgoAllocsUnknown + __ret := C.nvmlEventSetWait_v2(cSet, cData, cTimeoutms) + __v := (Return)(__ret) + return __v +} + +// nvmlEventSetFree function as declared in nvml/nvml.h +func nvmlEventSetFree(Set nvmlEventSet) Return { + cSet, _ := *(*C.nvmlEventSet_t)(unsafe.Pointer(&Set)), cgoAllocsUnknown + __ret := C.nvmlEventSetFree(cSet) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemEventSetCreate function as declared in nvml/nvml.h +func nvmlSystemEventSetCreate(Request *SystemEventSetCreateRequest) Return { + cRequest, _ := (*C.nvmlSystemEventSetCreateRequest_t)(unsafe.Pointer(Request)), cgoAllocsUnknown + __ret := C.nvmlSystemEventSetCreate(cRequest) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemEventSetFree function as declared in nvml/nvml.h +func nvmlSystemEventSetFree(Request *SystemEventSetFreeRequest) Return { + cRequest, _ := (*C.nvmlSystemEventSetFreeRequest_t)(unsafe.Pointer(Request)), cgoAllocsUnknown + __ret := C.nvmlSystemEventSetFree(cRequest) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemRegisterEvents function as declared in nvml/nvml.h +func nvmlSystemRegisterEvents(Request *SystemRegisterEventRequest) Return { + cRequest, _ := (*C.nvmlSystemRegisterEventRequest_t)(unsafe.Pointer(Request)), cgoAllocsUnknown + __ret := C.nvmlSystemRegisterEvents(cRequest) + __v := (Return)(__ret) + return __v +} + +// nvmlSystemEventSetWait function as declared in nvml/nvml.h +func nvmlSystemEventSetWait(Request *SystemEventSetWaitRequest) Return { + cRequest, _ := (*C.nvmlSystemEventSetWaitRequest_t)(unsafe.Pointer(Request)), cgoAllocsUnknown + __ret := C.nvmlSystemEventSetWait(cRequest) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceModifyDrainState function as declared in nvml/nvml.h +func nvmlDeviceModifyDrainState(PciInfo *PciInfo, NewState EnableState) Return { + cPciInfo, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(PciInfo)), cgoAllocsUnknown + cNewState, _ := (C.nvmlEnableState_t)(NewState), cgoAllocsUnknown + __ret := C.nvmlDeviceModifyDrainState(cPciInfo, cNewState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceQueryDrainState function as declared in nvml/nvml.h +func nvmlDeviceQueryDrainState(PciInfo *PciInfo, CurrentState *EnableState) Return { + cPciInfo, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(PciInfo)), cgoAllocsUnknown + cCurrentState, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(CurrentState)), cgoAllocsUnknown + __ret := C.nvmlDeviceQueryDrainState(cPciInfo, cCurrentState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceRemoveGpu_v2 function as declared in nvml/nvml.h +func nvmlDeviceRemoveGpu_v2(PciInfo *PciInfo, GpuState DetachGpuState, LinkState PcieLinkState) Return { + cPciInfo, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(PciInfo)), cgoAllocsUnknown + cGpuState, _ := (C.nvmlDetachGpuState_t)(GpuState), cgoAllocsUnknown + cLinkState, _ := (C.nvmlPcieLinkState_t)(LinkState), cgoAllocsUnknown + __ret := C.nvmlDeviceRemoveGpu_v2(cPciInfo, cGpuState, cLinkState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceDiscoverGpus function as declared in nvml/nvml.h +func nvmlDeviceDiscoverGpus(PciInfo *PciInfo) Return { + cPciInfo, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(PciInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceDiscoverGpus(cPciInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetFieldValues function as declared in nvml/nvml.h +func nvmlDeviceGetFieldValues(nvmlDevice nvmlDevice, ValuesCount int32, Values *FieldValue) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cValuesCount, _ := (C.int)(ValuesCount), cgoAllocsUnknown + cValues, _ := (*C.nvmlFieldValue_t)(unsafe.Pointer(Values)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetFieldValues(cnvmlDevice, cValuesCount, cValues) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceClearFieldValues function as declared in nvml/nvml.h +func nvmlDeviceClearFieldValues(nvmlDevice nvmlDevice, ValuesCount int32, Values *FieldValue) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cValuesCount, _ := (C.int)(ValuesCount), cgoAllocsUnknown + cValues, _ := (*C.nvmlFieldValue_t)(unsafe.Pointer(Values)), cgoAllocsUnknown + __ret := C.nvmlDeviceClearFieldValues(cnvmlDevice, cValuesCount, cValues) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVirtualizationMode function as declared in nvml/nvml.h +func nvmlDeviceGetVirtualizationMode(nvmlDevice nvmlDevice, PVirtualMode *GpuVirtualizationMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPVirtualMode, _ := (*C.nvmlGpuVirtualizationMode_t)(unsafe.Pointer(PVirtualMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVirtualizationMode(cnvmlDevice, cPVirtualMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHostVgpuMode function as declared in nvml/nvml.h +func nvmlDeviceGetHostVgpuMode(nvmlDevice nvmlDevice, PHostVgpuMode *HostVgpuMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPHostVgpuMode, _ := (*C.nvmlHostVgpuMode_t)(unsafe.Pointer(PHostVgpuMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHostVgpuMode(cnvmlDevice, cPHostVgpuMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetVirtualizationMode function as declared in nvml/nvml.h +func nvmlDeviceSetVirtualizationMode(nvmlDevice nvmlDevice, VirtualMode GpuVirtualizationMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVirtualMode, _ := (C.nvmlGpuVirtualizationMode_t)(VirtualMode), cgoAllocsUnknown + __ret := C.nvmlDeviceSetVirtualizationMode(cnvmlDevice, cVirtualMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuHeterogeneousMode function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuHeterogeneousMode(nvmlDevice nvmlDevice, PHeterogeneousMode *VgpuHeterogeneousMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPHeterogeneousMode, _ := (*C.nvmlVgpuHeterogeneousMode_t)(unsafe.Pointer(PHeterogeneousMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuHeterogeneousMode(cnvmlDevice, cPHeterogeneousMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetVgpuHeterogeneousMode function as declared in nvml/nvml.h +func nvmlDeviceSetVgpuHeterogeneousMode(nvmlDevice nvmlDevice, PHeterogeneousMode *VgpuHeterogeneousMode) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPHeterogeneousMode, _ := (*C.nvmlVgpuHeterogeneousMode_t)(unsafe.Pointer(PHeterogeneousMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetVgpuHeterogeneousMode(cnvmlDevice, cPHeterogeneousMode) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetPlacementId function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetPlacementId(nvmlVgpuInstance nvmlVgpuInstance, PPlacement *VgpuPlacementId) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cPPlacement, _ := (*C.nvmlVgpuPlacementId_t)(unsafe.Pointer(PPlacement)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetPlacementId(cnvmlVgpuInstance, cPPlacement) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuTypeSupportedPlacements function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuTypeSupportedPlacements(nvmlDevice nvmlDevice, nvmlVgpuTypeId nvmlVgpuTypeId, PPlacementList *VgpuPlacementList) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cPPlacementList, _ := (*C.nvmlVgpuPlacementList_t)(unsafe.Pointer(PPlacementList)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuTypeSupportedPlacements(cnvmlDevice, cnvmlVgpuTypeId, cPPlacementList) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuTypeCreatablePlacements function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuTypeCreatablePlacements(nvmlDevice nvmlDevice, nvmlVgpuTypeId nvmlVgpuTypeId, PPlacementList *VgpuPlacementList) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cPPlacementList, _ := (*C.nvmlVgpuPlacementList_t)(unsafe.Pointer(PPlacementList)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuTypeCreatablePlacements(cnvmlDevice, cnvmlVgpuTypeId, cPPlacementList) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetGspHeapSize function as declared in nvml/nvml.h +func nvmlVgpuTypeGetGspHeapSize(nvmlVgpuTypeId nvmlVgpuTypeId, GspHeapSize *uint64) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cGspHeapSize, _ := (*C.ulonglong)(unsafe.Pointer(GspHeapSize)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetGspHeapSize(cnvmlVgpuTypeId, cGspHeapSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetFbReservation function as declared in nvml/nvml.h +func nvmlVgpuTypeGetFbReservation(nvmlVgpuTypeId nvmlVgpuTypeId, FbReservation *uint64) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cFbReservation, _ := (*C.ulonglong)(unsafe.Pointer(FbReservation)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetFbReservation(cnvmlVgpuTypeId, cFbReservation) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetRuntimeStateSize function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetRuntimeStateSize(nvmlVgpuInstance nvmlVgpuInstance, PState *VgpuRuntimeState) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cPState, _ := (*C.nvmlVgpuRuntimeState_t)(unsafe.Pointer(PState)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetRuntimeStateSize(cnvmlVgpuInstance, cPState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetVgpuCapabilities function as declared in nvml/nvml.h +func nvmlDeviceSetVgpuCapabilities(nvmlDevice nvmlDevice, Capability DeviceVgpuCapability, State EnableState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCapability, _ := (C.nvmlDeviceVgpuCapability_t)(Capability), cgoAllocsUnknown + cState, _ := (C.nvmlEnableState_t)(State), cgoAllocsUnknown + __ret := C.nvmlDeviceSetVgpuCapabilities(cnvmlDevice, cCapability, cState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGridLicensableFeatures_v4 function as declared in nvml/nvml.h +func nvmlDeviceGetGridLicensableFeatures_v4(nvmlDevice nvmlDevice, PGridLicensableFeatures *GridLicensableFeatures) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPGridLicensableFeatures, _ := (*C.nvmlGridLicensableFeatures_t)(unsafe.Pointer(PGridLicensableFeatures)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGridLicensableFeatures_v4(cnvmlDevice, cPGridLicensableFeatures) + __v := (Return)(__ret) + return __v +} + +// nvmlGetVgpuDriverCapabilities function as declared in nvml/nvml.h +func nvmlGetVgpuDriverCapabilities(Capability VgpuDriverCapability, CapResult *uint32) Return { + cCapability, _ := (C.nvmlVgpuDriverCapability_t)(Capability), cgoAllocsUnknown + cCapResult, _ := (*C.uint)(unsafe.Pointer(CapResult)), cgoAllocsUnknown + __ret := C.nvmlGetVgpuDriverCapabilities(cCapability, cCapResult) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuCapabilities function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuCapabilities(nvmlDevice nvmlDevice, Capability DeviceVgpuCapability, CapResult *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCapability, _ := (C.nvmlDeviceVgpuCapability_t)(Capability), cgoAllocsUnknown + cCapResult, _ := (*C.uint)(unsafe.Pointer(CapResult)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuCapabilities(cnvmlDevice, cCapability, cCapResult) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSupportedVgpus function as declared in nvml/nvml.h +func nvmlDeviceGetSupportedVgpus(nvmlDevice nvmlDevice, VgpuCount *uint32, VgpuTypeIds *nvmlVgpuTypeId) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVgpuCount, _ := (*C.uint)(unsafe.Pointer(VgpuCount)), cgoAllocsUnknown + cVgpuTypeIds, _ := (*C.nvmlVgpuTypeId_t)(unsafe.Pointer(VgpuTypeIds)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSupportedVgpus(cnvmlDevice, cVgpuCount, cVgpuTypeIds) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCreatableVgpus function as declared in nvml/nvml.h +func nvmlDeviceGetCreatableVgpus(nvmlDevice nvmlDevice, VgpuCount *uint32, VgpuTypeIds *nvmlVgpuTypeId) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVgpuCount, _ := (*C.uint)(unsafe.Pointer(VgpuCount)), cgoAllocsUnknown + cVgpuTypeIds, _ := (*C.nvmlVgpuTypeId_t)(unsafe.Pointer(VgpuTypeIds)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCreatableVgpus(cnvmlDevice, cVgpuCount, cVgpuTypeIds) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetClass function as declared in nvml/nvml.h +func nvmlVgpuTypeGetClass(nvmlVgpuTypeId nvmlVgpuTypeId, VgpuTypeClass *byte, Size *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cVgpuTypeClass, _ := (*C.char)(unsafe.Pointer(VgpuTypeClass)), cgoAllocsUnknown + cSize, _ := (*C.uint)(unsafe.Pointer(Size)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetClass(cnvmlVgpuTypeId, cVgpuTypeClass, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetName function as declared in nvml/nvml.h +func nvmlVgpuTypeGetName(nvmlVgpuTypeId nvmlVgpuTypeId, VgpuTypeName *byte, Size *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cVgpuTypeName, _ := (*C.char)(unsafe.Pointer(VgpuTypeName)), cgoAllocsUnknown + cSize, _ := (*C.uint)(unsafe.Pointer(Size)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetName(cnvmlVgpuTypeId, cVgpuTypeName, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetGpuInstanceProfileId function as declared in nvml/nvml.h +func nvmlVgpuTypeGetGpuInstanceProfileId(nvmlVgpuTypeId nvmlVgpuTypeId, GpuInstanceProfileId *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cGpuInstanceProfileId, _ := (*C.uint)(unsafe.Pointer(GpuInstanceProfileId)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetGpuInstanceProfileId(cnvmlVgpuTypeId, cGpuInstanceProfileId) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetDeviceID function as declared in nvml/nvml.h +func nvmlVgpuTypeGetDeviceID(nvmlVgpuTypeId nvmlVgpuTypeId, DeviceID *uint64, SubsystemID *uint64) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cDeviceID, _ := (*C.ulonglong)(unsafe.Pointer(DeviceID)), cgoAllocsUnknown + cSubsystemID, _ := (*C.ulonglong)(unsafe.Pointer(SubsystemID)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetDeviceID(cnvmlVgpuTypeId, cDeviceID, cSubsystemID) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetFramebufferSize function as declared in nvml/nvml.h +func nvmlVgpuTypeGetFramebufferSize(nvmlVgpuTypeId nvmlVgpuTypeId, FbSize *uint64) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cFbSize, _ := (*C.ulonglong)(unsafe.Pointer(FbSize)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetFramebufferSize(cnvmlVgpuTypeId, cFbSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetNumDisplayHeads function as declared in nvml/nvml.h +func nvmlVgpuTypeGetNumDisplayHeads(nvmlVgpuTypeId nvmlVgpuTypeId, NumDisplayHeads *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cNumDisplayHeads, _ := (*C.uint)(unsafe.Pointer(NumDisplayHeads)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetNumDisplayHeads(cnvmlVgpuTypeId, cNumDisplayHeads) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetResolution function as declared in nvml/nvml.h +func nvmlVgpuTypeGetResolution(nvmlVgpuTypeId nvmlVgpuTypeId, DisplayIndex uint32, Xdim *uint32, Ydim *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cDisplayIndex, _ := (C.uint)(DisplayIndex), cgoAllocsUnknown + cXdim, _ := (*C.uint)(unsafe.Pointer(Xdim)), cgoAllocsUnknown + cYdim, _ := (*C.uint)(unsafe.Pointer(Ydim)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetResolution(cnvmlVgpuTypeId, cDisplayIndex, cXdim, cYdim) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetLicense function as declared in nvml/nvml.h +func nvmlVgpuTypeGetLicense(nvmlVgpuTypeId nvmlVgpuTypeId, VgpuTypeLicenseString *byte, Size uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cVgpuTypeLicenseString, _ := (*C.char)(unsafe.Pointer(VgpuTypeLicenseString)), cgoAllocsUnknown + cSize, _ := (C.uint)(Size), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetLicense(cnvmlVgpuTypeId, cVgpuTypeLicenseString, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetFrameRateLimit function as declared in nvml/nvml.h +func nvmlVgpuTypeGetFrameRateLimit(nvmlVgpuTypeId nvmlVgpuTypeId, FrameRateLimit *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cFrameRateLimit, _ := (*C.uint)(unsafe.Pointer(FrameRateLimit)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetFrameRateLimit(cnvmlVgpuTypeId, cFrameRateLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetMaxInstances function as declared in nvml/nvml.h +func nvmlVgpuTypeGetMaxInstances(nvmlDevice nvmlDevice, nvmlVgpuTypeId nvmlVgpuTypeId, VgpuInstanceCount *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cVgpuInstanceCount, _ := (*C.uint)(unsafe.Pointer(VgpuInstanceCount)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetMaxInstances(cnvmlDevice, cnvmlVgpuTypeId, cVgpuInstanceCount) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetMaxInstancesPerVm function as declared in nvml/nvml.h +func nvmlVgpuTypeGetMaxInstancesPerVm(nvmlVgpuTypeId nvmlVgpuTypeId, VgpuInstanceCountPerVm *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cVgpuInstanceCountPerVm, _ := (*C.uint)(unsafe.Pointer(VgpuInstanceCountPerVm)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetMaxInstancesPerVm(cnvmlVgpuTypeId, cVgpuInstanceCountPerVm) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetBAR1Info function as declared in nvml/nvml.h +func nvmlVgpuTypeGetBAR1Info(nvmlVgpuTypeId nvmlVgpuTypeId, Bar1Info *VgpuTypeBar1Info) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cBar1Info, _ := (*C.nvmlVgpuTypeBar1Info_t)(unsafe.Pointer(Bar1Info)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetBAR1Info(cnvmlVgpuTypeId, cBar1Info) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetActiveVgpus function as declared in nvml/nvml.h +func nvmlDeviceGetActiveVgpus(nvmlDevice nvmlDevice, VgpuCount *uint32, VgpuInstances *nvmlVgpuInstance) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVgpuCount, _ := (*C.uint)(unsafe.Pointer(VgpuCount)), cgoAllocsUnknown + cVgpuInstances, _ := (*C.nvmlVgpuInstance_t)(unsafe.Pointer(VgpuInstances)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetActiveVgpus(cnvmlDevice, cVgpuCount, cVgpuInstances) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetVmID function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetVmID(nvmlVgpuInstance nvmlVgpuInstance, VmId *byte, Size uint32, VmIdType *VgpuVmIdType) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cVmId, _ := (*C.char)(unsafe.Pointer(VmId)), cgoAllocsUnknown + cSize, _ := (C.uint)(Size), cgoAllocsUnknown + cVmIdType, _ := (*C.nvmlVgpuVmIdType_t)(unsafe.Pointer(VmIdType)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetVmID(cnvmlVgpuInstance, cVmId, cSize, cVmIdType) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetUUID function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetUUID(nvmlVgpuInstance nvmlVgpuInstance, Uuid *byte, Size uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cUuid, _ := (*C.char)(unsafe.Pointer(Uuid)), cgoAllocsUnknown + cSize, _ := (C.uint)(Size), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetUUID(cnvmlVgpuInstance, cUuid, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetVmDriverVersion function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetVmDriverVersion(nvmlVgpuInstance nvmlVgpuInstance, Version *byte, Length uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetVmDriverVersion(cnvmlVgpuInstance, cVersion, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetFbUsage function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetFbUsage(nvmlVgpuInstance nvmlVgpuInstance, FbUsage *uint64) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cFbUsage, _ := (*C.ulonglong)(unsafe.Pointer(FbUsage)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetFbUsage(cnvmlVgpuInstance, cFbUsage) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetLicenseStatus function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetLicenseStatus(nvmlVgpuInstance nvmlVgpuInstance, Licensed *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cLicensed, _ := (*C.uint)(unsafe.Pointer(Licensed)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetLicenseStatus(cnvmlVgpuInstance, cLicensed) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetType function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetType(nvmlVgpuInstance nvmlVgpuInstance, nvmlVgpuTypeId *nvmlVgpuTypeId) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cnvmlVgpuTypeId, _ := (*C.nvmlVgpuTypeId_t)(unsafe.Pointer(nvmlVgpuTypeId)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetType(cnvmlVgpuInstance, cnvmlVgpuTypeId) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetFrameRateLimit function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetFrameRateLimit(nvmlVgpuInstance nvmlVgpuInstance, FrameRateLimit *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cFrameRateLimit, _ := (*C.uint)(unsafe.Pointer(FrameRateLimit)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetFrameRateLimit(cnvmlVgpuInstance, cFrameRateLimit) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetEccMode function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetEccMode(nvmlVgpuInstance nvmlVgpuInstance, EccMode *EnableState) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cEccMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(EccMode)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetEccMode(cnvmlVgpuInstance, cEccMode) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetEncoderCapacity function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetEncoderCapacity(nvmlVgpuInstance nvmlVgpuInstance, EncoderCapacity *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cEncoderCapacity, _ := (*C.uint)(unsafe.Pointer(EncoderCapacity)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetEncoderCapacity(cnvmlVgpuInstance, cEncoderCapacity) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceSetEncoderCapacity function as declared in nvml/nvml.h +func nvmlVgpuInstanceSetEncoderCapacity(nvmlVgpuInstance nvmlVgpuInstance, EncoderCapacity uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cEncoderCapacity, _ := (C.uint)(EncoderCapacity), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceSetEncoderCapacity(cnvmlVgpuInstance, cEncoderCapacity) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetEncoderStats function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetEncoderStats(nvmlVgpuInstance nvmlVgpuInstance, SessionCount *uint32, AverageFps *uint32, AverageLatency *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cAverageFps, _ := (*C.uint)(unsafe.Pointer(AverageFps)), cgoAllocsUnknown + cAverageLatency, _ := (*C.uint)(unsafe.Pointer(AverageLatency)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetEncoderStats(cnvmlVgpuInstance, cSessionCount, cAverageFps, cAverageLatency) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetEncoderSessions function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetEncoderSessions(nvmlVgpuInstance nvmlVgpuInstance, SessionCount *uint32, SessionInfo *EncoderSessionInfo) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cSessionInfo, _ := (*C.nvmlEncoderSessionInfo_t)(unsafe.Pointer(SessionInfo)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetEncoderSessions(cnvmlVgpuInstance, cSessionCount, cSessionInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetFBCStats function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetFBCStats(nvmlVgpuInstance nvmlVgpuInstance, FbcStats *FBCStats) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cFbcStats, _ := (*C.nvmlFBCStats_t)(unsafe.Pointer(FbcStats)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetFBCStats(cnvmlVgpuInstance, cFbcStats) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetFBCSessions function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetFBCSessions(nvmlVgpuInstance nvmlVgpuInstance, SessionCount *uint32, SessionInfo *FBCSessionInfo) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cSessionCount, _ := (*C.uint)(unsafe.Pointer(SessionCount)), cgoAllocsUnknown + cSessionInfo, _ := (*C.nvmlFBCSessionInfo_t)(unsafe.Pointer(SessionInfo)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetFBCSessions(cnvmlVgpuInstance, cSessionCount, cSessionInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetGpuInstanceId function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetGpuInstanceId(nvmlVgpuInstance nvmlVgpuInstance, GpuInstanceId *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cGpuInstanceId, _ := (*C.uint)(unsafe.Pointer(GpuInstanceId)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetGpuInstanceId(cnvmlVgpuInstance, cGpuInstanceId) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetGpuPciId function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetGpuPciId(nvmlVgpuInstance nvmlVgpuInstance, VgpuPciId *byte, Length *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cVgpuPciId, _ := (*C.char)(unsafe.Pointer(VgpuPciId)), cgoAllocsUnknown + cLength, _ := (*C.uint)(unsafe.Pointer(Length)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetGpuPciId(cnvmlVgpuInstance, cVgpuPciId, cLength) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetCapabilities function as declared in nvml/nvml.h +func nvmlVgpuTypeGetCapabilities(nvmlVgpuTypeId nvmlVgpuTypeId, Capability VgpuCapability, CapResult *uint32) Return { + cnvmlVgpuTypeId, _ := (C.nvmlVgpuTypeId_t)(nvmlVgpuTypeId), cgoAllocsUnknown + cCapability, _ := (C.nvmlVgpuCapability_t)(Capability), cgoAllocsUnknown + cCapResult, _ := (*C.uint)(unsafe.Pointer(CapResult)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetCapabilities(cnvmlVgpuTypeId, cCapability, cCapResult) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetMdevUUID function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetMdevUUID(nvmlVgpuInstance nvmlVgpuInstance, MdevUuid *byte, Size uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cMdevUuid, _ := (*C.char)(unsafe.Pointer(MdevUuid)), cgoAllocsUnknown + cSize, _ := (C.uint)(Size), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetMdevUUID(cnvmlVgpuInstance, cMdevUuid, cSize) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetCreatableVgpus function as declared in nvml/nvml.h +func nvmlGpuInstanceGetCreatableVgpus(nvmlGpuInstance nvmlGpuInstance, PVgpus *VgpuTypeIdInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPVgpus, _ := (*C.nvmlVgpuTypeIdInfo_t)(unsafe.Pointer(PVgpus)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetCreatableVgpus(cnvmlGpuInstance, cPVgpus) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuTypeGetMaxInstancesPerGpuInstance function as declared in nvml/nvml.h +func nvmlVgpuTypeGetMaxInstancesPerGpuInstance(PMaxInstance *VgpuTypeMaxInstance) Return { + cPMaxInstance, _ := (*C.nvmlVgpuTypeMaxInstance_t)(unsafe.Pointer(PMaxInstance)), cgoAllocsUnknown + __ret := C.nvmlVgpuTypeGetMaxInstancesPerGpuInstance(cPMaxInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetActiveVgpus function as declared in nvml/nvml.h +func nvmlGpuInstanceGetActiveVgpus(nvmlGpuInstance nvmlGpuInstance, PVgpuInstanceInfo *ActiveVgpuInstanceInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPVgpuInstanceInfo, _ := (*C.nvmlActiveVgpuInstanceInfo_t)(unsafe.Pointer(PVgpuInstanceInfo)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetActiveVgpus(cnvmlGpuInstance, cPVgpuInstanceInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceSetVgpuSchedulerState function as declared in nvml/nvml.h +func nvmlGpuInstanceSetVgpuSchedulerState(nvmlGpuInstance nvmlGpuInstance, PScheduler *VgpuSchedulerState) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPScheduler, _ := (*C.nvmlVgpuSchedulerState_t)(unsafe.Pointer(PScheduler)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceSetVgpuSchedulerState(cnvmlGpuInstance, cPScheduler) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetVgpuSchedulerState function as declared in nvml/nvml.h +func nvmlGpuInstanceGetVgpuSchedulerState(nvmlGpuInstance nvmlGpuInstance, PSchedulerStateInfo *VgpuSchedulerStateInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPSchedulerStateInfo, _ := (*C.nvmlVgpuSchedulerStateInfo_t)(unsafe.Pointer(PSchedulerStateInfo)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetVgpuSchedulerState(cnvmlGpuInstance, cPSchedulerStateInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetVgpuSchedulerLog function as declared in nvml/nvml.h +func nvmlGpuInstanceGetVgpuSchedulerLog(nvmlGpuInstance nvmlGpuInstance, PSchedulerLogInfo *VgpuSchedulerLogInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPSchedulerLogInfo, _ := (*C.nvmlVgpuSchedulerLogInfo_t)(unsafe.Pointer(PSchedulerLogInfo)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetVgpuSchedulerLog(cnvmlGpuInstance, cPSchedulerLogInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetVgpuTypeCreatablePlacements function as declared in nvml/nvml.h +func nvmlGpuInstanceGetVgpuTypeCreatablePlacements(nvmlGpuInstance nvmlGpuInstance, PCreatablePlacementInfo *VgpuCreatablePlacementInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPCreatablePlacementInfo, _ := (*C.nvmlVgpuCreatablePlacementInfo_t)(unsafe.Pointer(PCreatablePlacementInfo)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetVgpuTypeCreatablePlacements(cnvmlGpuInstance, cPCreatablePlacementInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetVgpuHeterogeneousMode function as declared in nvml/nvml.h +func nvmlGpuInstanceGetVgpuHeterogeneousMode(nvmlGpuInstance nvmlGpuInstance, PHeterogeneousMode *VgpuHeterogeneousMode) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPHeterogeneousMode, _ := (*C.nvmlVgpuHeterogeneousMode_t)(unsafe.Pointer(PHeterogeneousMode)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetVgpuHeterogeneousMode(cnvmlGpuInstance, cPHeterogeneousMode) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceSetVgpuHeterogeneousMode function as declared in nvml/nvml.h +func nvmlGpuInstanceSetVgpuHeterogeneousMode(nvmlGpuInstance nvmlGpuInstance, PHeterogeneousMode *VgpuHeterogeneousMode) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cPHeterogeneousMode, _ := (*C.nvmlVgpuHeterogeneousMode_t)(unsafe.Pointer(PHeterogeneousMode)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceSetVgpuHeterogeneousMode(cnvmlGpuInstance, cPHeterogeneousMode) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetMetadata function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetMetadata(nvmlVgpuInstance nvmlVgpuInstance, nvmlVgpuMetadata *nvmlVgpuMetadata, BufferSize *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cnvmlVgpuMetadata, _ := (*C.nvmlVgpuMetadata_t)(unsafe.Pointer(nvmlVgpuMetadata)), cgoAllocsUnknown + cBufferSize, _ := (*C.uint)(unsafe.Pointer(BufferSize)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetMetadata(cnvmlVgpuInstance, cnvmlVgpuMetadata, cBufferSize) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuMetadata function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuMetadata(nvmlDevice nvmlDevice, PgpuMetadata *nvmlVgpuPgpuMetadata, BufferSize *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPgpuMetadata, _ := (*C.nvmlVgpuPgpuMetadata_t)(unsafe.Pointer(PgpuMetadata)), cgoAllocsUnknown + cBufferSize, _ := (*C.uint)(unsafe.Pointer(BufferSize)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuMetadata(cnvmlDevice, cPgpuMetadata, cBufferSize) + __v := (Return)(__ret) + return __v +} + +// nvmlGetVgpuCompatibility function as declared in nvml/nvml.h +func nvmlGetVgpuCompatibility(nvmlVgpuMetadata *nvmlVgpuMetadata, PgpuMetadata *nvmlVgpuPgpuMetadata, CompatibilityInfo *VgpuPgpuCompatibility) Return { + cnvmlVgpuMetadata, _ := (*C.nvmlVgpuMetadata_t)(unsafe.Pointer(nvmlVgpuMetadata)), cgoAllocsUnknown + cPgpuMetadata, _ := (*C.nvmlVgpuPgpuMetadata_t)(unsafe.Pointer(PgpuMetadata)), cgoAllocsUnknown + cCompatibilityInfo, _ := (*C.nvmlVgpuPgpuCompatibility_t)(unsafe.Pointer(CompatibilityInfo)), cgoAllocsUnknown + __ret := C.nvmlGetVgpuCompatibility(cnvmlVgpuMetadata, cPgpuMetadata, cCompatibilityInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPgpuMetadataString function as declared in nvml/nvml.h +func nvmlDeviceGetPgpuMetadataString(nvmlDevice nvmlDevice, PgpuMetadata *byte, BufferSize *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPgpuMetadata, _ := (*C.char)(unsafe.Pointer(PgpuMetadata)), cgoAllocsUnknown + cBufferSize, _ := (*C.uint)(unsafe.Pointer(BufferSize)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPgpuMetadataString(cnvmlDevice, cPgpuMetadata, cBufferSize) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuSchedulerLog function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuSchedulerLog(nvmlDevice nvmlDevice, PSchedulerLog *VgpuSchedulerLog) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPSchedulerLog, _ := (*C.nvmlVgpuSchedulerLog_t)(unsafe.Pointer(PSchedulerLog)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuSchedulerLog(cnvmlDevice, cPSchedulerLog) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuSchedulerState function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuSchedulerState(nvmlDevice nvmlDevice, PSchedulerState *VgpuSchedulerGetState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPSchedulerState, _ := (*C.nvmlVgpuSchedulerGetState_t)(unsafe.Pointer(PSchedulerState)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuSchedulerState(cnvmlDevice, cPSchedulerState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuSchedulerCapabilities function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuSchedulerCapabilities(nvmlDevice nvmlDevice, PCapabilities *VgpuSchedulerCapabilities) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPCapabilities, _ := (*C.nvmlVgpuSchedulerCapabilities_t)(unsafe.Pointer(PCapabilities)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuSchedulerCapabilities(cnvmlDevice, cPCapabilities) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetVgpuSchedulerState function as declared in nvml/nvml.h +func nvmlDeviceSetVgpuSchedulerState(nvmlDevice nvmlDevice, PSchedulerState *VgpuSchedulerSetState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPSchedulerState, _ := (*C.nvmlVgpuSchedulerSetState_t)(unsafe.Pointer(PSchedulerState)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetVgpuSchedulerState(cnvmlDevice, cPSchedulerState) + __v := (Return)(__ret) + return __v +} + +// nvmlGetVgpuVersion function as declared in nvml/nvml.h +func nvmlGetVgpuVersion(Supported *VgpuVersion, Current *VgpuVersion) Return { + cSupported, _ := (*C.nvmlVgpuVersion_t)(unsafe.Pointer(Supported)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlVgpuVersion_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + __ret := C.nvmlGetVgpuVersion(cSupported, cCurrent) + __v := (Return)(__ret) + return __v +} + +// nvmlSetVgpuVersion function as declared in nvml/nvml.h +func nvmlSetVgpuVersion(VgpuVersion *VgpuVersion) Return { + cVgpuVersion, _ := (*C.nvmlVgpuVersion_t)(unsafe.Pointer(VgpuVersion)), cgoAllocsUnknown + __ret := C.nvmlSetVgpuVersion(cVgpuVersion) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuUtilization(nvmlDevice nvmlDevice, LastSeenTimeStamp uint64, SampleValType *ValueType, VgpuInstanceSamplesCount *uint32, UtilizationSamples *VgpuInstanceUtilizationSample) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLastSeenTimeStamp, _ := (C.ulonglong)(LastSeenTimeStamp), cgoAllocsUnknown + cSampleValType, _ := (*C.nvmlValueType_t)(unsafe.Pointer(SampleValType)), cgoAllocsUnknown + cVgpuInstanceSamplesCount, _ := (*C.uint)(unsafe.Pointer(VgpuInstanceSamplesCount)), cgoAllocsUnknown + cUtilizationSamples, _ := (*C.nvmlVgpuInstanceUtilizationSample_t)(unsafe.Pointer(UtilizationSamples)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuUtilization(cnvmlDevice, cLastSeenTimeStamp, cSampleValType, cVgpuInstanceSamplesCount, cUtilizationSamples) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuInstancesUtilizationInfo function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuInstancesUtilizationInfo(nvmlDevice nvmlDevice, VgpuUtilInfo *VgpuInstancesUtilizationInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVgpuUtilInfo, _ := (*C.nvmlVgpuInstancesUtilizationInfo_t)(unsafe.Pointer(VgpuUtilInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuInstancesUtilizationInfo(cnvmlDevice, cVgpuUtilInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuProcessUtilization function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuProcessUtilization(nvmlDevice nvmlDevice, LastSeenTimeStamp uint64, VgpuProcessSamplesCount *uint32, UtilizationSamples *VgpuProcessUtilizationSample) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLastSeenTimeStamp, _ := (C.ulonglong)(LastSeenTimeStamp), cgoAllocsUnknown + cVgpuProcessSamplesCount, _ := (*C.uint)(unsafe.Pointer(VgpuProcessSamplesCount)), cgoAllocsUnknown + cUtilizationSamples, _ := (*C.nvmlVgpuProcessUtilizationSample_t)(unsafe.Pointer(UtilizationSamples)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuProcessUtilization(cnvmlDevice, cLastSeenTimeStamp, cVgpuProcessSamplesCount, cUtilizationSamples) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetVgpuProcessesUtilizationInfo function as declared in nvml/nvml.h +func nvmlDeviceGetVgpuProcessesUtilizationInfo(nvmlDevice nvmlDevice, VgpuProcUtilInfo *VgpuProcessesUtilizationInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cVgpuProcUtilInfo, _ := (*C.nvmlVgpuProcessesUtilizationInfo_t)(unsafe.Pointer(VgpuProcUtilInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetVgpuProcessesUtilizationInfo(cnvmlDevice, cVgpuProcUtilInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetAccountingMode function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetAccountingMode(nvmlVgpuInstance nvmlVgpuInstance, Mode *EnableState) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cMode, _ := (*C.nvmlEnableState_t)(unsafe.Pointer(Mode)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetAccountingMode(cnvmlVgpuInstance, cMode) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetAccountingPids function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetAccountingPids(nvmlVgpuInstance nvmlVgpuInstance, Count *uint32, Pids *uint32) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + cPids, _ := (*C.uint)(unsafe.Pointer(Pids)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetAccountingPids(cnvmlVgpuInstance, cCount, cPids) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetAccountingStats function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetAccountingStats(nvmlVgpuInstance nvmlVgpuInstance, Pid uint32, Stats *AccountingStats) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cPid, _ := (C.uint)(Pid), cgoAllocsUnknown + cStats, _ := (*C.nvmlAccountingStats_t)(unsafe.Pointer(Stats)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetAccountingStats(cnvmlVgpuInstance, cPid, cStats) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceClearAccountingPids function as declared in nvml/nvml.h +func nvmlVgpuInstanceClearAccountingPids(nvmlVgpuInstance nvmlVgpuInstance) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceClearAccountingPids(cnvmlVgpuInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetLicenseInfo_v2 function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetLicenseInfo_v2(nvmlVgpuInstance nvmlVgpuInstance, LicenseInfo *VgpuLicenseInfo) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cLicenseInfo, _ := (*C.nvmlVgpuLicenseInfo_t)(unsafe.Pointer(LicenseInfo)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetLicenseInfo_v2(cnvmlVgpuInstance, cLicenseInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGetExcludedDeviceCount function as declared in nvml/nvml.h +func nvmlGetExcludedDeviceCount(DeviceCount *uint32) Return { + cDeviceCount, _ := (*C.uint)(unsafe.Pointer(DeviceCount)), cgoAllocsUnknown + __ret := C.nvmlGetExcludedDeviceCount(cDeviceCount) + __v := (Return)(__ret) + return __v +} + +// nvmlGetExcludedDeviceInfoByIndex function as declared in nvml/nvml.h +func nvmlGetExcludedDeviceInfoByIndex(Index uint32, Info *ExcludedDeviceInfo) Return { + cIndex, _ := (C.uint)(Index), cgoAllocsUnknown + cInfo, _ := (*C.nvmlExcludedDeviceInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlGetExcludedDeviceInfoByIndex(cIndex, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceReadWritePRM_v1 function as declared in nvml/nvml.h +func nvmlDeviceReadWritePRM_v1(nvmlDevice nvmlDevice, Buffer *PRMTLV_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cBuffer, _ := (*C.nvmlPRMTLV_v1_t)(unsafe.Pointer(Buffer)), cgoAllocsUnknown + __ret := C.nvmlDeviceReadWritePRM_v1(cnvmlDevice, cBuffer) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceSetMigMode function as declared in nvml/nvml.h +func nvmlDeviceSetMigMode(nvmlDevice nvmlDevice, Mode uint32, ActivationStatus *Return) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cMode, _ := (C.uint)(Mode), cgoAllocsUnknown + cActivationStatus, _ := (*C.nvmlReturn_t)(unsafe.Pointer(ActivationStatus)), cgoAllocsUnknown + __ret := C.nvmlDeviceSetMigMode(cnvmlDevice, cMode, cActivationStatus) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMigMode function as declared in nvml/nvml.h +func nvmlDeviceGetMigMode(nvmlDevice nvmlDevice, CurrentMode *uint32, PendingMode *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrentMode, _ := (*C.uint)(unsafe.Pointer(CurrentMode)), cgoAllocsUnknown + cPendingMode, _ := (*C.uint)(unsafe.Pointer(PendingMode)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMigMode(cnvmlDevice, cCurrentMode, cPendingMode) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceProfileInfo function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceProfileInfo(nvmlDevice nvmlDevice, Profile uint32, Info *GpuInstanceProfileInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfile, _ := (C.uint)(Profile), cgoAllocsUnknown + cInfo, _ := (*C.nvmlGpuInstanceProfileInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceProfileInfo(cnvmlDevice, cProfile, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceProfileInfoV function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceProfileInfoV(nvmlDevice nvmlDevice, Profile uint32, Info *GpuInstanceProfileInfo_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfile, _ := (C.uint)(Profile), cgoAllocsUnknown + cInfo, _ := (*C.nvmlGpuInstanceProfileInfo_v2_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceProfileInfoV(cnvmlDevice, cProfile, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceProfileInfoByIdV function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceProfileInfoByIdV(nvmlDevice nvmlDevice, ProfileId uint32, Info *GpuInstanceProfileInfo_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cInfo, _ := (*C.nvmlGpuInstanceProfileInfo_v2_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceProfileInfoByIdV(cnvmlDevice, cProfileId, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstancePossiblePlacements_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstancePossiblePlacements_v2(nvmlDevice nvmlDevice, ProfileId uint32, Placements *GpuInstancePlacement, Count *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cPlacements, _ := (*C.nvmlGpuInstancePlacement_t)(unsafe.Pointer(Placements)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstancePossiblePlacements_v2(cnvmlDevice, cProfileId, cPlacements, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceRemainingCapacity function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceRemainingCapacity(nvmlDevice nvmlDevice, ProfileId uint32, Count *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceRemainingCapacity(cnvmlDevice, cProfileId, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceCreateGpuInstance function as declared in nvml/nvml.h +func nvmlDeviceCreateGpuInstance(nvmlDevice nvmlDevice, ProfileId uint32, nvmlGpuInstance *nvmlGpuInstance) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cnvmlGpuInstance, _ := (*C.nvmlGpuInstance_t)(unsafe.Pointer(nvmlGpuInstance)), cgoAllocsUnknown + __ret := C.nvmlDeviceCreateGpuInstance(cnvmlDevice, cProfileId, cnvmlGpuInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceCreateGpuInstanceWithPlacement function as declared in nvml/nvml.h +func nvmlDeviceCreateGpuInstanceWithPlacement(nvmlDevice nvmlDevice, ProfileId uint32, Placement *GpuInstancePlacement, nvmlGpuInstance *nvmlGpuInstance) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cPlacement, _ := (*C.nvmlGpuInstancePlacement_t)(unsafe.Pointer(Placement)), cgoAllocsUnknown + cnvmlGpuInstance, _ := (*C.nvmlGpuInstance_t)(unsafe.Pointer(nvmlGpuInstance)), cgoAllocsUnknown + __ret := C.nvmlDeviceCreateGpuInstanceWithPlacement(cnvmlDevice, cProfileId, cPlacement, cnvmlGpuInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceDestroy function as declared in nvml/nvml.h +func nvmlGpuInstanceDestroy(nvmlGpuInstance nvmlGpuInstance) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceDestroy(cnvmlGpuInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstances function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstances(nvmlDevice nvmlDevice, ProfileId uint32, GpuInstances *nvmlGpuInstance, Count *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cGpuInstances, _ := (*C.nvmlGpuInstance_t)(unsafe.Pointer(GpuInstances)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstances(cnvmlDevice, cProfileId, cGpuInstances, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceById function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceById(nvmlDevice nvmlDevice, Id uint32, nvmlGpuInstance *nvmlGpuInstance) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cId, _ := (C.uint)(Id), cgoAllocsUnknown + cnvmlGpuInstance, _ := (*C.nvmlGpuInstance_t)(unsafe.Pointer(nvmlGpuInstance)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceById(cnvmlDevice, cId, cnvmlGpuInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetInfo function as declared in nvml/nvml.h +func nvmlGpuInstanceGetInfo(nvmlGpuInstance nvmlGpuInstance, Info *nvmlGpuInstanceInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlGpuInstanceInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetInfo(cnvmlGpuInstance, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstanceProfileInfo function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstanceProfileInfo(nvmlGpuInstance nvmlGpuInstance, Profile uint32, EngProfile uint32, Info *ComputeInstanceProfileInfo) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfile, _ := (C.uint)(Profile), cgoAllocsUnknown + cEngProfile, _ := (C.uint)(EngProfile), cgoAllocsUnknown + cInfo, _ := (*C.nvmlComputeInstanceProfileInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstanceProfileInfo(cnvmlGpuInstance, cProfile, cEngProfile, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstanceProfileInfoV function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstanceProfileInfoV(nvmlGpuInstance nvmlGpuInstance, Profile uint32, EngProfile uint32, Info *ComputeInstanceProfileInfo_v2) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfile, _ := (C.uint)(Profile), cgoAllocsUnknown + cEngProfile, _ := (C.uint)(EngProfile), cgoAllocsUnknown + cInfo, _ := (*C.nvmlComputeInstanceProfileInfo_v2_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstanceProfileInfoV(cnvmlGpuInstance, cProfile, cEngProfile, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstanceRemainingCapacity function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstanceRemainingCapacity(nvmlGpuInstance nvmlGpuInstance, ProfileId uint32, Count *uint32) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstanceRemainingCapacity(cnvmlGpuInstance, cProfileId, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstancePossiblePlacements function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstancePossiblePlacements(nvmlGpuInstance nvmlGpuInstance, ProfileId uint32, Placements *ComputeInstancePlacement, Count *uint32) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cPlacements, _ := (*C.nvmlComputeInstancePlacement_t)(unsafe.Pointer(Placements)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstancePossiblePlacements(cnvmlGpuInstance, cProfileId, cPlacements, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceCreateComputeInstance function as declared in nvml/nvml.h +func nvmlGpuInstanceCreateComputeInstance(nvmlGpuInstance nvmlGpuInstance, ProfileId uint32, nvmlComputeInstance *nvmlComputeInstance) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cnvmlComputeInstance, _ := (*C.nvmlComputeInstance_t)(unsafe.Pointer(nvmlComputeInstance)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceCreateComputeInstance(cnvmlGpuInstance, cProfileId, cnvmlComputeInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceCreateComputeInstanceWithPlacement function as declared in nvml/nvml.h +func nvmlGpuInstanceCreateComputeInstanceWithPlacement(nvmlGpuInstance nvmlGpuInstance, ProfileId uint32, Placement *ComputeInstancePlacement, nvmlComputeInstance *nvmlComputeInstance) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cPlacement, _ := (*C.nvmlComputeInstancePlacement_t)(unsafe.Pointer(Placement)), cgoAllocsUnknown + cnvmlComputeInstance, _ := (*C.nvmlComputeInstance_t)(unsafe.Pointer(nvmlComputeInstance)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceCreateComputeInstanceWithPlacement(cnvmlGpuInstance, cProfileId, cPlacement, cnvmlComputeInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlComputeInstanceDestroy function as declared in nvml/nvml.h +func nvmlComputeInstanceDestroy(nvmlComputeInstance nvmlComputeInstance) Return { + cnvmlComputeInstance, _ := *(*C.nvmlComputeInstance_t)(unsafe.Pointer(&nvmlComputeInstance)), cgoAllocsUnknown + __ret := C.nvmlComputeInstanceDestroy(cnvmlComputeInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstances function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstances(nvmlGpuInstance nvmlGpuInstance, ProfileId uint32, ComputeInstances *nvmlComputeInstance, Count *uint32) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cComputeInstances, _ := (*C.nvmlComputeInstance_t)(unsafe.Pointer(ComputeInstances)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstances(cnvmlGpuInstance, cProfileId, cComputeInstances, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlGpuInstanceGetComputeInstanceById function as declared in nvml/nvml.h +func nvmlGpuInstanceGetComputeInstanceById(nvmlGpuInstance nvmlGpuInstance, Id uint32, nvmlComputeInstance *nvmlComputeInstance) Return { + cnvmlGpuInstance, _ := *(*C.nvmlGpuInstance_t)(unsafe.Pointer(&nvmlGpuInstance)), cgoAllocsUnknown + cId, _ := (C.uint)(Id), cgoAllocsUnknown + cnvmlComputeInstance, _ := (*C.nvmlComputeInstance_t)(unsafe.Pointer(nvmlComputeInstance)), cgoAllocsUnknown + __ret := C.nvmlGpuInstanceGetComputeInstanceById(cnvmlGpuInstance, cId, cnvmlComputeInstance) + __v := (Return)(__ret) + return __v +} + +// nvmlComputeInstanceGetInfo_v2 function as declared in nvml/nvml.h +func nvmlComputeInstanceGetInfo_v2(nvmlComputeInstance nvmlComputeInstance, Info *nvmlComputeInstanceInfo) Return { + cnvmlComputeInstance, _ := *(*C.nvmlComputeInstance_t)(unsafe.Pointer(&nvmlComputeInstance)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlComputeInstanceInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlComputeInstanceGetInfo_v2(cnvmlComputeInstance, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceIsMigDeviceHandle function as declared in nvml/nvml.h +func nvmlDeviceIsMigDeviceHandle(nvmlDevice nvmlDevice, IsMigDevice *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIsMigDevice, _ := (*C.uint)(unsafe.Pointer(IsMigDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceIsMigDeviceHandle(cnvmlDevice, cIsMigDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstanceId function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstanceId(nvmlDevice nvmlDevice, Id *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cId, _ := (*C.uint)(unsafe.Pointer(Id)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstanceId(cnvmlDevice, cId) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetComputeInstanceId function as declared in nvml/nvml.h +func nvmlDeviceGetComputeInstanceId(nvmlDevice nvmlDevice, Id *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cId, _ := (*C.uint)(unsafe.Pointer(Id)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetComputeInstanceId(cnvmlDevice, cId) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMaxMigDeviceCount function as declared in nvml/nvml.h +func nvmlDeviceGetMaxMigDeviceCount(nvmlDevice nvmlDevice, Count *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMaxMigDeviceCount(cnvmlDevice, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMigDeviceHandleByIndex function as declared in nvml/nvml.h +func nvmlDeviceGetMigDeviceHandleByIndex(nvmlDevice nvmlDevice, Index uint32, MigDevice *nvmlDevice) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cIndex, _ := (C.uint)(Index), cgoAllocsUnknown + cMigDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(MigDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMigDeviceHandleByIndex(cnvmlDevice, cIndex, cMigDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDeviceHandleFromMigDeviceHandle function as declared in nvml/nvml.h +func nvmlDeviceGetDeviceHandleFromMigDeviceHandle(MigDevice nvmlDevice, nvmlDevice *nvmlDevice) Return { + cMigDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&MigDevice)), cgoAllocsUnknown + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDeviceHandleFromMigDeviceHandle(cMigDevice, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmMetricsGet function as declared in nvml/nvml.h +func nvmlGpmMetricsGet(MetricsGet *nvmlGpmMetricsGetType) Return { + cMetricsGet, _ := (*C.nvmlGpmMetricsGet_t)(unsafe.Pointer(MetricsGet)), cgoAllocsUnknown + __ret := C.nvmlGpmMetricsGet(cMetricsGet) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmSampleFree function as declared in nvml/nvml.h +func nvmlGpmSampleFree(nvmlGpmSample nvmlGpmSample) Return { + cnvmlGpmSample, _ := *(*C.nvmlGpmSample_t)(unsafe.Pointer(&nvmlGpmSample)), cgoAllocsUnknown + __ret := C.nvmlGpmSampleFree(cnvmlGpmSample) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmSampleAlloc function as declared in nvml/nvml.h +func nvmlGpmSampleAlloc(nvmlGpmSample *nvmlGpmSample) Return { + cnvmlGpmSample, _ := (*C.nvmlGpmSample_t)(unsafe.Pointer(nvmlGpmSample)), cgoAllocsUnknown + __ret := C.nvmlGpmSampleAlloc(cnvmlGpmSample) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmSampleGet function as declared in nvml/nvml.h +func nvmlGpmSampleGet(nvmlDevice nvmlDevice, nvmlGpmSample nvmlGpmSample) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cnvmlGpmSample, _ := *(*C.nvmlGpmSample_t)(unsafe.Pointer(&nvmlGpmSample)), cgoAllocsUnknown + __ret := C.nvmlGpmSampleGet(cnvmlDevice, cnvmlGpmSample) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmMigSampleGet function as declared in nvml/nvml.h +func nvmlGpmMigSampleGet(nvmlDevice nvmlDevice, GpuInstanceId uint32, nvmlGpmSample nvmlGpmSample) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpuInstanceId, _ := (C.uint)(GpuInstanceId), cgoAllocsUnknown + cnvmlGpmSample, _ := *(*C.nvmlGpmSample_t)(unsafe.Pointer(&nvmlGpmSample)), cgoAllocsUnknown + __ret := C.nvmlGpmMigSampleGet(cnvmlDevice, cGpuInstanceId, cnvmlGpmSample) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmQueryDeviceSupport function as declared in nvml/nvml.h +func nvmlGpmQueryDeviceSupport(nvmlDevice nvmlDevice, GpmSupport *GpmSupport) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cGpmSupport, _ := (*C.nvmlGpmSupport_t)(unsafe.Pointer(GpmSupport)), cgoAllocsUnknown + __ret := C.nvmlGpmQueryDeviceSupport(cnvmlDevice, cGpmSupport) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmQueryIfStreamingEnabled function as declared in nvml/nvml.h +func nvmlGpmQueryIfStreamingEnabled(nvmlDevice nvmlDevice, State *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cState, _ := (*C.uint)(unsafe.Pointer(State)), cgoAllocsUnknown + __ret := C.nvmlGpmQueryIfStreamingEnabled(cnvmlDevice, cState) + __v := (Return)(__ret) + return __v +} + +// nvmlGpmSetStreamingEnabled function as declared in nvml/nvml.h +func nvmlGpmSetStreamingEnabled(nvmlDevice nvmlDevice, State uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cState, _ := (C.uint)(State), cgoAllocsUnknown + __ret := C.nvmlGpmSetStreamingEnabled(cnvmlDevice, cState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCapabilities function as declared in nvml/nvml.h +func nvmlDeviceGetCapabilities(nvmlDevice nvmlDevice, Caps *DeviceCapabilities) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCaps, _ := (*C.nvmlDeviceCapabilities_t)(unsafe.Pointer(Caps)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCapabilities(cnvmlDevice, cCaps) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceWorkloadPowerProfileGetProfilesInfo function as declared in nvml/nvml.h +func nvmlDeviceWorkloadPowerProfileGetProfilesInfo(nvmlDevice nvmlDevice, ProfilesInfo *WorkloadPowerProfileProfilesInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfilesInfo, _ := (*C.nvmlWorkloadPowerProfileProfilesInfo_t)(unsafe.Pointer(ProfilesInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceWorkloadPowerProfileGetProfilesInfo(cnvmlDevice, cProfilesInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceWorkloadPowerProfileGetCurrentProfiles function as declared in nvml/nvml.h +func nvmlDeviceWorkloadPowerProfileGetCurrentProfiles(nvmlDevice nvmlDevice, CurrentProfiles *WorkloadPowerProfileCurrentProfiles) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrentProfiles, _ := (*C.nvmlWorkloadPowerProfileCurrentProfiles_t)(unsafe.Pointer(CurrentProfiles)), cgoAllocsUnknown + __ret := C.nvmlDeviceWorkloadPowerProfileGetCurrentProfiles(cnvmlDevice, cCurrentProfiles) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceWorkloadPowerProfileSetRequestedProfiles function as declared in nvml/nvml.h +func nvmlDeviceWorkloadPowerProfileSetRequestedProfiles(nvmlDevice nvmlDevice, RequestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cRequestedProfiles, _ := (*C.nvmlWorkloadPowerProfileRequestedProfiles_t)(unsafe.Pointer(RequestedProfiles)), cgoAllocsUnknown + __ret := C.nvmlDeviceWorkloadPowerProfileSetRequestedProfiles(cnvmlDevice, cRequestedProfiles) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceWorkloadPowerProfileClearRequestedProfiles function as declared in nvml/nvml.h +func nvmlDeviceWorkloadPowerProfileClearRequestedProfiles(nvmlDevice nvmlDevice, RequestedProfiles *WorkloadPowerProfileRequestedProfiles) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cRequestedProfiles, _ := (*C.nvmlWorkloadPowerProfileRequestedProfiles_t)(unsafe.Pointer(RequestedProfiles)), cgoAllocsUnknown + __ret := C.nvmlDeviceWorkloadPowerProfileClearRequestedProfiles(cnvmlDevice, cRequestedProfiles) + __v := (Return)(__ret) + return __v +} + +// nvmlDevicePowerSmoothingActivatePresetProfile function as declared in nvml/nvml.h +func nvmlDevicePowerSmoothingActivatePresetProfile(nvmlDevice nvmlDevice, Profile *PowerSmoothingProfile) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfile, _ := (*C.nvmlPowerSmoothingProfile_t)(unsafe.Pointer(Profile)), cgoAllocsUnknown + __ret := C.nvmlDevicePowerSmoothingActivatePresetProfile(cnvmlDevice, cProfile) + __v := (Return)(__ret) + return __v +} + +// nvmlDevicePowerSmoothingUpdatePresetProfileParam function as declared in nvml/nvml.h +func nvmlDevicePowerSmoothingUpdatePresetProfileParam(nvmlDevice nvmlDevice, Profile *PowerSmoothingProfile) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfile, _ := (*C.nvmlPowerSmoothingProfile_t)(unsafe.Pointer(Profile)), cgoAllocsUnknown + __ret := C.nvmlDevicePowerSmoothingUpdatePresetProfileParam(cnvmlDevice, cProfile) + __v := (Return)(__ret) + return __v +} + +// nvmlDevicePowerSmoothingSetState function as declared in nvml/nvml.h +func nvmlDevicePowerSmoothingSetState(nvmlDevice nvmlDevice, State *PowerSmoothingState) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cState, _ := (*C.nvmlPowerSmoothingState_t)(unsafe.Pointer(State)), cgoAllocsUnknown + __ret := C.nvmlDevicePowerSmoothingSetState(cnvmlDevice, cState) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts function as declared in nvml/nvml.h +func nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(nvmlDevice nvmlDevice, ErrorCounts *EccSramUniqueUncorrectedErrorCounts) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cErrorCounts, _ := (*C.nvmlEccSramUniqueUncorrectedErrorCounts_t)(unsafe.Pointer(ErrorCounts)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(cnvmlDevice, cErrorCounts) + __v := (Return)(__ret) + return __v +} + +// nvmlInit_v1 function as declared in nvml/nvml.h +func nvmlInit_v1() Return { + __ret := C.nvmlInit() + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetCount_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetCount_v1(DeviceCount *uint32) Return { + cDeviceCount, _ := (*C.uint)(unsafe.Pointer(DeviceCount)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetCount(cDeviceCount) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByIndex_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByIndex_v1(Index uint32, nvmlDevice *nvmlDevice) Return { + cIndex, _ := (C.uint)(Index), cgoAllocsUnknown + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByIndex(cIndex, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetHandleByPciBusId_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetHandleByPciBusId_v1(PciBusId string, nvmlDevice *nvmlDevice) Return { + cPciBusId, _ := unpackPCharString(PciBusId) + cnvmlDevice, _ := (*C.nvmlDevice_t)(unsafe.Pointer(nvmlDevice)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetHandleByPciBusId(cPciBusId, cnvmlDevice) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPciInfo_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetPciInfo_v1(nvmlDevice nvmlDevice, Pci *PciInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPciInfo(cnvmlDevice, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetPciInfo_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetPciInfo_v2(nvmlDevice nvmlDevice, Pci *PciInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetPciInfo_v2(cnvmlDevice, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetNvLinkRemotePciInfo_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetNvLinkRemotePciInfo_v1(nvmlDevice nvmlDevice, Link uint32, Pci *PciInfo) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cLink, _ := (C.uint)(Link), cgoAllocsUnknown + cPci, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(Pci)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetNvLinkRemotePciInfo(cnvmlDevice, cLink, cPci) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGridLicensableFeatures_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetGridLicensableFeatures_v1(nvmlDevice nvmlDevice, PGridLicensableFeatures *GridLicensableFeatures) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPGridLicensableFeatures, _ := (*C.nvmlGridLicensableFeatures_t)(unsafe.Pointer(PGridLicensableFeatures)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGridLicensableFeatures(cnvmlDevice, cPGridLicensableFeatures) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGridLicensableFeatures_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetGridLicensableFeatures_v2(nvmlDevice nvmlDevice, PGridLicensableFeatures *GridLicensableFeatures) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPGridLicensableFeatures, _ := (*C.nvmlGridLicensableFeatures_t)(unsafe.Pointer(PGridLicensableFeatures)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGridLicensableFeatures_v2(cnvmlDevice, cPGridLicensableFeatures) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGridLicensableFeatures_v3 function as declared in nvml/nvml.h +func nvmlDeviceGetGridLicensableFeatures_v3(nvmlDevice nvmlDevice, PGridLicensableFeatures *GridLicensableFeatures) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cPGridLicensableFeatures, _ := (*C.nvmlGridLicensableFeatures_t)(unsafe.Pointer(PGridLicensableFeatures)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGridLicensableFeatures_v3(cnvmlDevice, cPGridLicensableFeatures) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceRemoveGpu_v1 function as declared in nvml/nvml.h +func nvmlDeviceRemoveGpu_v1(PciInfo *PciInfo) Return { + cPciInfo, _ := (*C.nvmlPciInfo_t)(unsafe.Pointer(PciInfo)), cgoAllocsUnknown + __ret := C.nvmlDeviceRemoveGpu(cPciInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlEventSetWait_v1 function as declared in nvml/nvml.h +func nvmlEventSetWait_v1(Set nvmlEventSet, Data *nvmlEventData, Timeoutms uint32) Return { + cSet, _ := *(*C.nvmlEventSet_t)(unsafe.Pointer(&Set)), cgoAllocsUnknown + cData, _ := (*C.nvmlEventData_t)(unsafe.Pointer(Data)), cgoAllocsUnknown + cTimeoutms, _ := (C.uint)(Timeoutms), cgoAllocsUnknown + __ret := C.nvmlEventSetWait(cSet, cData, cTimeoutms) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetAttributes_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetAttributes_v1(nvmlDevice nvmlDevice, Attributes *DeviceAttributes) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cAttributes, _ := (*C.nvmlDeviceAttributes_t)(unsafe.Pointer(Attributes)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetAttributes(cnvmlDevice, cAttributes) + __v := (Return)(__ret) + return __v +} + +// nvmlComputeInstanceGetInfo_v1 function as declared in nvml/nvml.h +func nvmlComputeInstanceGetInfo_v1(nvmlComputeInstance nvmlComputeInstance, Info *nvmlComputeInstanceInfo) Return { + cnvmlComputeInstance, _ := *(*C.nvmlComputeInstance_t)(unsafe.Pointer(&nvmlComputeInstance)), cgoAllocsUnknown + cInfo, _ := (*C.nvmlComputeInstanceInfo_t)(unsafe.Pointer(Info)), cgoAllocsUnknown + __ret := C.nvmlComputeInstanceGetInfo(cnvmlComputeInstance, cInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetComputeRunningProcesses_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetComputeRunningProcesses_v1(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v1_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetComputeRunningProcesses(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetComputeRunningProcesses_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetComputeRunningProcesses_v2(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v2_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetComputeRunningProcesses_v2(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGraphicsRunningProcesses_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetGraphicsRunningProcesses_v1(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v1_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGraphicsRunningProcesses(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGraphicsRunningProcesses_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetGraphicsRunningProcesses_v2(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v2_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGraphicsRunningProcesses_v2(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMPSComputeRunningProcesses_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetMPSComputeRunningProcesses_v1(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v1) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v1_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMPSComputeRunningProcesses(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetMPSComputeRunningProcesses_v2 function as declared in nvml/nvml.h +func nvmlDeviceGetMPSComputeRunningProcesses_v2(nvmlDevice nvmlDevice, InfoCount *uint32, Infos *ProcessInfo_v2) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cInfoCount, _ := (*C.uint)(unsafe.Pointer(InfoCount)), cgoAllocsUnknown + cInfos, _ := (*C.nvmlProcessInfo_v2_t)(unsafe.Pointer(Infos)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetMPSComputeRunningProcesses_v2(cnvmlDevice, cInfoCount, cInfos) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetGpuInstancePossiblePlacements_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetGpuInstancePossiblePlacements_v1(nvmlDevice nvmlDevice, ProfileId uint32, Placements *GpuInstancePlacement, Count *uint32) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cProfileId, _ := (C.uint)(ProfileId), cgoAllocsUnknown + cPlacements, _ := (*C.nvmlGpuInstancePlacement_t)(unsafe.Pointer(Placements)), cgoAllocsUnknown + cCount, _ := (*C.uint)(unsafe.Pointer(Count)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetGpuInstancePossiblePlacements(cnvmlDevice, cProfileId, cPlacements, cCount) + __v := (Return)(__ret) + return __v +} + +// nvmlVgpuInstanceGetLicenseInfo_v1 function as declared in nvml/nvml.h +func nvmlVgpuInstanceGetLicenseInfo_v1(nvmlVgpuInstance nvmlVgpuInstance, LicenseInfo *VgpuLicenseInfo) Return { + cnvmlVgpuInstance, _ := (C.nvmlVgpuInstance_t)(nvmlVgpuInstance), cgoAllocsUnknown + cLicenseInfo, _ := (*C.nvmlVgpuLicenseInfo_t)(unsafe.Pointer(LicenseInfo)), cgoAllocsUnknown + __ret := C.nvmlVgpuInstanceGetLicenseInfo(cnvmlVgpuInstance, cLicenseInfo) + __v := (Return)(__ret) + return __v +} + +// nvmlDeviceGetDriverModel_v1 function as declared in nvml/nvml.h +func nvmlDeviceGetDriverModel_v1(nvmlDevice nvmlDevice, Current *DriverModel, Pending *DriverModel) Return { + cnvmlDevice, _ := *(*C.nvmlDevice_t)(unsafe.Pointer(&nvmlDevice)), cgoAllocsUnknown + cCurrent, _ := (*C.nvmlDriverModel_t)(unsafe.Pointer(Current)), cgoAllocsUnknown + cPending, _ := (*C.nvmlDriverModel_t)(unsafe.Pointer(Pending)), cgoAllocsUnknown + __ret := C.nvmlDeviceGetDriverModel(cnvmlDevice, cCurrent, cPending) + __v := (Return)(__ret) + return __v +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.h b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.h new file mode 100644 index 00000000..917a8c93 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/nvml.h @@ -0,0 +1,13557 @@ +/*** NVML VERSION: 13.0.39 ***/ +/*** From https://developer.download.nvidia.com/compute/cuda/redist/cuda_nvml_dev/linux-x86_64/cuda_nvml_dev-linux-x86_64-13.0.39-archive.tar.xz ***/ +/* + * Copyright 1993-2025 NVIDIA Corporation. All rights reserved. + * + * NOTICE TO USER: + * + * This source code is subject to NVIDIA ownership rights under U.S. and + * international Copyright laws. Users and possessors of this source code + * are hereby granted a nonexclusive, royalty-free license to use this code + * in individual and commercial software. + * + * NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE + * CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR + * IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH + * REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. + * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, + * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS + * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE + * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE + * OR PERFORMANCE OF THIS SOURCE CODE. + * + * U.S. Government End Users. This source code is a "commercial item" as + * that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of + * "commercial computer software" and "commercial computer software + * documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) + * and is provided to the U.S. Government only as a commercial end item. + * Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through + * 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the + * source code with only those rights set forth herein. + * + * Any use of this source code in individual and commercial software must + * include, in the user documentation and internal comments to the code, + * the above Disclaimer and U.S. Government End Users Notice. + */ + +/* +NVML API Reference + +The NVIDIA Management Library (NVML) is a C-based programmatic interface for monitoring and +managing various states within NVIDIA Tesla &tm; GPUs. It is intended to be a platform for building +3rd party applications, and is also the underlying library for the NVIDIA-supported nvidia-smi +tool. NVML is thread-safe so it is safe to make simultaneous NVML calls from multiple threads. + +API Documentation + +Supported platforms: +- Windows: Windows Server 2008 R2 64bit, Windows Server 2012 R2 64bit, Windows 7 64bit, Windows 8 64bit, Windows 10 64bit +- Linux: 32-bit and 64-bit +- Hypervisors: Windows Server 2008R2/2012 Hyper-V 64bit, Citrix XenServer 6.2 SP1+, VMware ESX 5.1/5.5 + +Supported products: +- Full Support + - All Tesla products, starting with the Fermi architecture + - All Quadro products, starting with the Fermi architecture + - All vGPU Software products, starting with the Kepler architecture + - Selected GeForce Titan products +- Limited Support + - All Geforce products, starting with the Fermi architecture + +The NVML library can be found at \%ProgramW6432\%\\"NVIDIA Corporation"\\NVSMI\\ on Windows. It is +not be added to the system path by default. To dynamically link to NVML, add this path to the PATH +environmental variable. To dynamically load NVML, call LoadLibrary with this path. + +On Linux the NVML library will be found on the standard library path. For 64 bit Linux, both the 32 bit +and 64 bit NVML libraries will be installed. + +Online documentation for this library is available at http://docs.nvidia.com/deploy/nvml-api/index.html +*/ + +#ifndef __nvml_nvml_h__ +#define __nvml_nvml_h__ + +#ifdef __cplusplus +extern "C" { +#endif + +/* + * On Windows, set up methods for DLL export + * define NVML_STATIC_IMPORT when using nvml_loader library + */ +#if defined _WINDOWS + #if !defined NVML_STATIC_IMPORT + #if defined NVML_LIB_EXPORT + #define DECLDIR __declspec(dllexport) + #else + #define DECLDIR __declspec(dllimport) + #endif + #else + #define DECLDIR + #endif +#else + #define DECLDIR +#endif + +/* + * Deprecation definition. Starting CUDA 13.1 this will change to: + * #if defined _WINDOWS + * #define DEPRECATED(ver) __declspec(deprecated) + * #else + * #define DEPRECATED(ver) __attribute__((deprecated)) + * #endif + */ +#define DEPRECATED(ver) /* nop in CUDA 13.0, enabled in CUDA 13.1 */ + + #define NVML_MCDM_SUPPORT + +/** + * NVML API versioning support + */ +#define NVML_API_VERSION 13 +#define NVML_API_VERSION_STR "13" +/** + * Defining NVML_NO_UNVERSIONED_FUNC_DEFS will disable "auto upgrading" of APIs. + * e.g. the user will have to call nvmlInit_v2 instead of nvmlInit. Enable this + * guard if you need to support older versions of the API + */ +#ifndef NVML_NO_UNVERSIONED_FUNC_DEFS + #define nvmlInit nvmlInit_v2 + #define nvmlDeviceGetPciInfo nvmlDeviceGetPciInfo_v3 + #define nvmlDeviceGetCount nvmlDeviceGetCount_v2 + #define nvmlDeviceGetHandleByIndex nvmlDeviceGetHandleByIndex_v2 + #define nvmlDeviceGetHandleByPciBusId nvmlDeviceGetHandleByPciBusId_v2 + #define nvmlDeviceGetNvLinkRemotePciInfo nvmlDeviceGetNvLinkRemotePciInfo_v2 + #define nvmlDeviceRemoveGpu nvmlDeviceRemoveGpu_v2 + #define nvmlDeviceGetGridLicensableFeatures nvmlDeviceGetGridLicensableFeatures_v4 + #define nvmlEventSetWait nvmlEventSetWait_v2 + #define nvmlDeviceGetAttributes nvmlDeviceGetAttributes_v2 + #define nvmlComputeInstanceGetInfo nvmlComputeInstanceGetInfo_v2 + #define nvmlDeviceGetComputeRunningProcesses nvmlDeviceGetComputeRunningProcesses_v3 + #define nvmlDeviceGetGraphicsRunningProcesses nvmlDeviceGetGraphicsRunningProcesses_v3 + #define nvmlDeviceGetMPSComputeRunningProcesses nvmlDeviceGetMPSComputeRunningProcesses_v3 + #define nvmlBlacklistDeviceInfo_t nvmlExcludedDeviceInfo_t + #define nvmlGetBlacklistDeviceCount nvmlGetExcludedDeviceCount + #define nvmlGetBlacklistDeviceInfoByIndex nvmlGetExcludedDeviceInfoByIndex + #define nvmlDeviceGetGpuInstancePossiblePlacements nvmlDeviceGetGpuInstancePossiblePlacements_v2 + #define nvmlVgpuInstanceGetLicenseInfo nvmlVgpuInstanceGetLicenseInfo_v2 + #define nvmlDeviceGetDriverModel nvmlDeviceGetDriverModel_v2 +#endif // #ifndef NVML_NO_UNVERSIONED_FUNC_DEFS + +#define NVML_STRUCT_VERSION(data, ver) (unsigned int)(sizeof(nvml ## data ## _v ## ver ## _t) | \ + (ver << 24U)) + +/***************************************************************************************************/ +/** @defgroup nvmlDeviceStructs Device Structs + * @{ + */ +/***************************************************************************************************/ + +/** + * Special constant that some fields take when they are not available. + * Used when only part of the struct is not available. + * + * Each structure explicitly states when to check for this value. + */ +#define NVML_VALUE_NOT_AVAILABLE (-1) + +typedef struct +{ + struct nvmlDevice_st* handle; +} nvmlDevice_t; + +typedef struct +{ + struct nvmlGpuInstance_st* handle; +} nvmlGpuInstance_t; + +/** + * Buffer size guaranteed to be large enough for pci bus id + */ +#define NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE 32 + +/** + * Buffer size guaranteed to be large enough for pci bus id for \p busIdLegacy + */ +#define NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE 16 + +/** + * PCI information about a GPU device. + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int domain; //!< The PCI domain on which the device's bus resides, 0 to 0xffffffff + unsigned int bus; //!< The bus on which the device resides, 0 to 0xff + unsigned int device; //!< The device's id on the bus, 0 to 31 + + unsigned int pciDeviceId; //!< The combined 16-bit device id and 16-bit vendor id + unsigned int pciSubSystemId; //!< The 32-bit Sub System Device ID + + unsigned int baseClass; //!< The 8-bit PCI base class code + unsigned int subClass; //!< The 8-bit PCI sub class code + + char busId[NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE]; //!< The tuple domain:bus:device.function PCI identifier (& NULL terminator) +} nvmlPciInfoExt_v1_t; +typedef nvmlPciInfoExt_v1_t nvmlPciInfoExt_t; +#define nvmlPciInfoExt_v1 NVML_STRUCT_VERSION(PciInfoExt, 1) + +/** + * PCI information about a GPU device. + */ +typedef struct nvmlPciInfo_st +{ + char busIdLegacy[NVML_DEVICE_PCI_BUS_ID_BUFFER_V2_SIZE]; //!< The legacy tuple domain:bus:device.function PCI identifier (& NULL terminator) + unsigned int domain; //!< The PCI domain on which the device's bus resides, 0 to 0xffffffff + unsigned int bus; //!< The bus on which the device resides, 0 to 0xff + unsigned int device; //!< The device's id on the bus, 0 to 31 + unsigned int pciDeviceId; //!< The combined 16-bit device id and 16-bit vendor id + + // Added in NVML 2.285 API + unsigned int pciSubSystemId; //!< The 32-bit Sub System Device ID + + char busId[NVML_DEVICE_PCI_BUS_ID_BUFFER_SIZE]; //!< The tuple domain:bus:device.function PCI identifier (& NULL terminator) +} nvmlPciInfo_t; + +/** + * PCI format string for \p busIdLegacy + */ +#define NVML_DEVICE_PCI_BUS_ID_LEGACY_FMT "%04X:%02X:%02X.0" + +/** + * PCI format string for \p busId + */ +#define NVML_DEVICE_PCI_BUS_ID_FMT "%08X:%02X:%02X.0" + +/** + * Utility macro for filling the pci bus id format from a nvmlPciInfo_t + */ +#define NVML_DEVICE_PCI_BUS_ID_FMT_ARGS(pciInfo) (pciInfo)->domain, \ + (pciInfo)->bus, \ + (pciInfo)->device + +/** + * Detailed ECC error counts for a device. + * + * @deprecated Different GPU families can have different memory error counters + * See \ref nvmlDeviceGetMemoryErrorCounter + */ +typedef struct nvmlEccErrorCounts_st +{ + unsigned long long l1Cache; //!< L1 cache errors + unsigned long long l2Cache; //!< L2 cache errors + unsigned long long deviceMemory; //!< Device memory errors + unsigned long long registerFile; //!< Register file errors +} nvmlEccErrorCounts_t; + +/** + * Utilization information for a device. + * Each sample period may be between 1 second and 1/6 second, depending on the product being queried. + */ +typedef struct nvmlUtilization_st +{ + unsigned int gpu; //!< Percent of time over the past sample period during which one or more kernels was executing on the GPU + unsigned int memory; //!< Percent of time over the past sample period during which global (device) memory was being read or written +} nvmlUtilization_t; + +/** + * Memory allocation information for a device (v1). + * The total amount is equal to the sum of the amounts of free and used memory. + */ +typedef struct nvmlMemory_st +{ + unsigned long long total; //!< Total physical device memory (in bytes) + unsigned long long free; //!< Unallocated device memory (in bytes) + unsigned long long used; //!< Sum of Reserved and Allocated device memory (in bytes). + //!< Note that the driver/GPU always sets aside a small amount of memory for bookkeeping +} nvmlMemory_t; + +/** + * Memory allocation information for a device (v2). + * + * Version 2 adds versioning for the struct and the amount of system-reserved memory as an output. + */ +typedef struct nvmlMemory_v2_st +{ + unsigned int version; //!< Structure format version (must be 2) + unsigned long long total; //!< Total physical device memory (in bytes) + unsigned long long reserved; //!< Device memory (in bytes) reserved for system use (driver or firmware) + unsigned long long free; //!< Unallocated device memory (in bytes) + unsigned long long used; //!< Allocated device memory (in bytes). +} nvmlMemory_v2_t; + +#define nvmlMemory_v2 NVML_STRUCT_VERSION(Memory, 2) + +/** + * BAR1 Memory allocation Information for a device + */ +typedef struct nvmlBAR1Memory_st +{ + unsigned long long bar1Total; //!< Total BAR1 Memory (in bytes) + unsigned long long bar1Free; //!< Unallocated BAR1 Memory (in bytes) + unsigned long long bar1Used; //!< Allocated Used Memory (in bytes) +}nvmlBAR1Memory_t; + +/** + * Information about running compute processes on the GPU, legacy version + * for older versions of the API. + */ +typedef struct nvmlProcessInfo_v1_st +{ + unsigned int pid; //!< Process ID + unsigned long long usedGpuMemory; //!< Amount of used GPU memory in bytes. + //! Under WDDM, \ref NVML_VALUE_NOT_AVAILABLE is always reported + //! because Windows KMD manages all the memory and not the NVIDIA driver +} nvmlProcessInfo_v1_t; + +/** + * Information about running compute processes on the GPU + */ +typedef struct nvmlProcessInfo_v2_st +{ + unsigned int pid; //!< Process ID + unsigned long long usedGpuMemory; //!< Amount of used GPU memory in bytes. + //! Under WDDM, \ref NVML_VALUE_NOT_AVAILABLE is always reported + //! because Windows KMD manages all the memory and not the NVIDIA driver + unsigned int gpuInstanceId; //!< If MIG is enabled, stores a valid GPU instance ID. gpuInstanceId is set to + // 0xFFFFFFFF otherwise. + unsigned int computeInstanceId; //!< If MIG is enabled, stores a valid compute instance ID. computeInstanceId is set to + // 0xFFFFFFFF otherwise. +} nvmlProcessInfo_v2_t, nvmlProcessInfo_t; + +/** + * Information about running process on the GPU with protected memory + */ +typedef struct +{ + unsigned int pid; //!< Process ID + unsigned long long usedGpuMemory; //!< Amount of used GPU memory in bytes. + //! Under WDDM, \ref NVML_VALUE_NOT_AVAILABLE is always reported + //! because Windows KMD manages all the memory and not the NVIDIA driver + unsigned int gpuInstanceId; //!< If MIG is enabled, stores a valid GPU instance ID. gpuInstanceId is + // set to 0xFFFFFFFF otherwise. + unsigned int computeInstanceId; //!< If MIG is enabled, stores a valid compute instance ID. computeInstanceId + // is set to 0xFFFFFFFF otherwise. + unsigned long long usedGpuCcProtectedMemory; //!< Amount of used GPU conf compute protected memory in bytes. +} nvmlProcessDetail_v1_t; + +/** + * Information about all running processes on the GPU for the given mode + */ +typedef struct +{ + unsigned int version; //!< Struct version, MUST be nvmlProcessDetailList_v1 + unsigned int mode; //!< Process mode(Compute/Graphics/MPSCompute) + unsigned int numProcArrayEntries; //!< Number of process entries in procArray + nvmlProcessDetail_v1_t *procArray; //!< Process array +} nvmlProcessDetailList_v1_t; + +typedef nvmlProcessDetailList_v1_t nvmlProcessDetailList_t; + +/** + * nvmlProcessDetailList version + */ +#define nvmlProcessDetailList_v1 NVML_STRUCT_VERSION(ProcessDetailList, 1) + +typedef struct nvmlDeviceAttributes_st +{ + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int sharedCopyEngineCount; //!< Shared Copy Engine count + unsigned int sharedDecoderCount; //!< Shared Decoder Engine count + unsigned int sharedEncoderCount; //!< Shared Encoder Engine count + unsigned int sharedJpegCount; //!< Shared JPEG Engine count + unsigned int sharedOfaCount; //!< Shared OFA Engine count + unsigned int gpuInstanceSliceCount; //!< GPU instance slice count + unsigned int computeInstanceSliceCount; //!< Compute instance slice count + unsigned long long memorySizeMB; //!< Device memory size (in MiB) +} nvmlDeviceAttributes_t; + +/** + * C2C Mode information for a device + */ +typedef struct +{ + unsigned int isC2cEnabled; +} nvmlC2cModeInfo_v1_t; + +#define nvmlC2cModeInfo_v1 NVML_STRUCT_VERSION(C2cModeInfo, 1) + +/** + * Enum to represent device addressing mode values + */ +typedef enum +{ + NVML_DEVICE_ADDRESSING_MODE_NONE = 0, //!< No active mode + NVML_DEVICE_ADDRESSING_MODE_HMM = 1, //!< Heterogeneous Memory Management mode + NVML_DEVICE_ADDRESSING_MODE_ATS = 2, //!< Address Translation Services mode +} nvmlDeviceAddressingModeType_t; + +/** + * Struct to represent device addressing mode information + */ +typedef struct +{ + unsigned int version; //!< API version + unsigned int value; //!< One of \ref nvmlDeviceAddressingModeType_t +} nvmlDeviceAddressingMode_v1_t; +typedef nvmlDeviceAddressingMode_v1_t nvmlDeviceAddressingMode_t; + +#define nvmlDeviceAddressingMode_v1 NVML_STRUCT_VERSION(DeviceAddressingMode, 1) + +/** + * Struct to represent the NVML repair status + */ +typedef struct +{ + unsigned int version; //!< API version number + unsigned int bChannelRepairPending; //!< Reference to \a unsigned int + unsigned int bTpcRepairPending; //!< Reference to \a unsigned int +} nvmlRepairStatus_v1_t; +typedef nvmlRepairStatus_v1_t nvmlRepairStatus_t; + +#define nvmlRepairStatus_v1 NVML_STRUCT_VERSION(RepairStatus, 1) + +/** + * Possible values that classify the remap availability for each bank. The max + * field will contain the number of banks that have maximum remap availability + * (all reserved rows are available). None means that there are no reserved + * rows available. + */ +typedef struct nvmlRowRemapperHistogramValues_st +{ + unsigned int max; + unsigned int high; + unsigned int partial; + unsigned int low; + unsigned int none; +} nvmlRowRemapperHistogramValues_t; + +/** + * Enum to represent type of bridge chip + */ +typedef enum nvmlBridgeChipType_enum +{ + NVML_BRIDGE_CHIP_PLX = 0, + NVML_BRIDGE_CHIP_BRO4 = 1 +}nvmlBridgeChipType_t; + +/** + * Maximum number of NvLink links supported + */ +#define NVML_NVLINK_MAX_LINKS 18 + +/** + * Enum to represent the NvLink utilization counter packet units + */ +typedef enum nvmlNvLinkUtilizationCountUnits_enum +{ + NVML_NVLINK_COUNTER_UNIT_CYCLES = 0, // count by cycles + NVML_NVLINK_COUNTER_UNIT_PACKETS = 1, // count by packets + NVML_NVLINK_COUNTER_UNIT_BYTES = 2, // count by bytes + NVML_NVLINK_COUNTER_UNIT_RESERVED = 3, // count reserved for internal use + // this must be last + NVML_NVLINK_COUNTER_UNIT_COUNT +} nvmlNvLinkUtilizationCountUnits_t; + +/** + * Enum to represent the NvLink utilization counter packet types to count + * ** this is ONLY applicable with the units as packets or bytes + * ** as specified in \a nvmlNvLinkUtilizationCountUnits_t + * ** all packet filter descriptions are target GPU centric + * ** these can be "OR'd" together + */ +typedef enum nvmlNvLinkUtilizationCountPktTypes_enum +{ + NVML_NVLINK_COUNTER_PKTFILTER_NOP = 0x1, // no operation packets + NVML_NVLINK_COUNTER_PKTFILTER_READ = 0x2, // read packets + NVML_NVLINK_COUNTER_PKTFILTER_WRITE = 0x4, // write packets + NVML_NVLINK_COUNTER_PKTFILTER_RATOM = 0x8, // reduction atomic requests + NVML_NVLINK_COUNTER_PKTFILTER_NRATOM = 0x10, // non-reduction atomic requests + NVML_NVLINK_COUNTER_PKTFILTER_FLUSH = 0x20, // flush requests + NVML_NVLINK_COUNTER_PKTFILTER_RESPDATA = 0x40, // responses with data + NVML_NVLINK_COUNTER_PKTFILTER_RESPNODATA = 0x80, // responses without data + NVML_NVLINK_COUNTER_PKTFILTER_ALL = 0xFF // all packets +} nvmlNvLinkUtilizationCountPktTypes_t; + +/** + * Struct to define the NVLINK counter controls + */ +typedef struct nvmlNvLinkUtilizationControl_st +{ + nvmlNvLinkUtilizationCountUnits_t units; + nvmlNvLinkUtilizationCountPktTypes_t pktfilter; +} nvmlNvLinkUtilizationControl_t; + +/** + * Enum to represent NvLink queryable capabilities + */ +typedef enum nvmlNvLinkCapability_enum +{ + NVML_NVLINK_CAP_P2P_SUPPORTED = 0, // P2P over NVLink is supported + NVML_NVLINK_CAP_SYSMEM_ACCESS = 1, // Access to system memory is supported + NVML_NVLINK_CAP_P2P_ATOMICS = 2, // P2P atomics are supported + NVML_NVLINK_CAP_SYSMEM_ATOMICS= 3, // System memory atomics are supported + NVML_NVLINK_CAP_SLI_BRIDGE = 4, // SLI is supported over this link + NVML_NVLINK_CAP_VALID = 5, // Link is supported on this device + // should be last + NVML_NVLINK_CAP_COUNT +} nvmlNvLinkCapability_t; + +/** + * Enum to represent NvLink queryable error counters + */ +typedef enum nvmlNvLinkErrorCounter_enum +{ + NVML_NVLINK_ERROR_DL_REPLAY = 0, // Data link transmit replay error counter + NVML_NVLINK_ERROR_DL_RECOVERY = 1, // Data link transmit recovery error counter + NVML_NVLINK_ERROR_DL_CRC_FLIT = 2, // Data link receive flow control digit CRC error counter + NVML_NVLINK_ERROR_DL_CRC_DATA = 3, // Data link receive data CRC error counter + NVML_NVLINK_ERROR_DL_ECC_DATA = 4, // Data link receive data ECC error counter + + // this must be last + NVML_NVLINK_ERROR_COUNT +} nvmlNvLinkErrorCounter_t; + +/** + * Enum to represent NvLink's remote device type + */ +typedef enum nvmlIntNvLinkDeviceType_enum +{ + NVML_NVLINK_DEVICE_TYPE_GPU = 0x00, + NVML_NVLINK_DEVICE_TYPE_IBMNPU = 0x01, + NVML_NVLINK_DEVICE_TYPE_SWITCH = 0x02, + NVML_NVLINK_DEVICE_TYPE_UNKNOWN = 0xFF +} nvmlIntNvLinkDeviceType_t; + +/** + * Represents level relationships within a system between two GPUs + * The enums are spaced to allow for future relationships + */ +typedef enum nvmlGpuLevel_enum +{ + NVML_TOPOLOGY_INTERNAL = 0, // e.g. Tesla K80 + NVML_TOPOLOGY_SINGLE = 10, // all devices that only need traverse a single PCIe switch + NVML_TOPOLOGY_MULTIPLE = 20, // all devices that need not traverse a host bridge + NVML_TOPOLOGY_HOSTBRIDGE = 30, // all devices that are connected to the same host bridge + NVML_TOPOLOGY_NODE = 40, // all devices that are connected to the same NUMA node but possibly multiple host bridges + NVML_TOPOLOGY_SYSTEM = 50 // all devices in the system + + // there is purposefully no COUNT here because of the need for spacing above +} nvmlGpuTopologyLevel_t; + +/* Compatibility for CPU->NODE renaming */ +#define NVML_TOPOLOGY_CPU NVML_TOPOLOGY_NODE + +/* P2P Capability Index Status*/ +typedef enum nvmlGpuP2PStatus_enum +{ + NVML_P2P_STATUS_OK = 0, + NVML_P2P_STATUS_CHIPSET_NOT_SUPPORED, + NVML_P2P_STATUS_CHIPSET_NOT_SUPPORTED = NVML_P2P_STATUS_CHIPSET_NOT_SUPPORED, + NVML_P2P_STATUS_GPU_NOT_SUPPORTED, + NVML_P2P_STATUS_IOH_TOPOLOGY_NOT_SUPPORTED, + NVML_P2P_STATUS_DISABLED_BY_REGKEY, + NVML_P2P_STATUS_NOT_SUPPORTED, + NVML_P2P_STATUS_UNKNOWN + +} nvmlGpuP2PStatus_t; + +/* P2P Capability Index*/ +typedef enum nvmlGpuP2PCapsIndex_enum +{ + NVML_P2P_CAPS_INDEX_READ = 0, + NVML_P2P_CAPS_INDEX_WRITE = 1, + NVML_P2P_CAPS_INDEX_NVLINK = 2, + NVML_P2P_CAPS_INDEX_ATOMICS = 3, + NVML_P2P_CAPS_INDEX_PCI = 4, + /* + * DO NOT USE! NVML_P2P_CAPS_INDEX_PROP is deprecated. + * Use NVML_P2P_CAPS_INDEX_PCI instead. + */ + NVML_P2P_CAPS_INDEX_PROP = NVML_P2P_CAPS_INDEX_PCI, + NVML_P2P_CAPS_INDEX_UNKNOWN = 5, +}nvmlGpuP2PCapsIndex_t; + +/** + * Maximum limit on Physical Bridges per Board + */ +#define NVML_MAX_PHYSICAL_BRIDGE (128) + +/** + * Information about the Bridge Chip Firmware + */ +typedef struct nvmlBridgeChipInfo_st +{ + nvmlBridgeChipType_t type; //!< Type of Bridge Chip + unsigned int fwVersion; //!< Firmware Version. 0=Version is unavailable +}nvmlBridgeChipInfo_t; + +/** + * This structure stores the complete Hierarchy of the Bridge Chip within the board. The immediate + * bridge is stored at index 0 of bridgeInfoList, parent to immediate bridge is at index 1 and so forth. + */ +typedef struct nvmlBridgeChipHierarchy_st +{ + unsigned char bridgeCount; //!< Number of Bridge Chips on the Board + nvmlBridgeChipInfo_t bridgeChipInfo[NVML_MAX_PHYSICAL_BRIDGE]; //!< Hierarchy of Bridge Chips on the board +}nvmlBridgeChipHierarchy_t; + +/** + * Represents Type of Sampling Event + */ +typedef enum nvmlSamplingType_enum +{ + NVML_TOTAL_POWER_SAMPLES = 0, //!< To represent total power drawn by GPU + NVML_GPU_UTILIZATION_SAMPLES = 1, //!< To represent percent of time during which one or more kernels was executing on the GPU + NVML_MEMORY_UTILIZATION_SAMPLES = 2, //!< To represent percent of time during which global (device) memory was being read or written + NVML_ENC_UTILIZATION_SAMPLES = 3, //!< To represent percent of time during which NVENC remains busy + NVML_DEC_UTILIZATION_SAMPLES = 4, //!< To represent percent of time during which NVDEC remains busy + NVML_PROCESSOR_CLK_SAMPLES = 5, //!< To represent processor clock samples + NVML_MEMORY_CLK_SAMPLES = 6, //!< To represent memory clock samples + NVML_MODULE_POWER_SAMPLES = 7, //!< To represent module power samples for total module starting Grace Hopper + NVML_JPG_UTILIZATION_SAMPLES = 8, //!< To represent percent of time during which NVJPG remains busy + NVML_OFA_UTILIZATION_SAMPLES = 9, //!< To represent percent of time during which NVOFA remains busy + + // Keep this last + NVML_SAMPLINGTYPE_COUNT +}nvmlSamplingType_t; + +/** + * Represents the queryable PCIe utilization counters + */ +typedef enum nvmlPcieUtilCounter_enum +{ + NVML_PCIE_UTIL_TX_BYTES = 0, // 1KB granularity + NVML_PCIE_UTIL_RX_BYTES = 1, // 1KB granularity + + // Keep this last + NVML_PCIE_UTIL_COUNT +} nvmlPcieUtilCounter_t; + +/** + * Represents the type for sample value returned + */ +typedef enum nvmlValueType_enum +{ + NVML_VALUE_TYPE_DOUBLE = 0, + NVML_VALUE_TYPE_UNSIGNED_INT = 1, + NVML_VALUE_TYPE_UNSIGNED_LONG = 2, + NVML_VALUE_TYPE_UNSIGNED_LONG_LONG = 3, + NVML_VALUE_TYPE_SIGNED_LONG_LONG = 4, + NVML_VALUE_TYPE_SIGNED_INT = 5, + NVML_VALUE_TYPE_UNSIGNED_SHORT = 6, + + // Keep this last + NVML_VALUE_TYPE_COUNT +}nvmlValueType_t; + +/** + * Union to represent different types of Value + */ +typedef union nvmlValue_st +{ + double dVal; //!< If the value is double + int siVal; //!< If the value is signed int + unsigned int uiVal; //!< If the value is unsigned int + unsigned long ulVal; //!< If the value is unsigned long + unsigned long long ullVal; //!< If the value is unsigned long long + signed long long sllVal; //!< If the value is signed long long + unsigned short usVal; //!< If the value is unsigned short +}nvmlValue_t; + +/** + * Information for Sample + */ +typedef struct nvmlSample_st +{ + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + nvmlValue_t sampleValue; //!< Sample Value +}nvmlSample_t; + +/** + * Represents type of perf policy for which violation times can be queried + */ +typedef enum nvmlPerfPolicyType_enum +{ + NVML_PERF_POLICY_POWER = 0, //!< How long did power violations cause the GPU to be below application clocks + NVML_PERF_POLICY_THERMAL = 1, //!< How long did thermal violations cause the GPU to be below application clocks + NVML_PERF_POLICY_SYNC_BOOST = 2, //!< How long did sync boost cause the GPU to be below application clocks + NVML_PERF_POLICY_BOARD_LIMIT = 3, //!< How long did the board limit cause the GPU to be below application clocks + NVML_PERF_POLICY_LOW_UTILIZATION = 4, //!< How long did low utilization cause the GPU to be below application clocks + NVML_PERF_POLICY_RELIABILITY = 5, //!< How long did the board reliability limit cause the GPU to be below application clocks + + NVML_PERF_POLICY_TOTAL_APP_CLOCKS = 10, //!< Total time the GPU was held below application clocks by any limiter (0 - 5 above) + NVML_PERF_POLICY_TOTAL_BASE_CLOCKS = 11, //!< Total time the GPU was held below base clocks + + // Keep this last + NVML_PERF_POLICY_COUNT +}nvmlPerfPolicyType_t; + +/** + * Struct to hold perf policy violation status data + */ +typedef struct nvmlViolationTime_st +{ + unsigned long long referenceTime; //!< referenceTime represents CPU timestamp in microseconds + unsigned long long violationTime; //!< violationTime in Nanoseconds +}nvmlViolationTime_t; + +#define NVML_MAX_THERMAL_SENSORS_PER_GPU 3 + +/** + * Represents the thermal sensor targets + */ +typedef enum +{ + NVML_THERMAL_TARGET_NONE = 0, + NVML_THERMAL_TARGET_GPU = 1, //!< GPU core temperature requires NvPhysicalGpuHandle + NVML_THERMAL_TARGET_MEMORY = 2, //!< GPU memory temperature requires NvPhysicalGpuHandle + NVML_THERMAL_TARGET_POWER_SUPPLY = 4, //!< GPU power supply temperature requires NvPhysicalGpuHandle + NVML_THERMAL_TARGET_BOARD = 8, //!< GPU board ambient temperature requires NvPhysicalGpuHandle + NVML_THERMAL_TARGET_VCD_BOARD = 9, //!< Visual Computing Device Board temperature requires NvVisualComputingDeviceHandle + NVML_THERMAL_TARGET_VCD_INLET = 10, //!< Visual Computing Device Inlet temperature requires NvVisualComputingDeviceHandle + NVML_THERMAL_TARGET_VCD_OUTLET = 11, //!< Visual Computing Device Outlet temperature requires NvVisualComputingDeviceHandle + + NVML_THERMAL_TARGET_ALL = 15, + NVML_THERMAL_TARGET_UNKNOWN = -1, +} nvmlThermalTarget_t; + +/** + * Represents the thermal sensor controllers + */ +typedef enum +{ + NVML_THERMAL_CONTROLLER_NONE = 0, + NVML_THERMAL_CONTROLLER_GPU_INTERNAL, + NVML_THERMAL_CONTROLLER_ADM1032, + NVML_THERMAL_CONTROLLER_ADT7461, + NVML_THERMAL_CONTROLLER_MAX6649, + NVML_THERMAL_CONTROLLER_MAX1617, + NVML_THERMAL_CONTROLLER_LM99, + NVML_THERMAL_CONTROLLER_LM89, + NVML_THERMAL_CONTROLLER_LM64, + NVML_THERMAL_CONTROLLER_G781, + NVML_THERMAL_CONTROLLER_ADT7473, + NVML_THERMAL_CONTROLLER_SBMAX6649, + NVML_THERMAL_CONTROLLER_VBIOSEVT, + NVML_THERMAL_CONTROLLER_OS, + NVML_THERMAL_CONTROLLER_NVSYSCON_CANOAS, + NVML_THERMAL_CONTROLLER_NVSYSCON_E551, + NVML_THERMAL_CONTROLLER_MAX6649R, + NVML_THERMAL_CONTROLLER_ADT7473S, + NVML_THERMAL_CONTROLLER_UNKNOWN = -1, +} nvmlThermalController_t; + +/** + * Struct to hold the thermal sensor settings + */ +typedef struct +{ + unsigned int count; + struct + { + nvmlThermalController_t controller; + int defaultMinTemp; + int defaultMaxTemp; + int currentTemp; + nvmlThermalTarget_t target; + } sensor[NVML_MAX_THERMAL_SENSORS_PER_GPU]; + +} nvmlGpuThermalSettings_t; + +/** + * Cooler control type + */ +typedef enum nvmlCoolerControl_enum +{ + NVML_THERMAL_COOLER_SIGNAL_NONE = 0, //!< This cooler has no control signal. + NVML_THERMAL_COOLER_SIGNAL_TOGGLE = 1, //!< This cooler can only be toggled either ON or OFF (eg a switch). + NVML_THERMAL_COOLER_SIGNAL_VARIABLE = 2, //!< This cooler's level can be adjusted from some minimum to some maximum (eg a knob). + + // Keep this last + NVML_THERMAL_COOLER_SIGNAL_COUNT +} nvmlCoolerControl_t; + +/** + * Cooler's target + */ +typedef enum nvmlCoolerTarget_enum +{ + NVML_THERMAL_COOLER_TARGET_NONE = 1 << 0, //!< This cooler cools nothing. + NVML_THERMAL_COOLER_TARGET_GPU = 1 << 1, //!< This cooler can cool the GPU. + NVML_THERMAL_COOLER_TARGET_MEMORY = 1 << 2, //!< This cooler can cool the memory. + NVML_THERMAL_COOLER_TARGET_POWER_SUPPLY = 1 << 3, //!< This cooler can cool the power supply. + NVML_THERMAL_COOLER_TARGET_GPU_RELATED = (NVML_THERMAL_COOLER_TARGET_GPU | NVML_THERMAL_COOLER_TARGET_MEMORY | NVML_THERMAL_COOLER_TARGET_POWER_SUPPLY) //!< This cooler cools all of the components related to its target gpu. GPU_RELATED = GPU | MEMORY | POWER_SUPPLY +} nvmlCoolerTarget_t; + +typedef struct +{ + unsigned int version; //!< the API version number + unsigned int index; //!< the cooler index + nvmlCoolerControl_t signalType; //!< OUT: the cooler's control signal characteristics + nvmlCoolerTarget_t target; //!< OUT: the target that cooler cools +} nvmlCoolerInfo_v1_t; +typedef nvmlCoolerInfo_v1_t nvmlCoolerInfo_t; + +#define nvmlCoolerInfo_v1 NVML_STRUCT_VERSION(CoolerInfo, 1) + +/** + * UUID length in ASCII format + */ +#define NVML_DEVICE_UUID_ASCII_LEN 41 + +/** + * UUID length in binary format + */ +#define NVML_DEVICE_UUID_BINARY_LEN 16 + +/** + * Enum to represent different UUID types + */ +typedef enum +{ + NVML_UUID_TYPE_NONE = 0, //!< Undefined type + NVML_UUID_TYPE_ASCII = 1, //!< ASCII format type + NVML_UUID_TYPE_BINARY = 2, //!< Binary format type +} nvmlUUIDType_t; + +/** + * Union to represent different UUID values + */ +typedef union +{ + char str[NVML_DEVICE_UUID_ASCII_LEN]; //!< ASCII format value + unsigned char bytes[NVML_DEVICE_UUID_BINARY_LEN]; //!< Binary format value +} nvmlUUIDValue_t; + +/** + * Struct to represent NVML UUID information + */ +typedef struct +{ + unsigned int version; //!< API version number + unsigned int type; //!< One of \p nvmlUUIDType_t + nvmlUUIDValue_t value; //!< One of \p nvmlUUIDValue_t, to be set based on the UUID format +} nvmlUUID_v1_t; +typedef nvmlUUID_v1_t nvmlUUID_t; + +#define nvmlUUID_v1 NVML_STRUCT_VERSION(UUID, 1) + +/** + * Struct to represent the NVML PDI information + */ +typedef struct +{ + unsigned int version; //!< API version number + unsigned long long value; //!< 64-bit PDI value +} nvmlPdi_v1_t; +typedef nvmlPdi_v1_t nvmlPdi_t; + +#define nvmlPdi_v1 NVML_STRUCT_VERSION(Pdi, 1) + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlDeviceEnumvs Device Enums + * @{ + */ +/***************************************************************************************************/ + +/** + * Generic enable/disable enum. + */ +typedef enum nvmlEnableState_enum +{ + NVML_FEATURE_DISABLED = 0, //!< Feature disabled + NVML_FEATURE_ENABLED = 1 //!< Feature enabled +} nvmlEnableState_t; + +//! Generic flag used to specify the default behavior of some functions. See description of particular functions for details. +#define nvmlFlagDefault 0x00 +//! Generic flag used to force some behavior. See description of particular functions for details. +#define nvmlFlagForce 0x01 + +/** + * DRAM Encryption Info + */ +typedef struct +{ + unsigned int version; //!< IN - the API version number + nvmlEnableState_t encryptionState; //!< IN/OUT - DRAM Encryption state +} nvmlDramEncryptionInfo_v1_t; +typedef nvmlDramEncryptionInfo_v1_t nvmlDramEncryptionInfo_t; + +#define nvmlDramEncryptionInfo_v1 NVML_STRUCT_VERSION(DramEncryptionInfo, 1) + +/** + * * The Brand of the GPU + * */ +typedef enum nvmlBrandType_enum +{ + NVML_BRAND_UNKNOWN = 0, + NVML_BRAND_QUADRO = 1, + NVML_BRAND_TESLA = 2, + NVML_BRAND_NVS = 3, + NVML_BRAND_GRID = 4, // Deprecated from API reporting. Keeping definition for backward compatibility. + NVML_BRAND_GEFORCE = 5, + NVML_BRAND_TITAN = 6, + NVML_BRAND_NVIDIA_VAPPS = 7, // NVIDIA Virtual Applications + NVML_BRAND_NVIDIA_VPC = 8, // NVIDIA Virtual PC + NVML_BRAND_NVIDIA_VCS = 9, // NVIDIA Virtual Compute Server + NVML_BRAND_NVIDIA_VWS = 10, // NVIDIA RTX Virtual Workstation + NVML_BRAND_NVIDIA_CLOUD_GAMING = 11, // NVIDIA Cloud Gaming + NVML_BRAND_NVIDIA_VGAMING = NVML_BRAND_NVIDIA_CLOUD_GAMING, // Deprecated from API reporting. Keeping definition for backward compatibility. + NVML_BRAND_QUADRO_RTX = 12, + NVML_BRAND_NVIDIA_RTX = 13, + NVML_BRAND_NVIDIA = 14, + NVML_BRAND_GEFORCE_RTX = 15, // Unused + NVML_BRAND_TITAN_RTX = 16, // Unused + // Keep this last + NVML_BRAND_COUNT = 18, +} nvmlBrandType_t; + +/** + * Temperature thresholds. + */ +typedef enum nvmlTemperatureThresholds_enum +{ + NVML_TEMPERATURE_THRESHOLD_SHUTDOWN = 0, // Temperature at which the GPU will + // shut down for HW protection + NVML_TEMPERATURE_THRESHOLD_SLOWDOWN = 1, // Temperature at which the GPU will + // begin HW slowdown + NVML_TEMPERATURE_THRESHOLD_MEM_MAX = 2, // Memory Temperature at which the GPU will + // begin SW slowdown + NVML_TEMPERATURE_THRESHOLD_GPU_MAX = 3, // GPU Temperature at which the GPU + // can be throttled below base clock + NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MIN = 4, // Minimum GPU Temperature that can be + // set as acoustic threshold + NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_CURR = 5, // Current temperature that is set as + // acoustic threshold. + NVML_TEMPERATURE_THRESHOLD_ACOUSTIC_MAX = 6, // Maximum GPU temperature that can be + // set as acoustic threshold. + NVML_TEMPERATURE_THRESHOLD_GPS_CURR = 7, // Current temperature that is set as + // gps threshold. + // Keep this last + NVML_TEMPERATURE_THRESHOLD_COUNT +} nvmlTemperatureThresholds_t; + +/** + * Temperature sensors. + */ +typedef enum nvmlTemperatureSensors_enum +{ + NVML_TEMPERATURE_GPU = 0, //!< Temperature sensor for the GPU die + + // Keep this last + NVML_TEMPERATURE_COUNT +} nvmlTemperatureSensors_t; + +/** + * Margin temperature values + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + int marginTemperature; //!< The margin temperature value +} nvmlMarginTemperature_v1_t; + +typedef nvmlMarginTemperature_v1_t nvmlMarginTemperature_t; + +#define nvmlMarginTemperature_v1 NVML_STRUCT_VERSION(MarginTemperature, 1) + +/** + * Compute mode. + * + * NVML_COMPUTEMODE_EXCLUSIVE_PROCESS was added in CUDA 4.0. + * Earlier CUDA versions supported a single exclusive mode, + * which is equivalent to NVML_COMPUTEMODE_EXCLUSIVE_THREAD in CUDA 4.0 and beyond. + */ +typedef enum nvmlComputeMode_enum +{ + NVML_COMPUTEMODE_DEFAULT = 0, //!< Default compute mode -- multiple contexts per device + NVML_COMPUTEMODE_EXCLUSIVE_THREAD = 1, //!< Support Removed + NVML_COMPUTEMODE_PROHIBITED = 2, //!< Compute-prohibited mode -- no contexts per device + NVML_COMPUTEMODE_EXCLUSIVE_PROCESS = 3, //!< Compute-exclusive-process mode -- only one context per device, usable from multiple threads at a time + + // Keep this last + NVML_COMPUTEMODE_COUNT +} nvmlComputeMode_t; + +/** + * Max Clock Monitors available + */ +#define MAX_CLK_DOMAINS 32 + +/** + * Clock Monitor error types + */ +typedef struct nvmlClkMonFaultInfo_struct { + /** + * The Domain which faulted + */ + unsigned int clkApiDomain; + + /** + * Faults Information + */ + unsigned int clkDomainFaultMask; +} nvmlClkMonFaultInfo_t; + +/** + * Clock Monitor Status + */ +typedef struct nvmlClkMonStatus_status { + /** + * Fault status Indicator + */ + unsigned int bGlobalStatus; + + /** + * Total faulted domain numbers + */ + unsigned int clkMonListSize; + + /** + * The fault Information structure + */ + nvmlClkMonFaultInfo_t clkMonList[MAX_CLK_DOMAINS]; +} nvmlClkMonStatus_t; + +/** + * ECC bit types. + * + * @deprecated See \ref nvmlMemoryErrorType_t for a more flexible type + */ +#define nvmlEccBitType_t nvmlMemoryErrorType_t + +/** + * Single bit ECC errors + * + * @deprecated Mapped to \ref NVML_MEMORY_ERROR_TYPE_CORRECTED + */ +#define NVML_SINGLE_BIT_ECC NVML_MEMORY_ERROR_TYPE_CORRECTED + +/** + * Double bit ECC errors + * + * @deprecated Mapped to \ref NVML_MEMORY_ERROR_TYPE_UNCORRECTED + */ +#define NVML_DOUBLE_BIT_ECC NVML_MEMORY_ERROR_TYPE_UNCORRECTED + +/** + * Memory error types + */ +typedef enum nvmlMemoryErrorType_enum +{ + /** + * A memory error that was corrected + * + * For ECC errors, these are single bit errors + * For Texture memory, these are errors fixed by resend + */ + NVML_MEMORY_ERROR_TYPE_CORRECTED = 0, + /** + * A memory error that was not corrected + * + * For ECC errors, these are double bit errors + * For Texture memory, these are errors where the resend fails + */ + NVML_MEMORY_ERROR_TYPE_UNCORRECTED = 1, + + // Keep this last + NVML_MEMORY_ERROR_TYPE_COUNT //!< Count of memory error types + +} nvmlMemoryErrorType_t; + +/** + * Represents Nvlink Version + */ +typedef enum nvmlNvlinkVersion_enum +{ + NVML_NVLINK_VERSION_INVALID = 0, + NVML_NVLINK_VERSION_1_0 = 1, + NVML_NVLINK_VERSION_2_0 = 2, + NVML_NVLINK_VERSION_2_2 = 3, + NVML_NVLINK_VERSION_3_0 = 4, + NVML_NVLINK_VERSION_3_1 = 5, + NVML_NVLINK_VERSION_4_0 = 6, + NVML_NVLINK_VERSION_5_0 = 7, +}nvmlNvlinkVersion_t; + +/** + * ECC counter types. + * + * Note: Volatile counts are reset each time the driver loads. On Windows this is once per boot. On Linux this can be more frequent. + * On Linux the driver unloads when no active clients exist. If persistence mode is enabled or there is always a driver + * client active (e.g. X11), then Linux also sees per-boot behavior. If not, volatile counts are reset each time a compute app + * is run. + */ +typedef enum nvmlEccCounterType_enum +{ + NVML_VOLATILE_ECC = 0, //!< Volatile counts are reset each time the driver loads. + NVML_AGGREGATE_ECC = 1, //!< Aggregate counts persist across reboots (i.e. for the lifetime of the device) + + // Keep this last + NVML_ECC_COUNTER_TYPE_COUNT //!< Count of memory counter types +} nvmlEccCounterType_t; + +/** + * Clock types. + * + * All speeds are in Mhz. + */ +typedef enum nvmlClockType_enum +{ + NVML_CLOCK_GRAPHICS = 0, //!< Graphics clock domain + NVML_CLOCK_SM = 1, //!< SM clock domain + NVML_CLOCK_MEM = 2, //!< Memory clock domain + NVML_CLOCK_VIDEO = 3, //!< Video encoder/decoder clock domain + + // Keep this last + NVML_CLOCK_COUNT //!< Count of clock types +} nvmlClockType_t; + +/** + * Clock Ids. These are used in combination with nvmlClockType_t + * to specify a single clock value. + */ +typedef enum nvmlClockId_enum +{ + NVML_CLOCK_ID_CURRENT = 0, //!< Current actual clock value + NVML_CLOCK_ID_APP_CLOCK_TARGET = 1, //!< Target application clock. + //!< Deprecated, do not use. + NVML_CLOCK_ID_APP_CLOCK_DEFAULT = 2, //!< Default application clock target + //!< Deprecated, do not use. + NVML_CLOCK_ID_CUSTOMER_BOOST_MAX = 3, //!< OEM-defined maximum clock rate + + //Keep this last + NVML_CLOCK_ID_COUNT //!< Count of Clock Ids. +} nvmlClockId_t; + +/** + * Driver models. + * + * Windows only. + */ + +typedef enum nvmlDriverModel_enum +{ + NVML_DRIVER_WDDM = 0, //!< WDDM driver model -- GPU treated as a display device + NVML_DRIVER_WDM = 1, //!< WDM (TCC) model (deprecated) -- GPU treated as a generic compute device + NVML_DRIVER_MCDM = 2 //!< MCDM driver model -- GPU treated as a Microsoft compute device +} nvmlDriverModel_t; + +#define NVML_MAX_GPU_PERF_PSTATES 16 + +/** + * Allowed PStates. + */ +typedef enum nvmlPStates_enum +{ + NVML_PSTATE_0 = 0, //!< Performance state 0 -- Maximum Performance + NVML_PSTATE_1 = 1, //!< Performance state 1 + NVML_PSTATE_2 = 2, //!< Performance state 2 + NVML_PSTATE_3 = 3, //!< Performance state 3 + NVML_PSTATE_4 = 4, //!< Performance state 4 + NVML_PSTATE_5 = 5, //!< Performance state 5 + NVML_PSTATE_6 = 6, //!< Performance state 6 + NVML_PSTATE_7 = 7, //!< Performance state 7 + NVML_PSTATE_8 = 8, //!< Performance state 8 + NVML_PSTATE_9 = 9, //!< Performance state 9 + NVML_PSTATE_10 = 10, //!< Performance state 10 + NVML_PSTATE_11 = 11, //!< Performance state 11 + NVML_PSTATE_12 = 12, //!< Performance state 12 + NVML_PSTATE_13 = 13, //!< Performance state 13 + NVML_PSTATE_14 = 14, //!< Performance state 14 + NVML_PSTATE_15 = 15, //!< Performance state 15 -- Minimum Performance + NVML_PSTATE_UNKNOWN = 32 //!< Unknown performance state +} nvmlPstates_t; + +/** + * Clock offset info. + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + nvmlClockType_t type; + nvmlPstates_t pstate; + int clockOffsetMHz; + int minClockOffsetMHz; + int maxClockOffsetMHz; +} nvmlClockOffset_v1_t; + +typedef nvmlClockOffset_v1_t nvmlClockOffset_t; + +#define nvmlClockOffset_v1 NVML_STRUCT_VERSION(ClockOffset, 1) + +/** + * Fan speed info. + */ +typedef struct +{ + unsigned int version; //!< the API version number + unsigned int fan; //!< the fan index + unsigned int speed; //!< OUT: the fan speed in RPM +} nvmlFanSpeedInfo_v1_t; +typedef nvmlFanSpeedInfo_v1_t nvmlFanSpeedInfo_t; + +#define nvmlFanSpeedInfo_v1 NVML_STRUCT_VERSION(FanSpeedInfo, 1) + +#define NVML_PERF_MODES_BUFFER_SIZE 2048 + +/** + * Device performance modes string + */ +typedef struct +{ + unsigned int version; //!< the API version number + char str[NVML_PERF_MODES_BUFFER_SIZE]; //!< OUT: the performance modes string. +} nvmlDevicePerfModes_v1_t; +typedef nvmlDevicePerfModes_v1_t nvmlDevicePerfModes_t; + +#define nvmlDevicePerfModes_v1 NVML_STRUCT_VERSION(DevicePerfModes, 1) + +/** + * Device current clocks string + */ +typedef struct +{ + unsigned int version; //!< the API version number + char str[NVML_PERF_MODES_BUFFER_SIZE]; //!< OUT: the current clock frequency string. +} nvmlDeviceCurrentClockFreqs_v1_t; +typedef nvmlDeviceCurrentClockFreqs_v1_t nvmlDeviceCurrentClockFreqs_t; + +#define nvmlDeviceCurrentClockFreqs_v1 NVML_STRUCT_VERSION(DeviceCurrentClockFreqs, 1) + +/** + * Device powerMizer modes + */ +#define NVML_POWER_MIZER_MODE_ADAPTIVE 0 //!< adjust GPU clocks based on GPU utilization +#define NVML_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE 1 //!< raise GPU clocks to favor maximum performance, + //!< to the extent that thermal and other constraints allow +#define NVML_POWER_MIZER_MODE_AUTO 2 //!< PowerMizer mode is driver controlled. +#define NVML_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE 3 //!< lock to GPU base clocks + +typedef struct +{ + unsigned int currentMode; //!< OUT: the current powermizer mode + unsigned int mode; //!< IN: the powermizer mode to set + unsigned int supportedPowerMizerModes; //!< OUT: Bitmask of supported powermizer modes +} nvmlDevicePowerMizerModes_v1_t; + +/** + * GPU Operation Mode + * + * GOM allows to reduce power usage and optimize GPU throughput by disabling GPU features. + * + * Each GOM is designed to meet specific user needs. + */ +typedef enum nvmlGom_enum +{ + NVML_GOM_ALL_ON = 0, //!< Everything is enabled and running at full speed + + NVML_GOM_COMPUTE = 1, //!< Designed for running only compute tasks. Graphics operations + //!< are not allowed + + NVML_GOM_LOW_DP = 2 //!< Designed for running graphics applications that don't require + //!< high bandwidth double precision +} nvmlGpuOperationMode_t; + +/** + * Available infoROM objects. + */ +typedef enum nvmlInforomObject_enum +{ + NVML_INFOROM_OEM = 0, //!< An object defined by OEM + NVML_INFOROM_ECC = 1, //!< The ECC object determining the level of ECC support + NVML_INFOROM_POWER = 2, //!< The power management object + NVML_INFOROM_DEN = 3, //!< DRAM Encryption object + // Keep this last + NVML_INFOROM_COUNT //!< This counts the number of infoROM objects the driver knows about +} nvmlInforomObject_t; + +/** + * Return values for NVML API calls. + */ +typedef enum nvmlReturn_enum +{ + // cppcheck-suppress * + NVML_SUCCESS = 0, //!< The operation was successful + NVML_ERROR_UNINITIALIZED = 1, //!< NVML was not first initialized with nvmlInit() + NVML_ERROR_INVALID_ARGUMENT = 2, //!< A supplied argument is invalid + NVML_ERROR_NOT_SUPPORTED = 3, //!< The requested operation is not available on target device + NVML_ERROR_NO_PERMISSION = 4, //!< The current user does not have permission for operation + NVML_ERROR_ALREADY_INITIALIZED = 5, //!< Deprecated: Multiple initializations are now allowed through ref counting + NVML_ERROR_NOT_FOUND = 6, //!< A query to find an object was unsuccessful + NVML_ERROR_INSUFFICIENT_SIZE = 7, //!< An input argument is not large enough + NVML_ERROR_INSUFFICIENT_POWER = 8, //!< A device's external power cables are not properly attached + NVML_ERROR_DRIVER_NOT_LOADED = 9, //!< NVIDIA driver is not loaded + NVML_ERROR_TIMEOUT = 10, //!< User provided timeout passed + NVML_ERROR_IRQ_ISSUE = 11, //!< NVIDIA Kernel detected an interrupt issue with a GPU + NVML_ERROR_LIBRARY_NOT_FOUND = 12, //!< NVML Shared Library couldn't be found or loaded + NVML_ERROR_FUNCTION_NOT_FOUND = 13, //!< Local version of NVML doesn't implement this function + NVML_ERROR_CORRUPTED_INFOROM = 14, //!< infoROM is corrupted + NVML_ERROR_GPU_IS_LOST = 15, //!< The GPU has fallen off the bus or has otherwise become inaccessible + NVML_ERROR_RESET_REQUIRED = 16, //!< The GPU requires a reset before it can be used again + NVML_ERROR_OPERATING_SYSTEM = 17, //!< The GPU control device has been blocked by the operating system/cgroups + NVML_ERROR_LIB_RM_VERSION_MISMATCH = 18, //!< RM detects a driver/library version mismatch + NVML_ERROR_IN_USE = 19, //!< An operation cannot be performed because the GPU is currently in use + NVML_ERROR_MEMORY = 20, //!< Insufficient memory + NVML_ERROR_NO_DATA = 21, //!< No data + NVML_ERROR_VGPU_ECC_NOT_SUPPORTED = 22, //!< The requested vgpu operation is not available on target device, becasue ECC is enabled + NVML_ERROR_INSUFFICIENT_RESOURCES = 23, //!< Ran out of critical resources, other than memory + NVML_ERROR_FREQ_NOT_SUPPORTED = 24, //!< Ran out of critical resources, other than memory + NVML_ERROR_ARGUMENT_VERSION_MISMATCH = 25, //!< The provided version is invalid/unsupported + NVML_ERROR_DEPRECATED = 26, //!< The requested functionality has been deprecated + NVML_ERROR_NOT_READY = 27, //!< The system is not ready for the request + NVML_ERROR_GPU_NOT_FOUND = 28, //!< No GPUs were found + NVML_ERROR_INVALID_STATE = 29, //!< Resource not in correct state to perform requested operation + NVML_ERROR_RESET_TYPE_NOT_SUPPORTED = 30, //!< Reset not supported for given device/parameters + NVML_ERROR_UNKNOWN = 999 //!< An internal driver error occurred +} nvmlReturn_t; + +/** + * See \ref nvmlDeviceGetMemoryErrorCounter + */ +typedef enum nvmlMemoryLocation_enum +{ + NVML_MEMORY_LOCATION_L1_CACHE = 0, //!< GPU L1 Cache + NVML_MEMORY_LOCATION_L2_CACHE = 1, //!< GPU L2 Cache + NVML_MEMORY_LOCATION_DRAM = 2, //!< Turing+ DRAM + NVML_MEMORY_LOCATION_DEVICE_MEMORY = 2, //!< GPU Device Memory + NVML_MEMORY_LOCATION_REGISTER_FILE = 3, //!< GPU Register File + NVML_MEMORY_LOCATION_TEXTURE_MEMORY = 4, //!< GPU Texture Memory + NVML_MEMORY_LOCATION_TEXTURE_SHM = 5, //!< Shared memory + NVML_MEMORY_LOCATION_CBU = 6, //!< CBU + NVML_MEMORY_LOCATION_SRAM = 7, //!< Turing+ SRAM + // Keep this last + NVML_MEMORY_LOCATION_COUNT //!< This counts the number of memory locations the driver knows about +} nvmlMemoryLocation_t; + +/** + * Causes for page retirement + */ +typedef enum nvmlPageRetirementCause_enum +{ + NVML_PAGE_RETIREMENT_CAUSE_MULTIPLE_SINGLE_BIT_ECC_ERRORS = 0, //!< Page was retired due to multiple single bit ECC error + NVML_PAGE_RETIREMENT_CAUSE_DOUBLE_BIT_ECC_ERROR = 1, //!< Page was retired due to double bit ECC error + + // Keep this last + NVML_PAGE_RETIREMENT_CAUSE_COUNT +} nvmlPageRetirementCause_t; + +/** + * API types that allow changes to default permission restrictions + */ +typedef enum nvmlRestrictedAPI_enum +{ + NVML_RESTRICTED_API_SET_APPLICATION_CLOCKS = 0, //!< APIs that change application clocks, see nvmlDeviceSetApplicationsClocks + //!< and see nvmlDeviceResetApplicationsClocks. + //!< Deprecated, keeping definition for backward compatibility. + NVML_RESTRICTED_API_SET_AUTO_BOOSTED_CLOCKS = 1, //!< APIs that enable/disable Auto Boosted clocks + //!< see nvmlDeviceSetAutoBoostedClocksEnabled + // Keep this last + NVML_RESTRICTED_API_COUNT +} nvmlRestrictedAPI_t; + +/** + * Structure to store utilization value and process Id + */ +typedef struct nvmlProcessUtilizationSample_st +{ + unsigned int pid; //!< PID of process + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + unsigned int smUtil; //!< SM (3D/Compute) Util Value + unsigned int memUtil; //!< Frame Buffer Memory Util Value + unsigned int encUtil; //!< Encoder Util Value + unsigned int decUtil; //!< Decoder Util Value +} nvmlProcessUtilizationSample_t; + +/** + * Structure to store utilization value and process Id -- version 1 + */ +typedef struct +{ + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + unsigned int pid; //!< PID of process + unsigned int smUtil; //!< SM (3D/Compute) Util Value + unsigned int memUtil; //!< Frame Buffer Memory Util Value + unsigned int encUtil; //!< Encoder Util Value + unsigned int decUtil; //!< Decoder Util Value + unsigned int jpgUtil; //!< Jpeg Util Value + unsigned int ofaUtil; //!< Ofa Util Value +} nvmlProcessUtilizationInfo_v1_t; + +/** + * Structure to store utilization and process ID for each running process -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int processSamplesCount; //!< Caller-supplied array size, and returns number of processes running + unsigned long long lastSeenTimeStamp; //!< Return only samples with timestamp greater than lastSeenTimeStamp + nvmlProcessUtilizationInfo_v1_t *procUtilArray; //!< The array (allocated by caller) of the utilization of GPU SM, framebuffer, video encoder, video decoder, JPEG, and OFA +} nvmlProcessesUtilizationInfo_v1_t; +typedef nvmlProcessesUtilizationInfo_v1_t nvmlProcessesUtilizationInfo_t; +#define nvmlProcessesUtilizationInfo_v1 NVML_STRUCT_VERSION(ProcessesUtilizationInfo, 1) + +/** + * Structure to store SRAM uncorrectable error counters + */ +typedef struct +{ + unsigned int version; //!< the API version number + unsigned long long aggregateUncParity; //!< aggregate uncorrectable parity error count + unsigned long long aggregateUncSecDed; //!< aggregate uncorrectable SEC-DED error count + unsigned long long aggregateCor; //!< aggregate correctable error count + unsigned long long volatileUncParity; //!< volatile uncorrectable parity error count + unsigned long long volatileUncSecDed; //!< volatile uncorrectable SEC-DED error count + unsigned long long volatileCor; //!< volatile correctable error count + unsigned long long aggregateUncBucketL2; //!< aggregate uncorrectable error count for L2 cache bucket + unsigned long long aggregateUncBucketSm; //!< aggregate uncorrectable error count for SM bucket + unsigned long long aggregateUncBucketPcie; //!< aggregate uncorrectable error count for PCIE bucket + unsigned long long aggregateUncBucketMcu; //!< aggregate uncorrectable error count for Microcontroller bucket + unsigned long long aggregateUncBucketOther; //!< aggregate uncorrectable error count for Other bucket + unsigned int bThresholdExceeded; //!< if the error threshold of field diag is exceeded +} nvmlEccSramErrorStatus_v1_t; + +typedef nvmlEccSramErrorStatus_v1_t nvmlEccSramErrorStatus_t; +#define nvmlEccSramErrorStatus_v1 NVML_STRUCT_VERSION(EccSramErrorStatus, 1) + +/** + * Structure to store platform information + * + * @deprecated The nvmlPlatformInfo_v1_t will be deprecated in the subsequent releases. + * Use nvmlPlatformInfo_v2_t + */ +typedef struct +{ + unsigned int version; //!< the API version number + unsigned char ibGuid[16]; //!< Infiniband GUID reported by platform (for Blackwell, ibGuid is 8 bytes so indices 8-15 are zero) + unsigned char rackGuid[16]; //!< GUID of the rack containing this GPU (for Blackwell rackGuid is 13 bytes so indices 13-15 are zero) + unsigned char chassisPhysicalSlotNumber; //!< The slot number in the rack containing this GPU (includes switches) + unsigned char computeSlotIndex; //!< The index within the compute slots in the rack containing this GPU (does not include switches) + unsigned char nodeIndex; //!< Index of the node within the slot containing this GPU + unsigned char peerType; //!< Platform indicated NVLink-peer type (e.g. switch present or not) + unsigned char moduleId; //!< ID of this GPU within the node +} nvmlPlatformInfo_v1_t; +#define nvmlPlatformInfo_v1 NVML_STRUCT_VERSION(PlatformInfo, 1) + +/** + * Structure to store platform information (v2) + */ +typedef struct +{ + unsigned int version; //!< the API version number + unsigned char ibGuid[16]; //!< Infiniband GUID reported by platform (for Blackwell, ibGuid is 8 bytes so indices 8-15 are zero) + unsigned char chassisSerialNumber[16]; //!< Serial number of the chassis containing this GPU (for Blackwell it is 13 bytes so indices 13-15 are zero) + unsigned char slotNumber; //!< The slot number in the chassis containing this GPU (includes switches) + unsigned char trayIndex; //!< The tray index within the compute slots in the chassis containing this GPU (does not include switches) + unsigned char hostId; //!< Index of the node within the slot containing this GPU + unsigned char peerType; //!< Platform indicated NVLink-peer type (e.g. switch present or not) + unsigned char moduleId; //!< ID of this GPU within the node +} nvmlPlatformInfo_v2_t; + +typedef nvmlPlatformInfo_v2_t nvmlPlatformInfo_t; +#define nvmlPlatformInfo_v2 NVML_STRUCT_VERSION(PlatformInfo, 2) + +typedef struct +{ + unsigned int unit; //!< the SRAM unit index + unsigned int location; //!< the error location within the SRAM unit + unsigned int sublocation; //!< the error sublocation within the SRAM unit + unsigned int extlocation; //!< the error extlocation within the SRAM unit + unsigned int address; //!< the error address within the SRAM unit + unsigned int isParity; //!< if the SRAM error is parity or not + unsigned int count; //!< the error count at the same SRAM address +} nvmlEccSramUniqueUncorrectedErrorEntry_v1_t; + +typedef struct +{ + unsigned int version; //!< the API version number + unsigned int entryCount; //!< the number of error count entries + nvmlEccSramUniqueUncorrectedErrorEntry_v1_t *entries; //!< pointer to caller-supplied buffer to return the SRAM unique uncorrected ECC error count entries +} nvmlEccSramUniqueUncorrectedErrorCounts_v1_t; + +typedef nvmlEccSramUniqueUncorrectedErrorCounts_v1_t nvmlEccSramUniqueUncorrectedErrorCounts_t; +#define nvmlEccSramUniqueUncorrectedErrorCounts_v1 NVML_STRUCT_VERSION(EccSramUniqueUncorrectedErrorCounts, 1) + +/** + * GSP firmware + */ +#define NVML_GSP_FIRMWARE_VERSION_BUF_SIZE 0x40 + +/** + * Simplified chip architecture + */ +#define NVML_DEVICE_ARCH_KEPLER 2 // Devices based on the NVIDIA Kepler architecture +#define NVML_DEVICE_ARCH_MAXWELL 3 // Devices based on the NVIDIA Maxwell architecture +#define NVML_DEVICE_ARCH_PASCAL 4 // Devices based on the NVIDIA Pascal architecture +#define NVML_DEVICE_ARCH_VOLTA 5 // Devices based on the NVIDIA Volta architecture +#define NVML_DEVICE_ARCH_TURING 6 // Devices based on the NVIDIA Turing architecture +#define NVML_DEVICE_ARCH_AMPERE 7 // Devices based on the NVIDIA Ampere architecture +#define NVML_DEVICE_ARCH_ADA 8 // Devices based on the NVIDIA Ada architecture +#define NVML_DEVICE_ARCH_HOPPER 9 // Devices based on the NVIDIA Hopper architecture + +#define NVML_DEVICE_ARCH_BLACKWELL 10 // Devices based on the NVIDIA Blackwell architecture + +#define NVML_DEVICE_ARCH_UNKNOWN 0xffffffff // Anything else, presumably something newer + +typedef unsigned int nvmlDeviceArchitecture_t; + +/** + * PCI bus types + */ +#define NVML_BUS_TYPE_UNKNOWN 0 +#define NVML_BUS_TYPE_PCI 1 +#define NVML_BUS_TYPE_PCIE 2 +#define NVML_BUS_TYPE_FPCI 3 +#define NVML_BUS_TYPE_AGP 4 + +typedef unsigned int nvmlBusType_t; + +/** + * Device Power Modes + */ + +/** + * Device Fan control policy + */ +#define NVML_FAN_POLICY_TEMPERATURE_CONTINOUS_SW 0 +#define NVML_FAN_POLICY_MANUAL 1 + +typedef unsigned int nvmlFanControlPolicy_t; + +/** + * Device Power Source + */ +#define NVML_POWER_SOURCE_AC 0x00000000 +#define NVML_POWER_SOURCE_BATTERY 0x00000001 +#define NVML_POWER_SOURCE_UNDERSIZED 0x00000002 + +typedef unsigned int nvmlPowerSource_t; + +/** + * Device PCIE link Max Speed + */ +#define NVML_PCIE_LINK_MAX_SPEED_INVALID 0x00000000 +#define NVML_PCIE_LINK_MAX_SPEED_2500MBPS 0x00000001 +#define NVML_PCIE_LINK_MAX_SPEED_5000MBPS 0x00000002 +#define NVML_PCIE_LINK_MAX_SPEED_8000MBPS 0x00000003 +#define NVML_PCIE_LINK_MAX_SPEED_16000MBPS 0x00000004 +#define NVML_PCIE_LINK_MAX_SPEED_32000MBPS 0x00000005 +#define NVML_PCIE_LINK_MAX_SPEED_64000MBPS 0x00000006 + +/** + * Adaptive clocking status + */ +#define NVML_ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED 0x00000000 +#define NVML_ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED 0x00000001 + +#define NVML_MAX_GPU_UTILIZATIONS 8 + +/** + * Represents the GPU utilization domains + */ +typedef enum nvmlGpuUtilizationDomainId_t +{ + NVML_GPU_UTILIZATION_DOMAIN_GPU = 0, //!< Graphics engine domain + NVML_GPU_UTILIZATION_DOMAIN_FB = 1, //!< Frame buffer domain + NVML_GPU_UTILIZATION_DOMAIN_VID = 2, //!< Video engine domain + NVML_GPU_UTILIZATION_DOMAIN_BUS = 3, //!< Bus interface domain +} nvmlGpuUtilizationDomainId_t; + +typedef struct nvmlGpuDynamicPstatesInfo_st +{ + unsigned int flags; //!< Reserved for future use + struct + { + unsigned int bIsPresent; //!< Set if this utilization domain is present on this GPU + unsigned int percentage; //!< Percentage of time where the domain is considered busy in the last 1-second interval + unsigned int incThreshold; //!< Utilization threshold that can trigger a perf-increasing P-State change when crossed + unsigned int decThreshold; //!< Utilization threshold that can trigger a perf-decreasing P-State change when crossed + } utilization[NVML_MAX_GPU_UTILIZATIONS]; +} nvmlGpuDynamicPstatesInfo_t; + +/* + * PCIe outbound/inbound atomic operations capability + */ +#define NVML_PCIE_ATOMICS_CAP_FETCHADD32 0x01 +#define NVML_PCIE_ATOMICS_CAP_FETCHADD64 0x02 +#define NVML_PCIE_ATOMICS_CAP_SWAP32 0x04 +#define NVML_PCIE_ATOMICS_CAP_SWAP64 0x08 +#define NVML_PCIE_ATOMICS_CAP_CAS32 0x10 +#define NVML_PCIE_ATOMICS_CAP_CAS64 0x20 +#define NVML_PCIE_ATOMICS_CAP_CAS128 0x40 +#define NVML_PCIE_ATOMICS_OPS_MAX 7 + +/** + * Device Scope - This is useful to retrieve the telemetry at GPU and module (e.g. GPU + CPU) level + */ +#define NVML_POWER_SCOPE_GPU 0U //!< Targets only GPU +#define NVML_POWER_SCOPE_MODULE 1U //!< Targets the whole module +#define NVML_POWER_SCOPE_MEMORY 2U //!< Targets the GPU Memory + +typedef unsigned char nvmlPowerScopeType_t; + +/** + * Contains the power management limit + */ +typedef struct +{ + unsigned int version; //!< Structure format version (must be 1) + nvmlPowerScopeType_t powerScope; //!< [in] Device type: GPU or Total Module + unsigned int powerValueMw; //!< [out] Power value to retrieve or set in milliwatts +} nvmlPowerValue_v2_t; + +#define nvmlPowerValue_v2 NVML_STRUCT_VERSION(PowerValue, 2) + +/** @} */ + +/***************************************************************************************************/ +/** @addtogroup virtualGPU vGPU Enums, Constants, Structs + * @{ + */ +/***************************************************************************************************/ +/** @defgroup nvmlVirtualGpuEnums vGPU Enums + * @{ + */ +/***************************************************************************************************/ + +/*! + * GPU virtualization mode types. + */ +typedef enum nvmlGpuVirtualizationMode { + NVML_GPU_VIRTUALIZATION_MODE_NONE = 0, //!< Represents Bare Metal GPU + NVML_GPU_VIRTUALIZATION_MODE_PASSTHROUGH = 1, //!< Device is associated with GPU-Passthorugh + NVML_GPU_VIRTUALIZATION_MODE_VGPU = 2, //!< Device is associated with vGPU inside virtual machine. + NVML_GPU_VIRTUALIZATION_MODE_HOST_VGPU = 3, //!< Device is associated with VGX hypervisor in vGPU mode + NVML_GPU_VIRTUALIZATION_MODE_HOST_VSGA = 4 //!< Device is associated with VGX hypervisor in vSGA mode +} nvmlGpuVirtualizationMode_t; + +/** + * Host vGPU modes + */ +typedef enum nvmlHostVgpuMode_enum +{ + NVML_HOST_VGPU_MODE_NON_SRIOV = 0, //!< Non SR-IOV mode + NVML_HOST_VGPU_MODE_SRIOV = 1 //!< SR-IOV mode +} nvmlHostVgpuMode_t; + +/*! + * Types of VM identifiers + */ +typedef enum nvmlVgpuVmIdType { + NVML_VGPU_VM_ID_DOMAIN_ID = 0, //!< VM ID represents DOMAIN ID + NVML_VGPU_VM_ID_UUID = 1 //!< VM ID represents UUID +} nvmlVgpuVmIdType_t; + +/** + * vGPU GUEST info state + */ +typedef enum nvmlVgpuGuestInfoState_enum +{ + NVML_VGPU_INSTANCE_GUEST_INFO_STATE_UNINITIALIZED = 0, //!< Guest-dependent fields uninitialized + NVML_VGPU_INSTANCE_GUEST_INFO_STATE_INITIALIZED = 1 //!< Guest-dependent fields initialized +} nvmlVgpuGuestInfoState_t; + +/** + * vGPU software licensable features + */ +typedef enum { + NVML_GRID_LICENSE_FEATURE_CODE_UNKNOWN = 0, //!< Unknown + NVML_GRID_LICENSE_FEATURE_CODE_VGPU = 1, //!< Virtual GPU + NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX = 2, //!< Nvidia RTX + NVML_GRID_LICENSE_FEATURE_CODE_VWORKSTATION = NVML_GRID_LICENSE_FEATURE_CODE_NVIDIA_RTX, //!< Deprecated, do not use. + NVML_GRID_LICENSE_FEATURE_CODE_GAMING = 3, //!< Gaming + NVML_GRID_LICENSE_FEATURE_CODE_COMPUTE = 4 //!< Compute +} nvmlGridLicenseFeatureCode_t; + +/** + * Status codes for license expiry + */ +#define NVML_GRID_LICENSE_EXPIRY_NOT_AVAILABLE 0 //!< Expiry information not available +#define NVML_GRID_LICENSE_EXPIRY_INVALID 1 //!< Invalid expiry or error fetching expiry +#define NVML_GRID_LICENSE_EXPIRY_VALID 2 //!< Valid expiry +#define NVML_GRID_LICENSE_EXPIRY_NOT_APPLICABLE 3 //!< Expiry not applicable +#define NVML_GRID_LICENSE_EXPIRY_PERMANENT 4 //!< Permanent expiry + +/** + * vGPU queryable capabilities + */ +typedef enum nvmlVgpuCapability_enum +{ + NVML_VGPU_CAP_NVLINK_P2P = 0, //!< P2P over NVLink is supported + NVML_VGPU_CAP_GPUDIRECT = 1, //!< GPUDirect capability is supported + NVML_VGPU_CAP_MULTI_VGPU_EXCLUSIVE = 2, //!< vGPU profile cannot be mixed with other vGPU profiles in same VM + NVML_VGPU_CAP_EXCLUSIVE_TYPE = 3, //!< vGPU profile cannot run on a GPU alongside other profiles of different type + NVML_VGPU_CAP_EXCLUSIVE_SIZE = 4, //!< vGPU profile cannot run on a GPU alongside other profiles of different size + // Keep this last + NVML_VGPU_CAP_COUNT +} nvmlVgpuCapability_t; + +/** +* vGPU driver queryable capabilities +*/ +typedef enum nvmlVgpuDriverCapability_enum +{ + NVML_VGPU_DRIVER_CAP_HETEROGENEOUS_MULTI_VGPU = 0, //!< Supports mixing of different vGPU profiles within one guest VM + NVML_VGPU_DRIVER_CAP_WARM_UPDATE = 1, //!< Supports FSR and warm update of vGPU host driver without terminating the running guest VM + // Keep this last + NVML_VGPU_DRIVER_CAP_COUNT +} nvmlVgpuDriverCapability_t; + +/** +* Device vGPU queryable capabilities +*/ +typedef enum nvmlDeviceVgpuCapability_enum +{ + NVML_DEVICE_VGPU_CAP_FRACTIONAL_MULTI_VGPU = 0, //!< Query whether the fractional vGPU profiles on this GPU can be used in multi-vGPU configurations + NVML_DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_PROFILES = 1, //!< Query whether the GPU support concurrent execution of timesliced vGPU profiles of differing types + NVML_DEVICE_VGPU_CAP_HETEROGENEOUS_TIMESLICE_SIZES = 2, //!< Query whether the GPU support concurrent execution of timesliced vGPU profiles of differing framebuffer sizes + NVML_DEVICE_VGPU_CAP_READ_DEVICE_BUFFER_BW = 3, //!< Query the GPU's read_device_buffer expected bandwidth capacity in megabytes per second + NVML_DEVICE_VGPU_CAP_WRITE_DEVICE_BUFFER_BW = 4, //!< Query the GPU's write_device_buffer expected bandwidth capacity in megabytes per second + NVML_DEVICE_VGPU_CAP_DEVICE_STREAMING = 5, //!< Query whether the vGPU profiles on the GPU supports migration data streaming + NVML_DEVICE_VGPU_CAP_MINI_QUARTER_GPU = 6, //!< Set/Get support for mini-quarter vGPU profiles + NVML_DEVICE_VGPU_CAP_COMPUTE_MEDIA_ENGINE_GPU = 7, //!< Set/Get support for compute media engine vGPU profiles + NVML_DEVICE_VGPU_CAP_WARM_UPDATE = 8, //!< Query whether the GPU supports FSR and warm update + NVML_DEVICE_VGPU_CAP_HOMOGENEOUS_PLACEMENTS = 9, //!< Query whether the GPU supports reporting of placements of timesliced vGPU profiles with identical framebuffer sizes + NVML_DEVICE_VGPU_CAP_MIG_TIMESLICING_SUPPORTED = 10, //!< Query whether the GPU supports timesliced vGPU on MIG + NVML_DEVICE_VGPU_CAP_MIG_TIMESLICING_ENABLED = 11, //!< Set/Get MIG timesliced mode reporting, without impacting the underlying functionality + // Keep this last + NVML_DEVICE_VGPU_CAP_COUNT +} nvmlDeviceVgpuCapability_t; + +/** @} */ + +/***************************************************************************************************/ + +/** @defgroup nvmlVgpuConstants vGPU Constants + * @{ + */ +/***************************************************************************************************/ + +/** + * Buffer size guaranteed to be large enough for \ref nvmlVgpuTypeGetLicense + */ +#define NVML_GRID_LICENSE_BUFFER_SIZE 128 + +#define NVML_VGPU_NAME_BUFFER_SIZE 64 + +#define NVML_GRID_LICENSE_FEATURE_MAX_COUNT 3 + +#define INVALID_GPU_INSTANCE_PROFILE_ID 0xFFFFFFFF + +#define INVALID_GPU_INSTANCE_ID 0xFFFFFFFF + +#define NVML_INVALID_VGPU_PLACEMENT_ID 0xFFFF + +/*! + * Macros for vGPU instance's virtualization capabilities bitfield. + */ +#define NVML_VGPU_VIRTUALIZATION_CAP_MIGRATION 0:0 +#define NVML_VGPU_VIRTUALIZATION_CAP_MIGRATION_NO 0x0 +#define NVML_VGPU_VIRTUALIZATION_CAP_MIGRATION_YES 0x1 + +/*! + * Macros for pGPU's virtualization capabilities bitfield. + */ +#define NVML_VGPU_PGPU_VIRTUALIZATION_CAP_MIGRATION 0:0 +#define NVML_VGPU_PGPU_VIRTUALIZATION_CAP_MIGRATION_NO 0x0 +#define NVML_VGPU_PGPU_VIRTUALIZATION_CAP_MIGRATION_YES 0x1 + +/** + * Macros to indicate the vGPU mode of the GPU. + */ +#define NVML_VGPU_PGPU_HETEROGENEOUS_MODE 0 +#define NVML_VGPU_PGPU_HOMOGENEOUS_MODE 1 + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlVgpuStructs vGPU Structs + * @{ + */ +/***************************************************************************************************/ + +typedef unsigned int nvmlVgpuTypeId_t; + +typedef unsigned int nvmlVgpuInstance_t; + +/** + * Structure to store the vGPU heterogeneous mode of device -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int mode; //!< The vGPU heterogeneous mode +} nvmlVgpuHeterogeneousMode_v1_t; +typedef nvmlVgpuHeterogeneousMode_v1_t nvmlVgpuHeterogeneousMode_t; +#define nvmlVgpuHeterogeneousMode_v1 NVML_STRUCT_VERSION(VgpuHeterogeneousMode, 1) + +/** + * Structure to store the placement ID of vGPU instance -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int placementId; //!< Placement ID of the active vGPU instance +} nvmlVgpuPlacementId_v1_t; +typedef nvmlVgpuPlacementId_v1_t nvmlVgpuPlacementId_t; +#define nvmlVgpuPlacementId_v1 NVML_STRUCT_VERSION(VgpuPlacementId, 1) + +/** + * Structure to store the list of vGPU placements -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int placementSize; //!< The number of slots occupied by the vGPU type + unsigned int count; //!< Count of placement IDs fetched + unsigned int *placementIds; //!< Placement IDs for the vGPU type +} nvmlVgpuPlacementList_v1_t; +#define nvmlVgpuPlacementList_v1 NVML_STRUCT_VERSION(VgpuPlacementList, 1) + +/** + * Structure to store the list of vGPU placements -- version 2 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int placementSize; //!< OUT: The number of slots occupied by the vGPU type + unsigned int count; //!< IN/OUT: Count of the placement IDs + unsigned int *placementIds; //!< IN/OUT: Placement IDs for the vGPU type + unsigned int mode; //!< IN: The vGPU mode. Either NVML_VGPU_PGPU_HETEROGENEOUS_MODE or NVML_VGPU_PGPU_HOMOGENEOUS_MODE +} nvmlVgpuPlacementList_v2_t; +typedef nvmlVgpuPlacementList_v2_t nvmlVgpuPlacementList_t; +#define nvmlVgpuPlacementList_v2 NVML_STRUCT_VERSION(VgpuPlacementList, 2) + +/** + * Structure to store BAR1 size information of vGPU type -- Version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned long long bar1Size; //!< BAR1 size in megabytes +} nvmlVgpuTypeBar1Info_v1_t; +typedef nvmlVgpuTypeBar1Info_v1_t nvmlVgpuTypeBar1Info_t; +#define nvmlVgpuTypeBar1Info_v1 NVML_STRUCT_VERSION(VgpuTypeBar1Info, 1) + +/** + * Structure to store Utilization Value and vgpuInstance + */ +typedef struct nvmlVgpuInstanceUtilizationSample_st +{ + nvmlVgpuInstance_t vgpuInstance; //!< vGPU Instance + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + nvmlValue_t smUtil; //!< SM (3D/Compute) Util Value + nvmlValue_t memUtil; //!< Frame Buffer Memory Util Value + nvmlValue_t encUtil; //!< Encoder Util Value + nvmlValue_t decUtil; //!< Decoder Util Value +} nvmlVgpuInstanceUtilizationSample_t; + +/** + * Structure to store Utilization Value and vgpuInstance Info -- Version 1 + */ +typedef struct +{ + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + nvmlVgpuInstance_t vgpuInstance; //!< vGPU Instance + nvmlValue_t smUtil; //!< SM (3D/Compute) Util Value + nvmlValue_t memUtil; //!< Frame Buffer Memory Util Value + nvmlValue_t encUtil; //!< Encoder Util Value + nvmlValue_t decUtil; //!< Decoder Util Value + nvmlValue_t jpgUtil; //!< Jpeg Util Value + nvmlValue_t ofaUtil; //!< Ofa Util Value +} nvmlVgpuInstanceUtilizationInfo_v1_t; + +/** + * Structure to store recent utilization for vGPU instances running on a device -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + nvmlValueType_t sampleValType; //!< Hold the type of returned sample values + unsigned int vgpuInstanceCount; //!< Hold the number of vGPU instances + unsigned long long lastSeenTimeStamp; //!< Return only samples with timestamp greater than lastSeenTimeStamp + nvmlVgpuInstanceUtilizationInfo_v1_t *vgpuUtilArray; //!< The array (allocated by caller) in which vGPU utilization are returned +} nvmlVgpuInstancesUtilizationInfo_v1_t; +typedef nvmlVgpuInstancesUtilizationInfo_v1_t nvmlVgpuInstancesUtilizationInfo_t; +#define nvmlVgpuInstancesUtilizationInfo_v1 NVML_STRUCT_VERSION(VgpuInstancesUtilizationInfo, 1) + +/** + * Structure to store Utilization Value, vgpuInstance and subprocess information + */ +typedef struct nvmlVgpuProcessUtilizationSample_st +{ + nvmlVgpuInstance_t vgpuInstance; //!< vGPU Instance + unsigned int pid; //!< PID of process running within the vGPU VM + char processName[NVML_VGPU_NAME_BUFFER_SIZE]; //!< Name of process running within the vGPU VM + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + unsigned int smUtil; //!< SM (3D/Compute) Util Value + unsigned int memUtil; //!< Frame Buffer Memory Util Value + unsigned int encUtil; //!< Encoder Util Value + unsigned int decUtil; //!< Decoder Util Value +} nvmlVgpuProcessUtilizationSample_t; + +/** + * Structure to store Utilization Value, vgpuInstance and subprocess information for process running on vGPU instance -- version 1 + */ +typedef struct +{ + char processName[NVML_VGPU_NAME_BUFFER_SIZE]; //!< Name of process running within the vGPU VM + unsigned long long timeStamp; //!< CPU Timestamp in microseconds + nvmlVgpuInstance_t vgpuInstance; //!< vGPU Instance + unsigned int pid; //!< PID of process running within the vGPU VM + unsigned int smUtil; //!< SM (3D/Compute) Util Value + unsigned int memUtil; //!< Frame Buffer Memory Util Value + unsigned int encUtil; //!< Encoder Util Value + unsigned int decUtil; //!< Decoder Util Value + unsigned int jpgUtil; //!< Jpeg Util Value + unsigned int ofaUtil; //!< Ofa Util Value +} nvmlVgpuProcessUtilizationInfo_v1_t; + +/** + * Structure to store recent utilization, vgpuInstance and subprocess information for processes running on vGPU instances active on a device -- version 1 + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + unsigned int vgpuProcessCount; //!< Hold the number of processes running on vGPU instances + unsigned long long lastSeenTimeStamp; //!< Return only samples with timestamp greater than lastSeenTimeStamp + nvmlVgpuProcessUtilizationInfo_v1_t *vgpuProcUtilArray; //!< The array (allocated by caller) in which utilization of processes running on vGPU instances are returned +} nvmlVgpuProcessesUtilizationInfo_v1_t; +typedef nvmlVgpuProcessesUtilizationInfo_v1_t nvmlVgpuProcessesUtilizationInfo_t; +#define nvmlVgpuProcessesUtilizationInfo_v1 NVML_STRUCT_VERSION(VgpuProcessesUtilizationInfo, 1) + +/** + * Structure to store the information of vGPU runtime state -- version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned long long size; //!< OUT: The runtime state size of the vGPU instance +} nvmlVgpuRuntimeState_v1_t; +typedef nvmlVgpuRuntimeState_v1_t nvmlVgpuRuntimeState_t; +#define nvmlVgpuRuntimeState_v1 NVML_STRUCT_VERSION(VgpuRuntimeState, 1) + +/** + * vGPU scheduler policies + */ +#define NVML_VGPU_SCHEDULER_POLICY_UNKNOWN 0 +#define NVML_VGPU_SCHEDULER_POLICY_BEST_EFFORT 1 +#define NVML_VGPU_SCHEDULER_POLICY_EQUAL_SHARE 2 +#define NVML_VGPU_SCHEDULER_POLICY_FIXED_SHARE 3 + +#define NVML_SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT 3 + +#define NVML_SCHEDULER_SW_MAX_LOG_ENTRIES 200 + +#define NVML_VGPU_SCHEDULER_ARR_DEFAULT 0 +#define NVML_VGPU_SCHEDULER_ARR_DISABLE 1 +#define NVML_VGPU_SCHEDULER_ARR_ENABLE 2 + +/** + * vGPU scheduler engine types + */ +#define NVML_VGPU_SCHEDULER_ENGINE_TYPE_GRAPHICS 1 + +/** + * Union to represent the vGPU Scheduler Parameters + */ +typedef union +{ + struct + { + unsigned int avgFactor; //!< Average factor in compensating the timeslice for Adaptive Round Robin mode + unsigned int timeslice; //!< The timeslice in ns for each software run list as configured, or the default value otherwise + } vgpuSchedDataWithARR; + + struct + { + unsigned int timeslice; //!< The timeslice in ns for each software run list as configured, or the default value otherwise + } vgpuSchedData; + +} nvmlVgpuSchedulerParams_t; + +/** + * Structure to store the state and logs of a software runlist + */ +typedef struct nvmlVgpuSchedulerLogEntries_st +{ + unsigned long long timestamp; //!< Timestamp in ns when this software runlist was preeempted + unsigned long long timeRunTotal; //!< Total time in ns this software runlist has run + unsigned long long timeRun; //!< Time in ns this software runlist ran before preemption + unsigned int swRunlistId; //!< Software runlist Id + unsigned long long targetTimeSlice; //!< The actual timeslice after deduction + unsigned long long cumulativePreemptionTime; //!< Preemption time in ns for this SW runlist +} nvmlVgpuSchedulerLogEntry_t; + +/** + * Structure to store a vGPU software scheduler log + */ +typedef struct nvmlVgpuSchedulerLog_st +{ + unsigned int engineId; //!< Engine whose software runlist log entries are fetched + unsigned int schedulerPolicy; //!< Scheduler policy + unsigned int arrMode; //!< Adaptive Round Robin scheduler mode. One of the NVML_VGPU_SCHEDULER_ARR_*. + nvmlVgpuSchedulerParams_t schedulerParams; + unsigned int entriesCount; //!< Count of log entries fetched + nvmlVgpuSchedulerLogEntry_t logEntries[NVML_SCHEDULER_SW_MAX_LOG_ENTRIES]; +} nvmlVgpuSchedulerLog_t; + +/** + * Structure to store the vGPU scheduler state + */ +typedef struct nvmlVgpuSchedulerGetState_st +{ + unsigned int schedulerPolicy; //!< Scheduler policy + unsigned int arrMode; //!< Adaptive Round Robin scheduler mode. One of the NVML_VGPU_SCHEDULER_ARR_*. + nvmlVgpuSchedulerParams_t schedulerParams; +} nvmlVgpuSchedulerGetState_t; + +/** + * Union to represent the vGPU Scheduler set Parameters + */ +typedef union +{ + struct + { + unsigned int avgFactor; //!< Average factor in compensating the timeslice for Adaptive Round Robin mode + unsigned int frequency; //!< Frequency for Adaptive Round Robin mode + } vgpuSchedDataWithARR; + + struct + { + unsigned int timeslice; //!< The timeslice in ns(Nanoseconds) for each software run list as configured, or the default value otherwise + } vgpuSchedData; + +} nvmlVgpuSchedulerSetParams_t; + +/** + * Structure to set the vGPU scheduler state + */ +typedef struct nvmlVgpuSchedulerSetState_st +{ + unsigned int schedulerPolicy; //!< Scheduler policy + unsigned int enableARRMode; //!< Adaptive Round Robin scheduler + nvmlVgpuSchedulerSetParams_t schedulerParams; +} nvmlVgpuSchedulerSetState_t; + +/** + * Structure to store the vGPU scheduler capabilities + */ +typedef struct nvmlVgpuSchedulerCapabilities_st +{ + unsigned int supportedSchedulers[NVML_SUPPORTED_VGPU_SCHEDULER_POLICY_COUNT]; //!< List the supported vGPU schedulers on the device + unsigned int maxTimeslice; //!< Maximum timeslice value in ns + unsigned int minTimeslice; //!< Minimum timeslice value in ns + unsigned int isArrModeSupported; //!< Flag to check Adaptive Round Robin mode enabled/disabled. + unsigned int maxFrequencyForARR; //!< Maximum frequency for Adaptive Round Robin mode + unsigned int minFrequencyForARR; //!< Minimum frequency for Adaptive Round Robin mode + unsigned int maxAvgFactorForARR; //!< Maximum averaging factor for Adaptive Round Robin mode + unsigned int minAvgFactorForARR; //!< Minimum averaging factor for Adaptive Round Robin mode +} nvmlVgpuSchedulerCapabilities_t; + +/** + * Structure to store the vGPU license expiry details + */ +typedef struct nvmlVgpuLicenseExpiry_st +{ + unsigned int year; //!< Year of license expiry + unsigned short month; //!< Month of license expiry + unsigned short day; //!< Day of license expiry + unsigned short hour; //!< Hour of license expiry + unsigned short min; //!< Minutes of license expiry + unsigned short sec; //!< Seconds of license expiry + unsigned char status; //!< License expiry status +} nvmlVgpuLicenseExpiry_t; + +/** + * vGPU license state + */ +#define NVML_GRID_LICENSE_STATE_UNKNOWN 0 //!< Unknown state +#define NVML_GRID_LICENSE_STATE_UNINITIALIZED 1 //!< Uninitialized state +#define NVML_GRID_LICENSE_STATE_UNLICENSED_UNRESTRICTED 2 //!< Unlicensed unrestricted state +#define NVML_GRID_LICENSE_STATE_UNLICENSED_RESTRICTED 3 //!< Unlicensed restricted state +#define NVML_GRID_LICENSE_STATE_UNLICENSED 4 //!< Unlicensed state +#define NVML_GRID_LICENSE_STATE_LICENSED 5 //!< Licensed state + +typedef struct nvmlVgpuLicenseInfo_st +{ + unsigned char isLicensed; //!< License status + nvmlVgpuLicenseExpiry_t licenseExpiry; //!< License expiry information + unsigned int currentState; //!< Current license state +} nvmlVgpuLicenseInfo_t; + +/** + * Structure to store license expiry date and time values + */ +typedef struct nvmlGridLicenseExpiry_st +{ + unsigned int year; //!< Year value of license expiry + unsigned short month; //!< Month value of license expiry + unsigned short day; //!< Day value of license expiry + unsigned short hour; //!< Hour value of license expiry + unsigned short min; //!< Minutes value of license expiry + unsigned short sec; //!< Seconds value of license expiry + unsigned char status; //!< License expiry status +} nvmlGridLicenseExpiry_t; + +/** + * Structure containing vGPU software licensable feature information + */ +typedef struct nvmlGridLicensableFeature_st +{ + nvmlGridLicenseFeatureCode_t featureCode; //!< Licensed feature code + unsigned int featureState; //!< Non-zero if feature is currently licensed, otherwise zero + char licenseInfo[NVML_GRID_LICENSE_BUFFER_SIZE]; //!< Deprecated. + char productName[NVML_GRID_LICENSE_BUFFER_SIZE]; //!< Product name of feature + unsigned int featureEnabled; //!< Non-zero if feature is enabled, otherwise zero + nvmlGridLicenseExpiry_t licenseExpiry; //!< License expiry structure containing date and time +} nvmlGridLicensableFeature_t; + +/** + * Structure to store vGPU software licensable features + */ +typedef struct nvmlGridLicensableFeatures_st +{ + int isGridLicenseSupported; //!< Non-zero if vGPU Software Licensing is supported on the system, otherwise zero + unsigned int licensableFeaturesCount; //!< Entries returned in \a gridLicensableFeatures array + nvmlGridLicensableFeature_t gridLicensableFeatures[NVML_GRID_LICENSE_FEATURE_MAX_COUNT]; //!< Array of vGPU software licensable features. +} nvmlGridLicensableFeatures_t; + +/** + * Enum describing the GPU Recovery Action + */ +typedef enum nvmlDeviceGpuRecoveryAction_s { + NVML_GPU_RECOVERY_ACTION_NONE = 0, + NVML_GPU_RECOVERY_ACTION_GPU_RESET = 1, + NVML_GPU_RECOVERY_ACTION_NODE_REBOOT = 2, + NVML_GPU_RECOVERY_ACTION_DRAIN_P2P = 3, + NVML_GPU_RECOVERY_ACTION_DRAIN_AND_RESET = 4, +} nvmlDeviceGpuRecoveryAction_t; + +/** + * Structure to store the vGPU type IDs -- version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int vgpuCount; //!< IN/OUT: Number of vGPU types + nvmlVgpuTypeId_t *vgpuTypeIds; //!< OUT: List of vGPU type IDs +} nvmlVgpuTypeIdInfo_v1_t; +typedef nvmlVgpuTypeIdInfo_v1_t nvmlVgpuTypeIdInfo_t; +#define nvmlVgpuTypeIdInfo_v1 NVML_STRUCT_VERSION(VgpuTypeIdInfo, 1) + +/** + * Structure to store the maximum number of possible vGPU type IDs -- version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + nvmlVgpuTypeId_t vgpuTypeId; //!< IN: Handle to vGPU type + unsigned int maxInstancePerGI; //!< OUT: Maximum number of vGPU instances per GPU instance +} nvmlVgpuTypeMaxInstance_v1_t; +typedef nvmlVgpuTypeMaxInstance_v1_t nvmlVgpuTypeMaxInstance_t; +#define nvmlVgpuTypeMaxInstance_v1 NVML_STRUCT_VERSION(VgpuTypeMaxInstance, 1) + +/** + * Structure to store active vGPU instance information -- Version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int vgpuCount; //!< IN/OUT: Count of the active vGPU instances + nvmlVgpuInstance_t *vgpuInstances; //!< IN/OUT: list of active vGPU instances +} nvmlActiveVgpuInstanceInfo_v1_t; +typedef nvmlActiveVgpuInstanceInfo_v1_t nvmlActiveVgpuInstanceInfo_t; +#define nvmlActiveVgpuInstanceInfo_v1 NVML_STRUCT_VERSION(ActiveVgpuInstanceInfo, 1) + +/** + * Structure to set vGPU scheduler state information -- version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int engineId; //!< IN: One of NVML_VGPU_SCHEDULER_ENGINE_TYPE_*. + unsigned int schedulerPolicy; //!< IN: Scheduler policy + unsigned int enableARRMode; //!< IN: Adaptive Round Robin scheduler + nvmlVgpuSchedulerSetParams_t schedulerParams; //!< IN: vGPU Scheduler Parameters +} nvmlVgpuSchedulerState_v1_t; +typedef nvmlVgpuSchedulerState_v1_t nvmlVgpuSchedulerState_t; +#define nvmlVgpuSchedulerState_v1 NVML_STRUCT_VERSION(VgpuSchedulerState, 1) + +/** + * Structure to store vGPU scheduler state information -- Version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int engineId; //!< IN: Engine whose software scheduler state info is fetched. One of NVML_VGPU_SCHEDULER_ENGINE_TYPE_*. + unsigned int schedulerPolicy; //!< OUT: Scheduler policy + unsigned int arrMode; //!< OUT: Adaptive Round Robin scheduler mode. One of the NVML_VGPU_SCHEDULER_ARR_*. + nvmlVgpuSchedulerParams_t schedulerParams; //!< OUT: vGPU Scheduler Parameters +} nvmlVgpuSchedulerStateInfo_v1_t; +typedef nvmlVgpuSchedulerStateInfo_v1_t nvmlVgpuSchedulerStateInfo_t; +#define nvmlVgpuSchedulerStateInfo_v1 NVML_STRUCT_VERSION(VgpuSchedulerStateInfo, 1) + +/** + * Structure to store vGPU scheduler log information -- Version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + unsigned int engineId; //!< IN: Engine whose software runlist log entries are fetched. One of One of NVML_VGPU_SCHEDULER_ENGINE_TYPE_*. + unsigned int schedulerPolicy; //!< OUT: Scheduler policy + unsigned int arrMode; //!< OUT: Adaptive Round Robin scheduler mode. One of the NVML_VGPU_SCHEDULER_ARR_*. + nvmlVgpuSchedulerParams_t schedulerParams; //!< OUT: vGPU Scheduler Parameters + unsigned int entriesCount; //!< OUT: Count of log entries fetched + nvmlVgpuSchedulerLogEntry_t logEntries[NVML_SCHEDULER_SW_MAX_LOG_ENTRIES]; //!< OUT: Structure to store the state and logs of a software runlist +} nvmlVgpuSchedulerLogInfo_v1_t; +typedef nvmlVgpuSchedulerLogInfo_v1_t nvmlVgpuSchedulerLogInfo_t; +#define nvmlVgpuSchedulerLogInfo_v1 NVML_STRUCT_VERSION(VgpuSchedulerLogInfo, 1) + +/** + * Structure to store creatable vGPU placement information -- version 1 + */ +typedef struct +{ + unsigned int version; //!< IN: The version number of this struct + nvmlVgpuTypeId_t vgpuTypeId; //!< IN: Handle to vGPU type + unsigned int count; //!< IN/OUT: Count of the placement IDs + unsigned int *placementIds; //!< IN/OUT: Placement IDs for the vGPU type + unsigned int placementSize; //!< OUT: The number of slots occupied by the vGPU type +} nvmlVgpuCreatablePlacementInfo_v1_t; +typedef nvmlVgpuCreatablePlacementInfo_v1_t nvmlVgpuCreatablePlacementInfo_t; +#define nvmlVgpuCreatablePlacementInfo_v1 NVML_STRUCT_VERSION(VgpuCreatablePlacementInfo, 1) + +/** @} */ +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlFieldValueEnums Field Value Enums + * @{ + */ +/***************************************************************************************************/ + +/** + * Field Identifiers. + * + * All Identifiers pertain to a device. Each ID is only used once and is guaranteed never to change. + */ +#define NVML_FI_DEV_ECC_CURRENT 1 //!< Current ECC mode. 1=Active. 0=Inactive +#define NVML_FI_DEV_ECC_PENDING 2 //!< Pending ECC mode. 1=Active. 0=Inactive +/* ECC Count Totals */ +#define NVML_FI_DEV_ECC_SBE_VOL_TOTAL 3 //!< Total single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_TOTAL 4 //!< Total double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_TOTAL 5 //!< Total single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_TOTAL 6 //!< Total double bit aggregate (persistent) ECC errors +/* Individual ECC locations */ +#define NVML_FI_DEV_ECC_SBE_VOL_L1 7 //!< L1 cache single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_L1 8 //!< L1 cache double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_VOL_L2 9 //!< L2 cache single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_L2 10 //!< L2 cache double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_VOL_DEV 11 //!< Device memory single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_DEV 12 //!< Device memory double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_VOL_REG 13 //!< Register file single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_REG 14 //!< Register file double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_VOL_TEX 15 //!< Texture memory single bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_TEX 16 //!< Texture memory double bit volatile ECC errors +#define NVML_FI_DEV_ECC_DBE_VOL_CBU 17 //!< CBU double bit volatile ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_L1 18 //!< L1 cache single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_L1 19 //!< L1 cache double bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_L2 20 //!< L2 cache single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_L2 21 //!< L2 cache double bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_DEV 22 //!< Device memory single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_DEV 23 //!< Device memory double bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_REG 24 //!< Register File single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_REG 25 //!< Register File double bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_SBE_AGG_TEX 26 //!< Texture memory single bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_TEX 27 //!< Texture memory double bit aggregate (persistent) ECC errors +#define NVML_FI_DEV_ECC_DBE_AGG_CBU 28 //!< CBU double bit aggregate ECC errors + +/* Page Retirement */ +#define NVML_FI_DEV_RETIRED_SBE 29 //!< Number of retired pages because of single bit errors +#define NVML_FI_DEV_RETIRED_DBE 30 //!< Number of retired pages because of double bit errors +#define NVML_FI_DEV_RETIRED_PENDING 31 //!< If any pages are pending retirement. 1=yes. 0=no. + +/** + * NVLink Flit Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L0 32 //!< NVLink flow control CRC Error Counter for Lane 0 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L1 33 //!< NVLink flow control CRC Error Counter for Lane 1 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L2 34 //!< NVLink flow control CRC Error Counter for Lane 2 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L3 35 //!< NVLink flow control CRC Error Counter for Lane 3 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L4 36 //!< NVLink flow control CRC Error Counter for Lane 4 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L5 37 //!< NVLink flow control CRC Error Counter for Lane 5 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_TOTAL 38 //!< NVLink flow control CRC Error Counter total for all Lanes + +/** + * NVLink CRC Data Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L0 39 //!< NVLink data CRC Error Counter for Lane 0 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L1 40 //!< NVLink data CRC Error Counter for Lane 1 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L2 41 //!< NVLink data CRC Error Counter for Lane 2 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L3 42 //!< NVLink data CRC Error Counter for Lane 3 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L4 43 //!< NVLink data CRC Error Counter for Lane 4 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L5 44 //!< NVLink data CRC Error Counter for Lane 5 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_TOTAL 45 //!< NvLink data CRC Error Counter total for all Lanes + +/** + * NVLink Replay Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L0 46 //!< NVLink Replay Error Counter for Lane 0 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L1 47 //!< NVLink Replay Error Counter for Lane 1 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L2 48 //!< NVLink Replay Error Counter for Lane 2 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L3 49 //!< NVLink Replay Error Counter for Lane 3 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L4 50 //!< NVLink Replay Error Counter for Lane 4 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L5 51 //!< NVLink Replay Error Counter for Lane 5 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_TOTAL 52 //!< NVLink Replay Error Counter total for all Lanes + +/** + * NVLink Recovery Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L0 53 //!< NVLink Recovery Error Counter for Lane 0 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L1 54 //!< NVLink Recovery Error Counter for Lane 1 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L2 55 //!< NVLink Recovery Error Counter for Lane 2 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L3 56 //!< NVLink Recovery Error Counter for Lane 3 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L4 57 //!< NVLink Recovery Error Counter for Lane 4 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L5 58 //!< NVLink Recovery Error Counter for Lane 5 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_TOTAL 59 //!< NVLink Recovery Error Counter total for all Lanes + +/* NvLink Bandwidth Counters */ +/* + * NVML_FI_DEV_NVLINK_BANDWIDTH_* field values are now deprecated. + * Please use the following field values instead: + * NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX + * NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX + * NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX + * NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX + */ +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L0 60 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 0 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L1 61 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 1 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L2 62 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 2 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L3 63 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 3 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L4 64 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 4 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L5 65 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 5 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_TOTAL 66 //!< NVLink Bandwidth Counter Total for Counter Set 0, All Lanes + +/* NvLink Bandwidth Counters */ +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L0 67 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 0 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L1 68 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 1 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L2 69 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 2 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L3 70 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 3 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L4 71 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 4 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L5 72 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 5 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_TOTAL 73 //!< NVLink Bandwidth Counter Total for Counter Set 1, All Lanes + +/* NVML Perf Policy Counters */ +#define NVML_FI_DEV_PERF_POLICY_POWER 74 //!< Perf Policy Counter for Power Policy +#define NVML_FI_DEV_PERF_POLICY_THERMAL 75 //!< Perf Policy Counter for Thermal Policy +#define NVML_FI_DEV_PERF_POLICY_SYNC_BOOST 76 //!< Perf Policy Counter for Sync boost Policy +#define NVML_FI_DEV_PERF_POLICY_BOARD_LIMIT 77 //!< Perf Policy Counter for Board Limit +#define NVML_FI_DEV_PERF_POLICY_LOW_UTILIZATION 78 //!< Perf Policy Counter for Low GPU Utilization Policy +#define NVML_FI_DEV_PERF_POLICY_RELIABILITY 79 //!< Perf Policy Counter for Reliability Policy +#define NVML_FI_DEV_PERF_POLICY_TOTAL_APP_CLOCKS 80 //!< Perf Policy Counter for Total App Clock Policy +#define NVML_FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS 81 //!< Perf Policy Counter for Total Base Clocks Policy + +/* Memory temperatures */ +#define NVML_FI_DEV_MEMORY_TEMP 82 //!< Memory temperature for the device + +/* Energy Counter */ +#define NVML_FI_DEV_TOTAL_ENERGY_CONSUMPTION 83 //!< Total energy consumption for the GPU in mJ since the driver was last reloaded + +/** + * NVLink Speed + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L0 84 //!< NVLink Speed in MBps for Link 0 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L1 85 //!< NVLink Speed in MBps for Link 1 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L2 86 //!< NVLink Speed in MBps for Link 2 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L3 87 //!< NVLink Speed in MBps for Link 3 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L4 88 //!< NVLink Speed in MBps for Link 4 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L5 89 //!< NVLink Speed in MBps for Link 5 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_COMMON 90 //!< Common NVLink Speed in MBps for active links + +#define NVML_FI_DEV_NVLINK_LINK_COUNT 91 //!< Number of NVLinks present on the device + +#define NVML_FI_DEV_RETIRED_PENDING_SBE 92 //!< If any pages are pending retirement due to SBE. 1=yes. 0=no. +#define NVML_FI_DEV_RETIRED_PENDING_DBE 93 //!< If any pages are pending retirement due to DBE. 1=yes. 0=no. + +#define NVML_FI_DEV_PCIE_REPLAY_COUNTER 94 //!< PCIe replay counter +#define NVML_FI_DEV_PCIE_REPLAY_ROLLOVER_COUNTER 95 //!< PCIe replay rollover counter + +/** + * NVLink Flit Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L6 96 //!< NVLink flow control CRC Error Counter for Lane 6 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L7 97 //!< NVLink flow control CRC Error Counter for Lane 7 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L8 98 //!< NVLink flow control CRC Error Counter for Lane 8 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L9 99 //!< NVLink flow control CRC Error Counter for Lane 9 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L10 100 //!< NVLink flow control CRC Error Counter for Lane 10 +#define NVML_FI_DEV_NVLINK_CRC_FLIT_ERROR_COUNT_L11 101 //!< NVLink flow control CRC Error Counter for Lane 11 + +/** + * NVLink CRC Data Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L6 102 //!< NVLink data CRC Error Counter for Lane 6 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L7 103 //!< NVLink data CRC Error Counter for Lane 7 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L8 104 //!< NVLink data CRC Error Counter for Lane 8 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L9 105 //!< NVLink data CRC Error Counter for Lane 9 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L10 106 //!< NVLink data CRC Error Counter for Lane 10 +#define NVML_FI_DEV_NVLINK_CRC_DATA_ERROR_COUNT_L11 107 //!< NVLink data CRC Error Counter for Lane 11 + +/** + * NVLink Replay Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L6 108 //!< NVLink Replay Error Counter for Lane 6 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L7 109 //!< NVLink Replay Error Counter for Lane 7 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L8 110 //!< NVLink Replay Error Counter for Lane 8 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L9 111 //!< NVLink Replay Error Counter for Lane 9 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L10 112 //!< NVLink Replay Error Counter for Lane 10 +#define NVML_FI_DEV_NVLINK_REPLAY_ERROR_COUNT_L11 113 //!< NVLink Replay Error Counter for Lane 11 + +/** + * NVLink Recovery Error Counters + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L6 114 //!< NVLink Recovery Error Counter for Lane 6 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L7 115 //!< NVLink Recovery Error Counter for Lane 7 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L8 116 //!< NVLink Recovery Error Counter for Lane 8 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L9 117 //!< NVLink Recovery Error Counter for Lane 9 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L10 118 //!< NVLink Recovery Error Counter for Lane 10 +#define NVML_FI_DEV_NVLINK_RECOVERY_ERROR_COUNT_L11 119 //!< NVLink Recovery Error Counter for Lane 11 + +/* NvLink Bandwidth Counters */ +/* + * NVML_FI_DEV_NVLINK_BANDWIDTH_* field values are now deprecated. + * Please use the following field values instead: + * NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX + * NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX + * NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX + * NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX + */ +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L6 120 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 6 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L7 121 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 7 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L8 122 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 8 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L9 123 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 9 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L10 124 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 10 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C0_L11 125 //!< NVLink Bandwidth Counter for Counter Set 0, Lane 11 + +/* NvLink Bandwidth Counters */ +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L6 126 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 6 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L7 127 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 7 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L8 128 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 8 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L9 129 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 9 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L10 130 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 10 +#define NVML_FI_DEV_NVLINK_BANDWIDTH_C1_L11 131 //!< NVLink Bandwidth Counter for Counter Set 1, Lane 11 + +/** + * NVLink Speed + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L6 132 //!< NVLink Speed in MBps for Link 6 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L7 133 //!< NVLink Speed in MBps for Link 7 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L8 134 //!< NVLink Speed in MBps for Link 8 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L9 135 //!< NVLink Speed in MBps for Link 9 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L10 136 //!< NVLink Speed in MBps for Link 10 +#define NVML_FI_DEV_NVLINK_SPEED_MBPS_L11 137 //!< NVLink Speed in MBps for Link 11 + +/** + * NVLink throughput counters field values + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + * A scopeId of UINT_MAX returns aggregate value summed up across all links + * for the specified counter type in fieldId. + */ +#define NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_TX 138 //!< NVLink TX Data throughput in KiB +#define NVML_FI_DEV_NVLINK_THROUGHPUT_DATA_RX 139 //!< NVLink RX Data throughput in KiB +#define NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_TX 140 //!< NVLink TX Data + protocol overhead in KiB +#define NVML_FI_DEV_NVLINK_THROUGHPUT_RAW_RX 141 //!< NVLink RX Data + protocol overhead in KiB + +/* Row Remapper */ +#define NVML_FI_DEV_REMAPPED_COR 142 //!< Number of remapped rows due to correctable errors +#define NVML_FI_DEV_REMAPPED_UNC 143 //!< Number of remapped rows due to uncorrectable errors +#define NVML_FI_DEV_REMAPPED_PENDING 144 //!< If any rows are pending remapping. 1=yes 0=no +#define NVML_FI_DEV_REMAPPED_FAILURE 145 //!< If any rows failed to be remapped 1=yes 0=no + +/** + * Remote device NVLink ID + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_REMOTE_NVLINK_ID 146 //!< Remote device NVLink ID + +/** + * NVSwitch: connected NVLink count + */ +#define NVML_FI_DEV_NVSWITCH_CONNECTED_LINK_COUNT 147 //!< Number of NVLinks connected to NVSwitch + +/* NvLink ECC Data Error Counters + * + * Lane ID needs to be specified in the scopeId field in nvmlFieldValue_t. + * + */ +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L0 148 //!< NVLink data ECC Error Counter for Link 0 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L1 149 //!< NVLink data ECC Error Counter for Link 1 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L2 150 //!< NVLink data ECC Error Counter for Link 2 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L3 151 //!< NVLink data ECC Error Counter for Link 3 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L4 152 //!< NVLink data ECC Error Counter for Link 4 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L5 153 //!< NVLink data ECC Error Counter for Link 5 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L6 154 //!< NVLink data ECC Error Counter for Link 6 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L7 155 //!< NVLink data ECC Error Counter for Link 7 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L8 156 //!< NVLink data ECC Error Counter for Link 8 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L9 157 //!< NVLink data ECC Error Counter for Link 9 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L10 158 //!< NVLink data ECC Error Counter for Link 10 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_L11 159 //!< NVLink data ECC Error Counter for Link 11 +#define NVML_FI_DEV_NVLINK_ECC_DATA_ERROR_COUNT_TOTAL 160 //!< NVLink data ECC Error Counter total for all Links + +/** + * NVLink Error Replay + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_ERROR_DL_REPLAY 161 //!< NVLink Replay Error Counter + //!< This is unsupported for Blackwell+. + //!< Please use NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_* +/** + * NVLink Recovery Error Counter + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_ERROR_DL_RECOVERY 162 //!< NVLink Recovery Error Counter + //!< This is unsupported for Blackwell+ + //!< Please use NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_* + +/** + * NVLink Recovery Error CRC Counter + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_ERROR_DL_CRC 163 //!< NVLink CRC Error Counter + //!< This is unsupported for Blackwell+ + //!< Please use NVML_FI_DEV_NVLINK_COUNT_LINK_RECOVERY_* + +/** + * NVLink Speed, State and Version field id 164, 165, and 166 + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_GET_SPEED 164 //!< NVLink Speed in MBps +#define NVML_FI_DEV_NVLINK_GET_STATE 165 //!< NVLink State - Active,Inactive +#define NVML_FI_DEV_NVLINK_GET_VERSION 166 //!< NVLink Version + +#define NVML_FI_DEV_NVLINK_GET_POWER_STATE 167 //!< NVLink Power state. 0=HIGH_SPEED 1=LOW_SPEED +#define NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD 168 //!< NVLink length of idle period (units can be found from + //!< NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_UNITS) before + //!< transitioning links to sleep state + +#define NVML_FI_DEV_PCIE_L0_TO_RECOVERY_COUNTER 169 //!< Device PEX error recovery counter + +#define NVML_FI_DEV_C2C_LINK_COUNT 170 //!< Number of C2C Links present on the device +#define NVML_FI_DEV_C2C_LINK_GET_STATUS 171 //!< C2C Link Status 0=INACTIVE 1=ACTIVE +#define NVML_FI_DEV_C2C_LINK_GET_MAX_BW 172 //!< C2C Link Speed in MBps for active links + +#define NVML_FI_DEV_PCIE_COUNT_CORRECTABLE_ERRORS 173 //!< PCIe Correctable Errors Counter +#define NVML_FI_DEV_PCIE_COUNT_NAKS_RECEIVED 174 //!< PCIe NAK Receive Counter +#define NVML_FI_DEV_PCIE_COUNT_RECEIVER_ERROR 175 //!< PCIe Receiver Error Counter +#define NVML_FI_DEV_PCIE_COUNT_BAD_TLP 176 //!< PCIe Bad TLP Counter +#define NVML_FI_DEV_PCIE_COUNT_NAKS_SENT 177 //!< PCIe NAK Send Counter +#define NVML_FI_DEV_PCIE_COUNT_BAD_DLLP 178 //!< PCIe Bad DLLP Counter +#define NVML_FI_DEV_PCIE_COUNT_NON_FATAL_ERROR 179 //!< PCIe Non Fatal Error Counter +#define NVML_FI_DEV_PCIE_COUNT_FATAL_ERROR 180 //!< PCIe Fatal Error Counter +#define NVML_FI_DEV_PCIE_COUNT_UNSUPPORTED_REQ 181 //!< PCIe Unsupported Request Counter +#define NVML_FI_DEV_PCIE_COUNT_LCRC_ERROR 182 //!< PCIe LCRC Error Counter +#define NVML_FI_DEV_PCIE_COUNT_LANE_ERROR 183 //!< PCIe Per Lane Error Counter. + +#define NVML_FI_DEV_IS_RESETLESS_MIG_SUPPORTED 184 //!< Device's Restless MIG Capability + +/** + * Retrieves power usage for this GPU in milliwatts. + * It is only available if power management mode is supported. See \ref nvmlDeviceGetPowerManagementMode and + * \ref nvmlDeviceGetPowerUsage. + * + * scopeId needs to be specified. It signifies: + * 0 - GPU Only Scope - Metrics for GPU are retrieved + * 1 - Module scope - Metrics for the module (e.g. CPU + GPU) are retrieved. + * Note: CPU here refers to NVIDIA CPU (e.g. Grace). x86 or non-NVIDIA ARM is not supported + */ +#define NVML_FI_DEV_POWER_AVERAGE 185 //!< GPU power averaged over 1 sec interval, supported on Ampere (except GA100) or newer architectures. +#define NVML_FI_DEV_POWER_INSTANT 186 //!< Current GPU power, supported on all architectures. +#define NVML_FI_DEV_POWER_MIN_LIMIT 187 //!< Minimum power limit in milliwatts. +#define NVML_FI_DEV_POWER_MAX_LIMIT 188 //!< Maximum power limit in milliwatts. +#define NVML_FI_DEV_POWER_DEFAULT_LIMIT 189 //!< Default power limit in milliwatts (limit which device boots with). +#define NVML_FI_DEV_POWER_CURRENT_LIMIT 190 //!< Limit currently enforced in milliwatts (This includes other limits set elsewhere. E.g. Out-of-band). +#define NVML_FI_DEV_ENERGY 191 //!< Total energy consumption (in mJ) since the driver was last reloaded. Same as \ref NVML_FI_DEV_TOTAL_ENERGY_CONSUMPTION for the GPU. +#define NVML_FI_DEV_POWER_REQUESTED_LIMIT 192 //!< Power limit requested by NVML or any other userspace client. + +/** + * GPU T.Limit temperature thresholds in degree Celsius + * + * These fields are supported on Ada and later architectures and supersedes \ref nvmlDeviceGetTemperatureThreshold. + */ +#define NVML_FI_DEV_TEMPERATURE_SHUTDOWN_TLIMIT 193 //!< T.Limit temperature after which GPU may shut down for HW protection +#define NVML_FI_DEV_TEMPERATURE_SLOWDOWN_TLIMIT 194 //!< T.Limit temperature after which GPU may begin HW slowdown +#define NVML_FI_DEV_TEMPERATURE_MEM_MAX_TLIMIT 195 //!< T.Limit temperature after which GPU may begin SW slowdown due to memory temperature +#define NVML_FI_DEV_TEMPERATURE_GPU_MAX_TLIMIT 196 //!< T.Limit temperature after which GPU may be throttled below base clock + +#define NVML_FI_DEV_PCIE_COUNT_TX_BYTES 197 //!< PCIe transmit bytes. Value can be wrapped. +#define NVML_FI_DEV_PCIE_COUNT_RX_BYTES 198 //!< PCIe receive bytes. Value can be wrapped. + +#define NVML_FI_DEV_IS_MIG_MODE_INDEPENDENT_MIG_QUERY_CAPABLE 199 //!< MIG mode independent, MIG query capable device. 1=yes. 0=no. + +#define NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD_MAX 200 //!< Max Nvlink Power Threshold. See NVML_FI_DEV_NVLINK_GET_POWER_THRESHOLD + +/** + * NVLink counter field id 201-225 + * + * Link ID needs to be specified in the scopeId field in nvmlFieldValue_t. + */ +#define NVML_FI_DEV_NVLINK_COUNT_XMIT_PACKETS 201 //!usedGpuMemory is not supported + + + unsigned long long time; //!< Amount of time in ms during which the compute context was active. The time is reported as 0 if + //!< the process is not terminated + + unsigned long long startTime; //!< CPU Timestamp in usec representing start time for the process + + unsigned int isRunning; //!< Flag to represent if the process is running (1 for running, 0 for terminated) + + unsigned int reserved[5]; //!< Reserved for future use +} nvmlAccountingStats_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlEncoderStructs Encoder Structs + * @{ + */ +/***************************************************************************************************/ + +/** + * Represents type of encoder for capacity can be queried + */ +typedef enum nvmlEncoderQueryType_enum +{ + NVML_ENCODER_QUERY_H264 = 0x00, //!< H264 encoder + NVML_ENCODER_QUERY_HEVC = 0x01, //!< HEVC encoder + NVML_ENCODER_QUERY_AV1 = 0x02, //!< AV1 encoder + NVML_ENCODER_QUERY_UNKNOWN = 0xFF //!< Unknown encoder +}nvmlEncoderType_t; + +/** + * Structure to hold encoder session data + */ +typedef struct nvmlEncoderSessionInfo_st +{ + unsigned int sessionId; //!< Unique session ID + unsigned int pid; //!< Owning process ID + nvmlVgpuInstance_t vgpuInstance; //!< Owning vGPU instance ID (only valid on vGPU hosts, otherwise zero) + nvmlEncoderType_t codecType; //!< Video encoder type + unsigned int hResolution; //!< Current encode horizontal resolution + unsigned int vResolution; //!< Current encode vertical resolution + unsigned int averageFps; //!< Moving average encode frames per second + unsigned int averageLatency; //!< Moving average encode latency in microseconds +}nvmlEncoderSessionInfo_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlFBCStructs Frame Buffer Capture Structures +* @{ +*/ +/***************************************************************************************************/ + +/** + * Represents frame buffer capture session type + */ +typedef enum nvmlFBCSessionType_enum +{ + NVML_FBC_SESSION_TYPE_UNKNOWN = 0, //!< Unknown + NVML_FBC_SESSION_TYPE_TOSYS, //!< ToSys + NVML_FBC_SESSION_TYPE_CUDA, //!< Cuda + NVML_FBC_SESSION_TYPE_VID, //!< Vid + NVML_FBC_SESSION_TYPE_HWENC //!< HEnc +} nvmlFBCSessionType_t; + +/** + * Structure to hold frame buffer capture sessions stats + */ +typedef struct nvmlFBCStats_st +{ + unsigned int sessionsCount; //!< Total no of sessions + unsigned int averageFPS; //!< Moving average new frames captured per second + unsigned int averageLatency; //!< Moving average new frame capture latency in microseconds +} nvmlFBCStats_t; + +#define NVML_NVFBC_SESSION_FLAG_DIFFMAP_ENABLED 0x00000001 //!< Bit specifying differential map state. +#define NVML_NVFBC_SESSION_FLAG_CLASSIFICATIONMAP_ENABLED 0x00000002 //!< Bit specifying classification map state. +#define NVML_NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_NO_WAIT 0x00000004 //!< Bit specifying if capture was requested as non-blocking call. +#define NVML_NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_INFINITE 0x00000008 //!< Bit specifying if capture was requested as blocking call. +#define NVML_NVFBC_SESSION_FLAG_CAPTURE_WITH_WAIT_TIMEOUT 0x00000010 //!< Bit specifying if capture was requested as blocking call with timeout period. + +/** + * Structure to hold FBC session data + */ +typedef struct nvmlFBCSessionInfo_st +{ + unsigned int sessionId; //!< Unique session ID + unsigned int pid; //!< Owning process ID + nvmlVgpuInstance_t vgpuInstance; //!< Owning vGPU instance ID (only valid on vGPU hosts, otherwise zero) + unsigned int displayOrdinal; //!< Display identifier + nvmlFBCSessionType_t sessionType; //!< Type of frame buffer capture session + unsigned int sessionFlags; //!< Session flags (one or more of NVML_NVFBC_SESSION_FLAG_XXX). + unsigned int hMaxResolution; //!< Max horizontal resolution supported by the capture session + unsigned int vMaxResolution; //!< Max vertical resolution supported by the capture session + unsigned int hResolution; //!< Horizontal resolution requested by caller in capture call + unsigned int vResolution; //!< Vertical resolution requested by caller in capture call + unsigned int averageFPS; //!< Moving average new frames captured per second + unsigned int averageLatency; //!< Moving average new frame capture latency in microseconds +} nvmlFBCSessionInfo_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlDrainDefs Drain State definitions + * @{ + */ +/***************************************************************************************************/ + +/** + * Is the GPU device to be removed from the kernel by nvmlDeviceRemoveGpu() + */ +typedef enum nvmlDetachGpuState_enum +{ + NVML_DETACH_GPU_KEEP = 0, + NVML_DETACH_GPU_REMOVE +} nvmlDetachGpuState_t; + +/** + * Parent bridge PCIe link state requested by nvmlDeviceRemoveGpu() + */ +typedef enum nvmlPcieLinkState_enum +{ + NVML_PCIE_LINK_KEEP = 0, + NVML_PCIE_LINK_SHUT_DOWN +} nvmlPcieLinkState_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlConfidentialComputingDefs Confidential Computing definitions + * @{ + */ +/***************************************************************************************************/ +/** + * Confidential Compute CPU Capabilities values + */ +#define NVML_CC_SYSTEM_CPU_CAPS_NONE 0 +#define NVML_CC_SYSTEM_CPU_CAPS_AMD_SEV 1 +#define NVML_CC_SYSTEM_CPU_CAPS_INTEL_TDX 2 +#define NVML_CC_SYSTEM_CPU_CAPS_AMD_SEV_SNP 3 +#define NVML_CC_SYSTEM_CPU_CAPS_AMD_SNP_VTOM 4 + +/** + * Confidenial Compute GPU Capabilities values + */ +#define NVML_CC_SYSTEM_GPUS_CC_NOT_CAPABLE 0 +#define NVML_CC_SYSTEM_GPUS_CC_CAPABLE 1 + +typedef struct nvmlConfComputeSystemCaps_st { + unsigned int cpuCaps; + unsigned int gpusCaps; +} nvmlConfComputeSystemCaps_t; + +/** + * Confidential Compute DevTools Mode values + */ +#define NVML_CC_SYSTEM_DEVTOOLS_MODE_OFF 0 +#define NVML_CC_SYSTEM_DEVTOOLS_MODE_ON 1 + +/** + * Confidential Compute Environment values + */ +#define NVML_CC_SYSTEM_ENVIRONMENT_UNAVAILABLE 0 +#define NVML_CC_SYSTEM_ENVIRONMENT_SIM 1 +#define NVML_CC_SYSTEM_ENVIRONMENT_PROD 2 + +/** + * Confidential Compute Feature Status values + */ +#define NVML_CC_SYSTEM_FEATURE_DISABLED 0 +#define NVML_CC_SYSTEM_FEATURE_ENABLED 1 + +typedef struct nvmlConfComputeSystemState_st { + unsigned int environment; + unsigned int ccFeature; + unsigned int devToolsMode; +} nvmlConfComputeSystemState_t; + +/** + * Confidential Compute Multigpu mode values + */ +#define NVML_CC_SYSTEM_MULTIGPU_NONE 0 +#define NVML_CC_SYSTEM_MULTIGPU_PROTECTED_PCIE 1 +#define NVML_CC_SYSTEM_MULTIGPU_NVLE 2 + +/** + * Confidential Compute System settings + */ +typedef struct { + unsigned int version; + unsigned int environment; + unsigned int ccFeature; + unsigned int devToolsMode; + unsigned int multiGpuMode; +} nvmlSystemConfComputeSettings_v1_t; + +typedef nvmlSystemConfComputeSettings_v1_t nvmlSystemConfComputeSettings_t; +#define nvmlSystemConfComputeSettings_v1 NVML_STRUCT_VERSION(SystemConfComputeSettings, 1) + +/** + * Protected memory size + */ +typedef struct +nvmlConfComputeMemSizeInfo_st +{ + unsigned long long protectedMemSizeKib; + unsigned long long unprotectedMemSizeKib; +} nvmlConfComputeMemSizeInfo_t; + +/** + * Confidential Compute GPUs/System Ready State values + */ +#define NVML_CC_ACCEPTING_CLIENT_REQUESTS_FALSE 0 +#define NVML_CC_ACCEPTING_CLIENT_REQUESTS_TRUE 1 + +/** + * GPU Certificate Details + */ +#define NVML_GPU_CERT_CHAIN_SIZE 0x1000 +#define NVML_GPU_ATTESTATION_CERT_CHAIN_SIZE 0x1400 + +typedef struct nvmlConfComputeGpuCertificate_st { + unsigned int certChainSize; + unsigned int attestationCertChainSize; + unsigned char certChain[NVML_GPU_CERT_CHAIN_SIZE]; + unsigned char attestationCertChain[NVML_GPU_ATTESTATION_CERT_CHAIN_SIZE]; +} nvmlConfComputeGpuCertificate_t; + +/** + * GPU Attestation Report + */ +#define NVML_CC_GPU_CEC_NONCE_SIZE 0x20 +#define NVML_CC_GPU_ATTESTATION_REPORT_SIZE 0x2000 +#define NVML_CC_GPU_CEC_ATTESTATION_REPORT_SIZE 0x1000 +#define NVML_CC_CEC_ATTESTATION_REPORT_NOT_PRESENT 0 +#define NVML_CC_CEC_ATTESTATION_REPORT_PRESENT 1 +#define NVML_CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MIN 50 +#define NVML_CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MAX 65 + +typedef struct nvmlConfComputeGpuAttestationReport_st { + unsigned int isCecAttestationReportPresent; //!< output + unsigned int attestationReportSize; //!< output + unsigned int cecAttestationReportSize; //!< output + unsigned char nonce[NVML_CC_GPU_CEC_NONCE_SIZE]; //!< input: spdm supports 32 bytes on nonce + unsigned char attestationReport[NVML_CC_GPU_ATTESTATION_REPORT_SIZE]; //!< output + unsigned char cecAttestationReport[NVML_CC_GPU_CEC_ATTESTATION_REPORT_SIZE]; //!< output +} nvmlConfComputeGpuAttestationReport_t; + +typedef struct nvmlConfComputeSetKeyRotationThresholdInfo_st { + unsigned int version; + unsigned long long maxAttackerAdvantage; +} nvmlConfComputeSetKeyRotationThresholdInfo_v1_t; + +typedef nvmlConfComputeSetKeyRotationThresholdInfo_v1_t nvmlConfComputeSetKeyRotationThresholdInfo_t; +#define nvmlConfComputeSetKeyRotationThresholdInfo_v1 \ + NVML_STRUCT_VERSION(ConfComputeSetKeyRotationThresholdInfo, 1) + +typedef struct nvmlConfComputeGetKeyRotationThresholdInfo_st { + unsigned int version; + unsigned long long attackerAdvantage; +} nvmlConfComputeGetKeyRotationThresholdInfo_v1_t; + +typedef nvmlConfComputeGetKeyRotationThresholdInfo_v1_t nvmlConfComputeGetKeyRotationThresholdInfo_t; +#define nvmlConfComputeGetKeyRotationThresholdInfo_v1 \ + NVML_STRUCT_VERSION(ConfComputeGetKeyRotationThresholdInfo, 1) + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlFabricDefs Fabric definitions + * @{ + */ +/***************************************************************************************************/ + +#define NVML_GPU_FABRIC_UUID_LEN 16 //!< Length of Fabric UUID + +/** + * Fabric Probe States + */ +#define NVML_GPU_FABRIC_STATE_NOT_SUPPORTED 0 //!< Fabric Probe State not supported +#define NVML_GPU_FABRIC_STATE_NOT_STARTED 1 //!< Fabric Probe has not started +#define NVML_GPU_FABRIC_STATE_IN_PROGRESS 2 //!< Fabric Probe in progress +#define NVML_GPU_FABRIC_STATE_COMPLETED 3 //!< Fabric Probe State completed + +/** + * Probe State of GPU registration process + */ +typedef unsigned char nvmlGpuFabricState_t; + +/** + * Contains the device fabric information + */ +typedef struct +{ + unsigned char clusterUuid[NVML_GPU_FABRIC_UUID_LEN]; //!< Uuid of the cluster to which this GPU belongs + nvmlReturn_t status; //!< Error status, if any. Must be checked only if state returns "complete". + unsigned int cliqueId; //!< ID of the fabric clique to which this GPU belongs + nvmlGpuFabricState_t state; //!< Current state of GPU registration process. See NVML_GPU_FABRIC_STATE_* +} nvmlGpuFabricInfo_t; + +/** + * Fabric Degraded BW + */ +#define NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_NOT_SUPPORTED 0 //!< Fabric Health Mask: Degraded Bandwidth not supported +#define NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_TRUE 1 //!< Fabric Health Mask: Bandwidth degraded +#define NVML_GPU_FABRIC_HEALTH_MASK_DEGRADED_BW_FALSE 2 //!< Fabric Health Mask: Bandwidth not degraded + +#define NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_DEGRADED_BW 0 //!< Fabric Health Mask Bit Shift for Degraded Bandwidth +#define NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_DEGRADED_BW 0x3 //!< Fabric Health Mask Width for Degraded Bandwidth + +/** + * Fabric Route Recovery + */ +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_NOT_SUPPORTED 0 //!< Fabric Health Mask: Route Recovery not supported +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_TRUE 1 //!< Fabric Health Mask: Route Recovery in progress +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_RECOVERY_FALSE 2 //!< Fabric Health Mask: Route Recovery not in progress + +#define NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_RECOVERY 2 //!< Fabric Health Mask Bit Shift for Route Recovery +#define NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_RECOVERY 0x3 //!< Fabric Health Mask Width for Route Recovery + +/** + * Nvlink Fabric Route Unhealthy + */ +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_NOT_SUPPORTED 0 //!< Fabric Health Mask: Route Unhealthy not supported +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_TRUE 1 //!< Fabric Health Mask: Route is unhealthy +#define NVML_GPU_FABRIC_HEALTH_MASK_ROUTE_UNHEALTHY_FALSE 2 //!< Fabric Health Mask: Route is healthy + +#define NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ROUTE_UNHEALTHY 4 //!< Fabric Health Mask Bit Shift for Route Unhealthy +#define NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ROUTE_UNHEALTHY 0x3 //!< Fabric Health Mask Width for Route Unhealthy + +/** + * Fabric Access Timeout Recovery + */ +#define NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_NOT_SUPPORTED 0 //!< Fabric Health Mask: Access Timeout Recovery not supported +#define NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_TRUE 1 //!< Fabric Health Mask: Access Timeout Recovery in progress +#define NVML_GPU_FABRIC_HEALTH_MASK_ACCESS_TIMEOUT_RECOVERY_FALSE 2 //!< Fabric Health Mask: Access Timeout Recovery not in progress + +#define NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_ACCESS_TIMEOUT_RECOVERY 6 //!< Fabric Health Mask Bit Shift for Access Timeout Recovery +#define NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_ACCESS_TIMEOUT_RECOVERY 0x3 //!< Fabric Health Mask Width for Access Timeout Recovery + +/** + * Fabric Incorrect Configuration + */ +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NOT_SUPPORTED 0 //!< Fabric Health Mask: Incorrect Configuration not supported +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NONE 1 //!< Fabric Health Mask: Correct Configuration +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_SYSGUID 2 //!< Fabric Health Mask: Incorrect Configuration - SysGUID +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INCORRECT_CHASSIS_SN 3 //!< Fabric Health Mask: Incorrect Configuration - Chassis Serial Number +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_NO_PARTITION 4 //!< Fabric Health Mask: Incorrect Configuration - No Partition +#define NVML_GPU_FABRIC_HEALTH_MASK_INCORRECT_CONFIGURATION_INSUFFICIENT_NVLINKS 5 //!< Fabric Health Mask: Incorrect Configuration - Insufficient Nvlinks + +#define NVML_GPU_FABRIC_HEALTH_MASK_SHIFT_INCORRECT_CONFIGURATION 8 //!< Fabric Health Mask Bit Shift for Incorrect Configuration +#define NVML_GPU_FABRIC_HEALTH_MASK_WIDTH_INCORRECT_CONFIGURATION 0xf //!< Fabric Health Mask Width for Incorrect Configuration + +/** + * Fabric Health + */ +#define NVML_GPU_FABRIC_HEALTH_SUMMARY_NOT_SUPPORTED 0 //!< Fabric Health Summary: Not supported +#define NVML_GPU_FABRIC_HEALTH_SUMMARY_HEALTHY 1 //!< Fabric Health Summary: Healthy +#define NVML_GPU_FABRIC_HEALTH_SUMMARY_UNHEALTHY 2 //!< Fabric Health Summary: Unhealthy +#define NVML_GPU_FABRIC_HEALTH_SUMMARY_LIMITED_CAPACITY 3 //!< Fabric Health Summary: Limited Capacity + +/** + * GPU Fabric Health Status Mask for various fields can be obtained + * using the below macro. + * Ex - NVML_GPU_FABRIC_HEALTH_GET(var, _DEGRADED_BW) + */ +#define NVML_GPU_FABRIC_HEALTH_GET(var, type) \ + (((var) >> NVML_GPU_FABRIC_HEALTH_MASK_SHIFT##type) & \ + (NVML_GPU_FABRIC_HEALTH_MASK_WIDTH##type)) + +/** + * GPU Fabric Health Status Mask for various fields can be tested + * using the below macro. + * Ex - NVML_GPU_FABRIC_HEALTH_TEST(var, _DEGRADED_BW, _TRUE) + */ +#define NVML_GPU_FABRIC_HEALTH_TEST(var, type, val) \ + (NVML_GPU_FABRIC_HEALTH_GET(var, type) == \ + NVML_GPU_FABRIC_HEALTH_MASK##type##val) + +/** +* GPU Fabric information (v2). +* +* @deprecated nvmlGpuFabricInfo_v2_t is deprecated and will be removed in a future release. +* Use nvmlGpuFabricInfo_v3_t instead +* +* Version 2 adds the \ref nvmlGpuFabricInfo_v2_t.version field +* to the start of the structure, and the \ref nvmlGpuFabricInfo_v2_t.healthMask +* field to the end. This structure is not backwards-compatible with +* \ref nvmlGpuFabricInfo_t. +*/ +typedef struct +{ + unsigned int version; //!< Structure version identifier (set to nvmlGpuFabricInfo_v2) + unsigned char clusterUuid[NVML_GPU_FABRIC_UUID_LEN]; //!< Uuid of the cluster to which this GPU belongs + nvmlReturn_t status; //!< Probe Error status, if any. Must be checked only if Probe state returns "complete". + unsigned int cliqueId; //!< ID of the fabric clique to which this GPU belongs + nvmlGpuFabricState_t state; //!< Current Probe State of GPU registration process. See NVML_GPU_FABRIC_STATE_* + unsigned int healthMask; //!< GPU Fabric health Status Mask. See NVML_GPU_FABRIC_HEALTH_MASK_* +} nvmlGpuFabricInfo_v2_t; + +/** +* Version identifier value for \ref nvmlGpuFabricInfo_v2_t.version. +*/ +#define nvmlGpuFabricInfo_v2 NVML_STRUCT_VERSION(GpuFabricInfo, 2) + +/** +* GPU Fabric information (v3). +*/ +typedef struct +{ + unsigned int version; //!< Structure version identifier (set to nvmlGpuFabricInfo_v2) + unsigned char clusterUuid[NVML_GPU_FABRIC_UUID_LEN]; //!< Uuid of the cluster to which this GPU belongs + nvmlReturn_t status; //!< Probe Error status, if any. Must be checked only if Probe state returns "complete". + unsigned int cliqueId; //!< ID of the fabric clique to which this GPU belongs + nvmlGpuFabricState_t state; //!< Current Probe State of GPU registration process. See NVML_GPU_FABRIC_STATE_* + unsigned int healthMask; //!< GPU Fabric health Status Mask. See NVML_GPU_FABRIC_HEALTH_MASK_* + unsigned char healthSummary; //!< GPU Fabric health summary. See NVML_GPU_FABRIC_HEALTH_SUMMARY_* +} nvmlGpuFabricInfo_v3_t; + +typedef nvmlGpuFabricInfo_v3_t nvmlGpuFabricInfoV_t; + +/** +* Version identifier value for \ref nvmlGpuFabricInfo_v3_t.version. +*/ +#define nvmlGpuFabricInfo_v3 NVML_STRUCT_VERSION(GpuFabricInfo, 3) + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlInitializationAndCleanup Initialization and Cleanup + * This chapter describes the methods that handle NVML initialization and cleanup. + * It is the user's responsibility to call \ref nvmlInit_v2() before calling any other methods, and + * nvmlShutdown() once NVML is no longer being used. + * @{ + */ +/***************************************************************************************************/ + +#define NVML_INIT_FLAG_NO_GPUS 1 //!< Don't fail nvmlInit() when no GPUs are found +#define NVML_INIT_FLAG_NO_ATTACH 2 //!< Don't attach GPUs + +/** + * Initialize NVML, but don't initialize any GPUs yet. + * + * \note nvmlInit_v3 introduces a "flags" argument, that allows passing boolean values + * modifying the behaviour of nvmlInit(). + * \note In NVML 5.319 new nvmlInit_v2 has replaced nvmlInit"_v1" (default in NVML 4.304 and older) that + * did initialize all GPU devices in the system. + * + * This allows NVML to communicate with a GPU + * when other GPUs in the system are unstable or in a bad state. When using this API, GPUs are + * discovered and initialized in nvmlDeviceGetHandleBy* functions instead. + * + * \note To contrast nvmlInit_v2 with nvmlInit"_v1", NVML 4.304 nvmlInit"_v1" will fail when any detected GPU is in + * a bad or unstable state. + * + * For all products. + * + * This method, should be called once before invoking any other methods in the library. + * A reference count of the number of initializations is maintained. Shutdown only occurs + * when the reference count reaches zero. + * + * @return + * - \ref NVML_SUCCESS if NVML has been properly initialized + * - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running + * - \ref NVML_ERROR_NO_PERMISSION if NVML does not have permission to talk to the driver + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlInit_v2(void); + +/** + * nvmlInitWithFlags is a variant of nvmlInit(), that allows passing a set of boolean values + * modifying the behaviour of nvmlInit(). + * Other than the "flags" parameter it is completely similar to \ref nvmlInit_v2. + * + * For all products. + * + * @param flags behaviour modifier flags + * + * @return + * - \ref NVML_SUCCESS if NVML has been properly initialized + * - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running + * - \ref NVML_ERROR_NO_PERMISSION if NVML does not have permission to talk to the driver + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlInitWithFlags(unsigned int flags); + +/** + * Shut down NVML by releasing all GPU resources previously allocated with \ref nvmlInit_v2(). + * + * For all products. + * + * This method should be called after NVML work is done, once for each call to \ref nvmlInit_v2() + * A reference count of the number of initializations is maintained. Shutdown only occurs + * when the reference count reaches zero. For backwards compatibility, no error is reported if + * nvmlShutdown() is called more times than nvmlInit(). + * + * @return + * - \ref NVML_SUCCESS if NVML has been properly shut down + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlShutdown(void); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlErrorReporting Error reporting + * This chapter describes helper functions for error reporting routines. + * @{ + */ +/***************************************************************************************************/ + +/** + * Helper method for converting NVML error codes into readable strings. + * + * For all products. + * + * @param result NVML error code to convert + * + * @return String representation of the error. + * + */ +const DECLDIR char* nvmlErrorString(nvmlReturn_t result); +/** @} */ + + +/***************************************************************************************************/ +/** @defgroup nvmlConstants Constants + * @{ + */ +/***************************************************************************************************/ + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetInforomVersion and \ref nvmlDeviceGetInforomImageVersion + */ +#define NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE 16 + +/** + * Buffer size guaranteed to be large enough for storing GPU identifiers. + */ +#define NVML_DEVICE_UUID_BUFFER_SIZE 80 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetUUID + */ +#define NVML_DEVICE_UUID_V2_BUFFER_SIZE 96 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetBoardPartNumber + */ +#define NVML_DEVICE_PART_NUMBER_BUFFER_SIZE 80 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlSystemGetDriverVersion + */ +#define NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE 80 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlSystemGetNVMLVersion + */ +#define NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE 80 + +/** + * Buffer size guaranteed to be large enough for storing GPU device names. + */ +#define NVML_DEVICE_NAME_BUFFER_SIZE 64 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetName + */ +#define NVML_DEVICE_NAME_V2_BUFFER_SIZE 96 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetSerial + */ +#define NVML_DEVICE_SERIAL_BUFFER_SIZE 30 + +/** + * Buffer size guaranteed to be large enough for \ref nvmlDeviceGetVbiosVersion + */ +#define NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE 32 + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlSystemQueries System Queries + * This chapter describes the queries that NVML can perform against the local system. These queries + * are not device-specific. + * @{ + */ +/***************************************************************************************************/ + +/** + * Retrieves the version of the system's graphics driver. + * + * For all products. + * + * The version identifier is an alphanumeric string. It will not exceed 80 characters in length + * (including the NULL terminator). See \ref nvmlConstants::NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE. + * + * @param version Reference in which to return the version identifier + * @param length The maximum allowed length of the string returned in \a version + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a version is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + */ +nvmlReturn_t DECLDIR nvmlSystemGetDriverVersion(char *version, unsigned int length); + +/** + * Retrieves the version of the NVML library. + * + * For all products. + * + * The version identifier is an alphanumeric string. It will not exceed 80 characters in length + * (including the NULL terminator). See \ref nvmlConstants::NVML_SYSTEM_NVML_VERSION_BUFFER_SIZE. + * + * @param version Reference in which to return the version identifier + * @param length The maximum allowed length of the string returned in \a version + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a version is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + */ +nvmlReturn_t DECLDIR nvmlSystemGetNVMLVersion(char *version, unsigned int length); + +/** + * Retrieves the version of the CUDA driver. + * + * For all products. + * + * The CUDA driver version returned will be retreived from the currently installed version of CUDA. + * If the cuda library is not found, this function will return a known supported version number. + * + * @param cudaDriverVersion Reference in which to return the version identifier + * + * @return + * - \ref NVML_SUCCESS if \a cudaDriverVersion has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a cudaDriverVersion is NULL + */ +nvmlReturn_t DECLDIR nvmlSystemGetCudaDriverVersion(int *cudaDriverVersion); + +/** + * Retrieves the version of the CUDA driver from the shared library. + * + * For all products. + * + * The returned CUDA driver version by calling cuDriverGetVersion() + * + * @param cudaDriverVersion Reference in which to return the version identifier + * + * @return + * - \ref NVML_SUCCESS if \a cudaDriverVersion has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a cudaDriverVersion is NULL + * - \ref NVML_ERROR_LIBRARY_NOT_FOUND if \a libcuda.so.1 or libcuda.dll is not found + * - \ref NVML_ERROR_FUNCTION_NOT_FOUND if \a cuDriverGetVersion() is not found in the shared library + */ +nvmlReturn_t DECLDIR nvmlSystemGetCudaDriverVersion_v2(int *cudaDriverVersion); + +/** + * Macros for converting the CUDA driver version number to Major and Minor version numbers. + */ +#define NVML_CUDA_DRIVER_VERSION_MAJOR(v) ((v)/1000) +#define NVML_CUDA_DRIVER_VERSION_MINOR(v) (((v)%1000)/10) + +/** + * Gets name of the process with provided process id + * + * For all products. + * + * Returned process name is cropped to provided length. + * name string is encoded in ANSI. + * + * @param pid The identifier of the process + * @param name Reference in which to return the process name + * @param length The maximum allowed length of the string returned in \a name + * + * @return + * - \ref NVML_SUCCESS if \a name has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a name is NULL or \a length is 0. + * - \ref NVML_ERROR_NOT_FOUND if process doesn't exists + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlSystemGetProcessName(unsigned int pid, char *name, unsigned int length); + +/** + * Retrieves the IDs and firmware versions for any Host Interface Cards (HICs) in the system. + * + * For S-class products. + * + * The \a hwbcCount argument is expected to be set to the size of the input \a hwbcEntries array. + * The HIC must be connected to an S-class system for it to be reported by this function. + * + * @param hwbcCount Size of hwbcEntries array + * @param hwbcEntries Array holding information about hwbc + * + * @return + * - \ref NVML_SUCCESS if \a hwbcCount and \a hwbcEntries have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if either \a hwbcCount or \a hwbcEntries is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a hwbcCount indicates that the \a hwbcEntries array is too small + */ +nvmlReturn_t DECLDIR nvmlSystemGetHicVersion(unsigned int *hwbcCount, nvmlHwbcEntry_t *hwbcEntries); + +/** + * Retrieve the set of GPUs that have a CPU affinity with the given CPU number + * For all products. + * Supported on Linux only. + * + * @param cpuNumber The CPU number + * @param count When zero, is set to the number of matching GPUs such that \a deviceArray + * can be malloc'd. When non-zero, \a deviceArray will be filled with \a count + * number of device handles. + * @param deviceArray An array of device handles for GPUs found with affinity to \a cpuNumber + * + * @return + * - \ref NVML_SUCCESS if \a deviceArray or \a count (if initially zero) has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a cpuNumber, or \a count is invalid, or \a deviceArray is NULL with a non-zero \a count + * - \ref NVML_ERROR_NOT_SUPPORTED if the device or OS does not support this feature + * - \ref NVML_ERROR_UNKNOWN an error has occurred in underlying topology discovery + */ +nvmlReturn_t DECLDIR nvmlSystemGetTopologyGpuSet(unsigned int cpuNumber, unsigned int *count, nvmlDevice_t *deviceArray); + +/** + * Structure to store Driver branch information + */ +typedef struct +{ + unsigned int version; //!< The version number of this struct + char branch[NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE]; //!< driver branch +} nvmlSystemDriverBranchInfo_v1_t; +typedef nvmlSystemDriverBranchInfo_v1_t nvmlSystemDriverBranchInfo_t; +#define nvmlSystemDriverBranchInfo_v1 NVML_STRUCT_VERSION(SystemDriverBranchInfo, 1) + +/** + * Retrieves the driver branch of the NVIDIA driver installed on the system. + * + * For all products. + * + * The branch identifier is an alphanumeric string. It will not exceed 80 characters in length + * (including the NULL terminator). See \ref nvmlConstants::NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE. + * + * @param branchInfo Pointer to the driver branch information structure \a nvmlSystemDriverBranchInfo_t + * @param length The maximum allowed length of the driver branch string + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a branchInfo is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlSystemGetDriverBranch(nvmlSystemDriverBranchInfo_t *branchInfo, unsigned int length); + + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlUnitQueries Unit Queries + * This chapter describes that queries that NVML can perform against each unit. For S-class systems only. + * In each case the device is identified with an nvmlUnit_t handle. This handle is obtained by + * calling \ref nvmlUnitGetHandleByIndex(). + * @{ + */ +/***************************************************************************************************/ + + /** + * Retrieves the number of units in the system. + * + * For S-class products. + * + * @param unitCount Reference in which to return the number of units + * + * @return + * - \ref NVML_SUCCESS if \a unitCount has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unitCount is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetCount(unsigned int *unitCount); + +/** + * Acquire the handle for a particular unit, based on its index. + * + * For S-class products. + * + * Valid indices are derived from the \a unitCount returned by \ref nvmlUnitGetCount(). + * For example, if \a unitCount is 2 the valid indices are 0 and 1, corresponding to UNIT 0 and UNIT 1. + * + * The order in which NVML enumerates units has no guarantees of consistency between reboots. + * + * @param index The index of the target unit, >= 0 and < \a unitCount + * @param unit Reference in which to return the unit handle + * + * @return + * - \ref NVML_SUCCESS if \a unit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a unit is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetHandleByIndex(unsigned int index, nvmlUnit_t *unit); + +/** + * Retrieves the static information associated with a unit. + * + * For S-class products. + * + * See \ref nvmlUnitInfo_t for details on available unit info. + * + * @param unit The identifier of the target unit + * @param info Reference in which to return the unit information + * + * @return + * - \ref NVML_SUCCESS if \a info has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a info is NULL + */ +nvmlReturn_t DECLDIR nvmlUnitGetUnitInfo(nvmlUnit_t unit, nvmlUnitInfo_t *info); + +/** + * Retrieves the LED state associated with this unit. + * + * For S-class products. + * + * See \ref nvmlLedState_t for details on allowed states. + * + * @param unit The identifier of the target unit + * @param state Reference in which to return the current LED state + * + * @return + * - \ref NVML_SUCCESS if \a state has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a state is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this is not an S-class product + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlUnitSetLedState() + */ +nvmlReturn_t DECLDIR nvmlUnitGetLedState(nvmlUnit_t unit, nvmlLedState_t *state); + +/** + * Retrieves the PSU stats for the unit. + * + * For S-class products. + * + * See \ref nvmlPSUInfo_t for details on available PSU info. + * + * @param unit The identifier of the target unit + * @param psu Reference in which to return the PSU information + * + * @return + * - \ref NVML_SUCCESS if \a psu has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a psu is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this is not an S-class product + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetPsuInfo(nvmlUnit_t unit, nvmlPSUInfo_t *psu); + +/** + * Retrieves the temperature readings for the unit, in degrees C. + * + * For S-class products. + * + * Depending on the product, readings may be available for intake (type=0), + * exhaust (type=1) and board (type=2). + * + * @param unit The identifier of the target unit + * @param type The type of reading to take + * @param temp Reference in which to return the intake temperature + * + * @return + * - \ref NVML_SUCCESS if \a temp has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit or \a type is invalid or \a temp is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this is not an S-class product + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetTemperature(nvmlUnit_t unit, unsigned int type, unsigned int *temp); + +/** + * Retrieves the fan speed readings for the unit. + * + * For S-class products. + * + * See \ref nvmlUnitFanSpeeds_t for details on available fan speed info. + * + * @param unit The identifier of the target unit + * @param fanSpeeds Reference in which to return the fan speed information + * + * @return + * - \ref NVML_SUCCESS if \a fanSpeeds has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid or \a fanSpeeds is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this is not an S-class product + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetFanSpeedInfo(nvmlUnit_t unit, nvmlUnitFanSpeeds_t *fanSpeeds); + +/** + * Retrieves the set of GPU devices that are attached to the specified unit. + * + * For S-class products. + * + * The \a deviceCount argument is expected to be set to the size of the input \a devices array. + * + * @param unit The identifier of the target unit + * @param deviceCount Reference in which to provide the \a devices array size, and + * to return the number of attached GPU devices + * @param devices Reference in which to return the references to the attached GPU devices + * + * @return + * - \ref NVML_SUCCESS if \a deviceCount and \a devices have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a deviceCount indicates that the \a devices array is too small + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit is invalid, either of \a deviceCount or \a devices is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlUnitGetDevices(nvmlUnit_t unit, unsigned int *deviceCount, nvmlDevice_t *devices); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlDeviceQueries Device Queries + * This chapter describes that queries that NVML can perform against each device. + * In each case the device is identified with an nvmlDevice_t handle. This handle is obtained by + * calling one of \ref nvmlDeviceGetHandleByIndex_v2(), \ref nvmlDeviceGetHandleBySerial(), + * \ref nvmlDeviceGetHandleByPciBusId_v2(). or \ref nvmlDeviceGetHandleByUUID(). + * @{ + */ +/***************************************************************************************************/ + + /** + * Retrieves the number of compute devices in the system. A compute device is a single GPU. + * + * For all products. + * + * Note: New nvmlDeviceGetCount_v2 (default in NVML 5.319) returns count of all devices in the system + * even if nvmlDeviceGetHandleByIndex_v2 returns NVML_ERROR_NO_PERMISSION for such device. + * Update your code to handle this error, or use NVML 4.304 or older nvml header file. + * For backward binary compatibility reasons _v1 version of the API is still present in the shared + * library. + * Old _v1 version of nvmlDeviceGetCount doesn't count devices that NVML has no permission to talk to. + * + * @param deviceCount Reference in which to return the number of accessible devices + * + * @return + * - \ref NVML_SUCCESS if \a deviceCount has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a deviceCount is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCount_v2(unsigned int *deviceCount); + +/** + * Get attributes (engine counts etc.) for the given NVML device handle. + * + * @note This API currently only supports MIG device handles. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device NVML device handle + * @param attributes Device attributes + * + * @return + * - \ref NVML_SUCCESS if \a device attributes were successfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device handle is invalid + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAttributes_v2(nvmlDevice_t device, nvmlDeviceAttributes_t *attributes); + +/** + * Acquire the handle for a particular device, based on its index. + * + * For all products. + * + * Valid indices are derived from the \a accessibleDevices count returned by + * \ref nvmlDeviceGetCount_v2(). For example, if \a accessibleDevices 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. For that reason it + * is recommended that devices be looked up by their PCI ids or UUID. See + * \ref nvmlDeviceGetHandleByUUID() and \ref nvmlDeviceGetHandleByPciBusId_v2(). + * + * Note: The NVML index may not correlate with other APIs, such as the CUDA device index. + * + * Starting from NVML 5, this API causes NVML to initialize the target GPU + * NVML may initialize additional GPUs if: + * - The target GPU is an SLI slave + * + * Note: New nvmlDeviceGetCount_v2 (default in NVML 5.319) returns count of all devices in the system + * even if nvmlDeviceGetHandleByIndex_v2 returns NVML_ERROR_NO_PERMISSION for such device. + * Update your code to handle this error, or use NVML 4.304 or older nvml header file. + * For backward binary compatibility reasons _v1 version of the API is still present in the shared + * library. + * Old _v1 version of nvmlDeviceGetCount doesn't count devices that NVML has no permission to talk to. + * + * This means that nvmlDeviceGetHandleByIndex_v2 and _v1 can return different devices for the same index. + * If you don't touch macros that map old (_v1) versions to _v2 versions at the top of the file you don't + * need to worry about that. + * + * @param index The index of the target GPU, >= 0 and < \a accessibleDevices + * @param device Reference in which to return the device handle + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a device is NULL + * - \ref NVML_ERROR_INSUFFICIENT_POWER if any attached devices have improperly attached external power cables + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to talk to this device + * - \ref NVML_ERROR_IRQ_ISSUE if NVIDIA kernel detected an interrupt issue with the attached GPUs + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetIndex + * @see nvmlDeviceGetCount + */ +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByIndex_v2(unsigned int index, nvmlDevice_t *device); + +/** + * Acquire the handle for a particular device, based on its board serial number. + * + * For Fermi &tm; or newer fully supported devices. + * + * This number corresponds to the value printed directly on the board, and to the value returned by + * \ref nvmlDeviceGetSerial(). + * + * @deprecated Since more than one GPU can exist on a single board this function is deprecated in favor + * of \ref nvmlDeviceGetHandleByUUID. + * For dual GPU boards this function will return NVML_ERROR_INVALID_ARGUMENT. + * + * Starting from NVML 5, this API causes NVML to initialize the target GPU + * NVML may initialize additional GPUs as it searches for the target GPU + * + * @param serial The board serial number of the target GPU + * @param device Reference in which to return the device handle + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a serial is invalid, \a device is NULL or more than one + * device has the same serial (dual GPU boards) + * - \ref NVML_ERROR_NOT_FOUND if \a serial does not match a valid device on the system + * - \ref NVML_ERROR_INSUFFICIENT_POWER if any attached devices have improperly attached external power cables + * - \ref NVML_ERROR_IRQ_ISSUE if NVIDIA kernel detected an interrupt issue with the attached GPUs + * - \ref NVML_ERROR_GPU_IS_LOST if any GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetSerial + * @see nvmlDeviceGetHandleByUUID + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetHandleBySerial(const char *serial, nvmlDevice_t *device); + +/** + * Acquire the handle for a particular device, based on its globally unique immutable UUID (in ASCII format) associated with each device. + * + * For all products. + * + * @param uuid The UUID of the target GPU or MIG instance + * @param device Reference in which to return the device handle or MIG device handle + * + * Starting from NVML 5, this API causes NVML to initialize the target GPU + * NVML may initialize additional GPUs as it searches for the target GPU + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a uuid is invalid or \a device is null + * - \ref NVML_ERROR_NOT_FOUND if \a uuid does not match a valid device on the system + * - \ref NVML_ERROR_INSUFFICIENT_POWER if any attached devices have improperly attached external power cables + * - \ref NVML_ERROR_IRQ_ISSUE if NVIDIA kernel detected an interrupt issue with the attached GPUs + * - \ref NVML_ERROR_GPU_IS_LOST if any GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetUUID + */ +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByUUID(const char *uuid, nvmlDevice_t *device); + +/** + * Acquire the handle for a particular device, based on its globally unique immutable UUID (in either ASCII or binary format) associated with each device. + * See \ref nvmlUUID_v1_t for more information on the UUID struct. The caller must set the appropriate version prior to calling this API. + * + * For all products. + * + * @param[in] uuid The UUID of the target GPU or MIG instance + * @param[out] device Reference in which to return the device handle or MIG device handle + * + * This API causes NVML to initialize the target GPU + * NVML may initialize additional GPUs as it searches for the target GPU + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a uuid is invalid, \a device is null or \a uuid->type is invalid + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_FOUND if \a uuid does not match a valid device on the system + * - \ref NVML_ERROR_GPU_IS_LOST if any GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByUUIDV(const nvmlUUID_t *uuid, nvmlDevice_t *device); + +/** + * Acquire the handle for a particular device, based on its PCI bus id. + * + * For all products. + * + * This value corresponds to the nvmlPciInfo_t::busId returned by \ref nvmlDeviceGetPciInfo_v3(). + * + * Starting from NVML 5, this API causes NVML to initialize the target GPU + * NVML may initialize additional GPUs if: + * - The target GPU is an SLI slave + * + * \note NVML 4.304 and older version of nvmlDeviceGetHandleByPciBusId"_v1" returns NVML_ERROR_NOT_FOUND + * instead of NVML_ERROR_NO_PERMISSION. + * + * @param pciBusId The PCI bus id of the target GPU + * Accept the following formats (all numbers in hexadecimal): + * domain:bus:device.function in format %x:%x:%x.%x + * domain:bus:device in format %x:%x:%x + * bus:device.function in format %x:%x.%x + * + * @param device Reference in which to return the device handle + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a pciBusId is invalid or \a device is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a pciBusId does not match a valid device on the system + * - \ref NVML_ERROR_INSUFFICIENT_POWER if the attached device has improperly attached external power cables + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to talk to this device + * - \ref NVML_ERROR_IRQ_ISSUE if NVIDIA kernel detected an interrupt issue with the attached GPUs + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByPciBusId_v2(const char *pciBusId, nvmlDevice_t *device); + +/** + * Retrieves the name of this device. + * + * For all products. + * + * The name is an alphanumeric string that denotes a particular product, e.g. Tesla &tm; C2070. It will not + * exceed 96 characters in length (including the NULL terminator). See \ref + * nvmlConstants::NVML_DEVICE_NAME_V2_BUFFER_SIZE. + * + * When used with MIG device handles the API returns MIG device names which can be used to identify devices + * based on their attributes. + * + * @param device The identifier of the target device + * @param name Reference in which to return the product name + * @param length The maximum allowed length of the string returned in \a name + * + * @return + * - \ref NVML_SUCCESS if \a name has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a name is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetName(nvmlDevice_t device, char *name, unsigned int length); + +/** + * Retrieves the brand of this device. + * + * For all products. + * + * The type is a member of \ref nvmlBrandType_t defined above. + * + * @param device The identifier of the target device + * @param type Reference in which to return the product brand type + * + * @return + * - \ref NVML_SUCCESS if \a name has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a type is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBrand(nvmlDevice_t device, nvmlBrandType_t *type); + +/** + * Retrieves the NVML index of this device. + * + * For all products. + * + * Valid indices are derived from the \a accessibleDevices count returned by + * \ref nvmlDeviceGetCount_v2(). For example, if \a accessibleDevices 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. For that reason it + * is recommended that devices be looked up by their PCI ids or GPU UUID. See + * \ref nvmlDeviceGetHandleByPciBusId_v2() and \ref nvmlDeviceGetHandleByUUID(). + * + * When used with MIG device handles this API returns indices that can be + * passed to \ref nvmlDeviceGetMigDeviceHandleByIndex to retrieve an identical handle. + * MIG device indices are unique within a device. + * + * Note: The NVML index may not correlate with other APIs, such as the CUDA device index. + * + * @param device The identifier of the target device + * @param index Reference in which to return the NVML index of the device + * + * @return + * - \ref NVML_SUCCESS if \a index has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a index is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetHandleByIndex() + * @see nvmlDeviceGetCount() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetIndex(nvmlDevice_t device, unsigned int *index); + +/** + * Retrieves the globally unique board serial number associated with this device's board. + * + * For all products with an inforom. + * + * The serial number is an alphanumeric string that will not exceed 30 characters (including the NULL terminator). + * This number matches the serial number tag that is physically attached to the board. See \ref + * nvmlConstants::NVML_DEVICE_SERIAL_BUFFER_SIZE. + * + * @param device The identifier of the target device + * @param serial Reference in which to return the board/module serial number + * @param length The maximum allowed length of the string returned in \a serial + * + * @return + * - \ref NVML_SUCCESS if \a serial has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a serial is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSerial(nvmlDevice_t device, char *serial, unsigned int length); + +/** + * Get a unique identifier for the device module on the baseboard + * + * This API retrieves a unique identifier for each GPU module that exists on a given baseboard. + * For non-baseboard products, this ID would always be 0. + * + * @param device The identifier of the target device + * @param moduleId Unique identifier for the GPU module + * + * @return + * - \ref NVML_SUCCESS if \a moduleId has been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a moduleId is invalid + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetModuleId(nvmlDevice_t device, unsigned int *moduleId); + +/** + * Retrieves the Device's C2C Mode information + * + * @param device The identifier of the target device + * @param c2cModeInfo Output struct containing the device's C2C Mode info + * + * @return + * - \ref NVML_SUCCESS if \a C2C Mode Infor query is successful + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a serial is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetC2cModeInfoV(nvmlDevice_t device, nvmlC2cModeInfo_v1_t *c2cModeInfo); + +/***************************************************************************************************/ + +/** @defgroup nvmlAffinity CPU and Memory Affinity + * This chapter describes NVML operations that are associated with CPU and memory + * affinity. + * @{ + */ +/***************************************************************************************************/ + +//! Scope of NUMA node for affinity queries +#define NVML_AFFINITY_SCOPE_NODE 0 +//! Scope of processor socket for affinity queries +#define NVML_AFFINITY_SCOPE_SOCKET 1 + +typedef unsigned int nvmlAffinityScope_t; + +/** + * Retrieves an array of unsigned ints (sized to nodeSetSize) of bitmasks with + * the ideal memory affinity within node or socket for the device. + * For example, if NUMA node 0, 1 are ideal within the socket for the device and nodeSetSize == 1, + * result[0] = 0x3 + * + * \note If requested scope is not applicable to the target topology, the API + * will fall back to reporting the memory affinity for the immediate non-I/O + * ancestor of the device. + * + * For Kepler &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param nodeSetSize The size of the nodeSet array that is safe to access + * @param nodeSet Array reference in which to return a bitmask of NODEs, 64 NODEs per + * unsigned long on 64-bit machines, 32 on 32-bit machines + * @param scope Scope that change the default behavior + * + * @return + * - \ref NVML_SUCCESS if \a NUMA node Affinity has been filled + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, nodeSetSize == 0, nodeSet is NULL or scope is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ + +nvmlReturn_t DECLDIR nvmlDeviceGetMemoryAffinity(nvmlDevice_t device, unsigned int nodeSetSize, unsigned long *nodeSet, nvmlAffinityScope_t scope); + +/** + * Retrieves an array of unsigned ints (sized to cpuSetSize) of bitmasks with the + * ideal CPU affinity within node or socket for the device. + * For example, if processors 0, 1, 32, and 33 are ideal for the device and cpuSetSize == 2, + * result[0] = 0x3, result[1] = 0x3 + * + * \note If requested scope is not applicable to the target topology, the API + * will fall back to reporting the CPU affinity for the immediate non-I/O + * ancestor of the device. + * + * For Kepler &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param cpuSetSize The size of the cpuSet array that is safe to access + * @param cpuSet Array reference in which to return a bitmask of CPUs, 64 CPUs per + * unsigned long on 64-bit machines, 32 on 32-bit machines + * @param scope Scope that change the default behavior + * + * @return + * - \ref NVML_SUCCESS if \a cpuAffinity has been filled + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, cpuSetSize == 0, cpuSet is NULL or sope is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ + +nvmlReturn_t DECLDIR nvmlDeviceGetCpuAffinityWithinScope(nvmlDevice_t device, unsigned int cpuSetSize, unsigned long *cpuSet, nvmlAffinityScope_t scope); + +/** + * Retrieves an array of unsigned ints (sized to cpuSetSize) of bitmasks with the ideal CPU affinity for the device + * For example, if processors 0, 1, 32, and 33 are ideal for the device and cpuSetSize == 2, + * result[0] = 0x3, result[1] = 0x3 + * This is equivalent to calling \ref nvmlDeviceGetCpuAffinityWithinScope with \ref NVML_AFFINITY_SCOPE_NODE. + * + * For Kepler &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param cpuSetSize The size of the cpuSet array that is safe to access + * @param cpuSet Array reference in which to return a bitmask of CPUs, 64 CPUs per + * unsigned long on 64-bit machines, 32 on 32-bit machines + * + * @return + * - \ref NVML_SUCCESS if \a cpuAffinity has been filled + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, cpuSetSize == 0, or cpuSet is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCpuAffinity(nvmlDevice_t device, unsigned int cpuSetSize, unsigned long *cpuSet); + +/** + * Sets the ideal affinity for the calling thread and device using the guidelines + * given in nvmlDeviceGetCpuAffinity(). 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 &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if the calling process has been successfully bound + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetCpuAffinity(nvmlDevice_t device); + +/** + * 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 &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if the calling process has been successfully unbound + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceClearCpuAffinity(nvmlDevice_t device); + +/** + * Get the NUMA node of the given GPU device. + * This only applies to platforms where the GPUs are NUMA nodes. + * + * @param[in] device The device handle + * @param[out] node NUMA node ID of the device + * + * @returns + * - \ref NVML_SUCCESS if the NUMA node is retrieved successfully + * - \ref NVML_ERROR_NOT_SUPPORTED if request is not supported on the current platform + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device \a node is invalid + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNumaNodeId(nvmlDevice_t device, unsigned int *node); + +/** + * Get the addressing mode for a given GPU. Addressing modes can be one of: + * 1. HMM: System allocated memory (malloc, mmap) is addressable from the device (GPU), + * via software-based mirroring of the CPU's page tables, on the GPU. + * 2. ATS: System allocated memory (malloc, mmap) is addressable from the device (GPU), + * via Address Translation Services. This means that there is (effectively) + * a single set of page tables, and the CPU and GPU both use them. + * 3. None: Neither HMM nor ATS is active. + * + * %TURING_OR_NEWER% + * Supported on Linux only. + * + * @param[in] device The device handle + * @param[out] mode Pointer to addressing mode of the device + * + * @returns + * - \ref NVML_SUCCESS if \a mode is retrieved successfully + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED if request is not supported on the current platform + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device \a node is invalid + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAddressingMode(nvmlDevice_t device, nvmlDeviceAddressingMode_t *mode); + +/** + * Get the repair status for TPC/Channel repair + * + * For Ampere &tm; or newer fully supported devices. + * + * @param[in] device The identifier of the target device + * @param[out] repairStatus Reference to \a nvmlRepairStatus_t + * + * @return + * - \ref NVML_SUCCESS if the query was successful + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the provided version is invalid/unsupported + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRepairStatus(nvmlDevice_t device, nvmlRepairStatus_t *repairStatus); + +/** + * Retrieve the common ancestor for two devices + * For all products. + * Supported on Linux only. + * + * @param device1 The identifier of the first device + * @param device2 The identifier of the second device + * @param pathInfo A \ref nvmlGpuTopologyLevel_t that gives the path type + * + * @return + * - \ref NVML_SUCCESS if \a pathInfo has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device1, or \a device2 is invalid, or \a pathInfo is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device or OS does not support this feature + * - \ref NVML_ERROR_UNKNOWN an error has occurred in underlying topology discovery + */ + +/** @} */ +nvmlReturn_t DECLDIR nvmlDeviceGetTopologyCommonAncestor(nvmlDevice_t device1, nvmlDevice_t device2, nvmlGpuTopologyLevel_t *pathInfo); + +/** + * Retrieve the set of GPUs that are nearest to a given device at a specific interconnectivity level + * For all products. + * Supported on Linux only. + * + * @param device The identifier of the first device + * @param level The \ref nvmlGpuTopologyLevel_t level to search for other GPUs + * @param count When zero, is set to the number of matching GPUs such that \a deviceArray + * can be malloc'd. When non-zero, \a deviceArray will be filled with \a count + * number of device handles. + * @param deviceArray An array of device handles for GPUs found at \a level + * + * @return + * - \ref NVML_SUCCESS if \a deviceArray or \a count (if initially zero) has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a level, or \a count is invalid, or \a deviceArray is NULL with a non-zero \a count + * - \ref NVML_ERROR_NOT_SUPPORTED if the device or OS does not support this feature + * - \ref NVML_ERROR_UNKNOWN an error has occurred in underlying topology discovery + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTopologyNearestGpus(nvmlDevice_t device, nvmlGpuTopologyLevel_t level, unsigned int *count, nvmlDevice_t *deviceArray); + +/** + * Retrieve the status for a given p2p capability index between a given pair of GPU + * + * @param device1 The first device + * @param device2 The second device + * @param p2pIndex p2p Capability Index being looked for between \a device1 and \a device2 + * @param p2pStatus Reference in which to return the status of the \a p2pIndex + * between \a device1 and \a device2 + * @return + * - \ref NVML_SUCCESS if \a p2pStatus has been populated + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device1 or \a device2 or \a p2pIndex is invalid or \a p2pStatus is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetP2PStatus(nvmlDevice_t device1, nvmlDevice_t device2, nvmlGpuP2PCapsIndex_t p2pIndex,nvmlGpuP2PStatus_t *p2pStatus); + +/** + * Retrieves the globally unique immutable UUID associated with this device, as a 5 part hexadecimal string, + * that augments the immutable, board serial identifier. + * + * For all products. + * + * The UUID is a globally unique identifier. It is the only available identifier for pre-Fermi-architecture products. + * It does NOT correspond to any identifier printed on the board. It will not exceed 96 characters in length + * (including the NULL terminator). See \ref nvmlConstants::NVML_DEVICE_UUID_V2_BUFFER_SIZE. + * + * When used with MIG device handles the API returns globally unique UUIDs which can be used to identify MIG + * devices across both GPU and MIG devices. UUIDs are immutable for the lifetime of a MIG device. + * + * @param device The identifier of the target device + * @param uuid Reference in which to return the GPU UUID + * @param length The maximum allowed length of the string returned in \a uuid + * + * @return + * - \ref NVML_SUCCESS if \a uuid has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a uuid is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetUUID(nvmlDevice_t device, char *uuid, unsigned int length); + +/** + * Retrieves minor number for the device. The minor number for the device is such that the Nvidia device node file for + * each GPU will have the form /dev/nvidia[minor number]. + * + * For all products. + * Supported only for Linux + * + * @param device The identifier of the target device + * @param minorNumber Reference in which to return the minor number for the device + * @return + * - \ref NVML_SUCCESS if the minor number is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a minorNumber is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMinorNumber(nvmlDevice_t device, unsigned int *minorNumber); + +/** + * Retrieves the the device board part number which is programmed into the board's InfoROM + * + * For all products. + * + * @param device Identifier of the target device + * @param partNumber Reference to the buffer to return + * @param length Length of the buffer reference + * + * @return + * - \ref NVML_SUCCESS if \a partNumber has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NOT_SUPPORTED if the needed VBIOS fields have not been filled + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a serial is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBoardPartNumber(nvmlDevice_t device, char* partNumber, unsigned int length); + +/** + * Retrieves 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 will not + * exceed 16 characters in length (including the NULL terminator). + * See \ref nvmlConstants::NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE. + * + * See \ref nvmlInforomObject_t for details on the available infoROM objects. + * + * @param device The identifier of the target device + * @param object The target infoROM object + * @param version Reference in which to return the infoROM version + * @param length The maximum allowed length of the string returned in \a version + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a version is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have an infoROM + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetInforomImageVersion + */ +nvmlReturn_t DECLDIR nvmlDeviceGetInforomVersion(nvmlDevice_t device, nvmlInforomObject_t object, char *version, unsigned int length); + +/** + * Retrieves the global infoROM image version + * + * For all products with an inforom. + * + * Image version just like VBIOS version uniquely describes the exact version of the infoROM flashed on the board + * in contrast to infoROM object version which is only an indicator of supported features. + * Version string will not exceed 16 characters in length (including the NULL terminator). + * See \ref nvmlConstants::NVML_DEVICE_INFOROM_VERSION_BUFFER_SIZE. + * + * @param device The identifier of the target device + * @param version Reference in which to return the infoROM image version + * @param length The maximum allowed length of the string returned in \a version + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a version is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have an infoROM + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetInforomVersion + */ +nvmlReturn_t DECLDIR nvmlDeviceGetInforomImageVersion(nvmlDevice_t device, char *version, unsigned int length); + +/** + * Retrieves 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. + * Checksum can change between driver releases or when user changes configuration (e.g. disable/enable ECC) + * + * @param device The identifier of the target device + * @param checksum Reference in which to return the infoROM configuration checksum + * + * @return + * - \ref NVML_SUCCESS if \a checksum has been set + * - \ref NVML_ERROR_CORRUPTED_INFOROM if the device's checksum couldn't be retrieved due to infoROM corruption + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a checksum is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetInforomConfigurationChecksum(nvmlDevice_t device, unsigned int *checksum); + +/** + * Reads the infoROM from the flash and verifies the checksums. + * + * For all products with an inforom. + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if infoROM is not corrupted + * - \ref NVML_ERROR_CORRUPTED_INFOROM if the device's infoROM is corrupted + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceValidateInforom(nvmlDevice_t device); + +/** + * Retrieves 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. + * + * @param device The identifier of the target device + * @param timestamp The start timestamp of the last BBX Flush + * @param durationUs The duration (us) of the last BBX Flush + * + * @return + * - \ref NVML_SUCCESS if \a timestamp and \a durationUs are successfully retrieved + * - \ref NVML_ERROR_NOT_READY if the BBX object has not been flushed yet + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have an infoROM + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetInforomVersion + */ +nvmlReturn_t DECLDIR nvmlDeviceGetLastBBXFlushTime(nvmlDevice_t device, unsigned long long *timestamp, + unsigned long *durationUs); + +/** + * Retrieves the display mode for the device. + * + * For all products. + * + * This method indicates whether a physical display (e.g. monitor) is currently connected to + * any of the device's connectors. + * + * See \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param display Reference in which to return the display mode + * + * @return + * - \ref NVML_SUCCESS if \a display has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a display is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDisplayMode(nvmlDevice_t device, nvmlEnableState_t *display); + +/** + * Retrieves the display active state for the device. + * + * For all products. + * + * This method 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 \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param isActive Reference in which to return the display active state + * + * @return + * - \ref NVML_SUCCESS if \a isActive has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a isActive is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDisplayActive(nvmlDevice_t device, nvmlEnableState_t *isActive); + +/** + * Retrieves 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 \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param mode Reference in which to return the current driver persistence mode + * + * @return + * - \ref NVML_SUCCESS if \a mode has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetPersistenceMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPersistenceMode(nvmlDevice_t device, nvmlEnableState_t *mode); + +/** + * Retrieves PCI attributes of this device. + * + * For all products. + * + * See \ref nvmlPciInfoExt_v1_t for details on the available PCI info. + * + * @param device The identifier of the target device + * @param pci Reference in which to return the PCI info + * + * @return + * - \ref NVML_SUCCESS if \a pci has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pci is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPciInfoExt(nvmlDevice_t device, nvmlPciInfoExt_t *pci); + +/** + * Retrieves the PCI attributes of this device. + * + * For all products. + * + * See \ref nvmlPciInfo_t for details on the available PCI info. + * + * @param device The identifier of the target device + * @param pci Reference in which to return the PCI info + * + * @return + * - \ref NVML_SUCCESS if \a pci has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pci is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPciInfo_v3(nvmlDevice_t device, nvmlPciInfo_t *pci); + +/** + * Retrieves the maximum PCIe link generation possible with this device and system + * + * I.E. for a generation 2 PCIe device attached to a generation 1 PCIe bus the max link generation this function will + * report is generation 1. + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param maxLinkGen Reference in which to return the max PCIe link generation + * + * @return + * - \ref NVML_SUCCESS if \a maxLinkGen has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a maxLinkGen is null + * - \ref NVML_ERROR_NOT_SUPPORTED if PCIe link information is not available + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMaxPcieLinkGeneration(nvmlDevice_t device, unsigned int *maxLinkGen); + +/** + * Retrieves the maximum PCIe link generation supported by this device + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param maxLinkGenDevice Reference in which to return the max PCIe link generation + * + * @return + * - \ref NVML_SUCCESS if \a maxLinkGenDevice has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a maxLinkGenDevice is null + * - \ref NVML_ERROR_NOT_SUPPORTED if PCIe link information is not available + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuMaxPcieLinkGeneration(nvmlDevice_t device, unsigned int *maxLinkGenDevice); + +/** + * Retrieves the maximum PCIe link width possible with this device and system + * + * I.E. for a device with a 16x PCIe bus width attached to a 8x PCIe system bus this function will report + * a max link width of 8. + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param maxLinkWidth Reference in which to return the max PCIe link generation + * + * @return + * - \ref NVML_SUCCESS if \a maxLinkWidth has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a maxLinkWidth is null + * - \ref NVML_ERROR_NOT_SUPPORTED if PCIe link information is not available + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMaxPcieLinkWidth(nvmlDevice_t device, unsigned int *maxLinkWidth); + +/** + * Retrieves the current PCIe link generation + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param currLinkGen Reference in which to return the current PCIe link generation + * + * @return + * - \ref NVML_SUCCESS if \a currLinkGen has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a currLinkGen is null + * - \ref NVML_ERROR_NOT_SUPPORTED if PCIe link information is not available + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCurrPcieLinkGeneration(nvmlDevice_t device, unsigned int *currLinkGen); + +/** + * Retrieves the current PCIe link width + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param currLinkWidth Reference in which to return the current PCIe link generation + * + * @return + * - \ref NVML_SUCCESS if \a currLinkWidth has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a currLinkWidth is null + * - \ref NVML_ERROR_NOT_SUPPORTED if PCIe link information is not available + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCurrPcieLinkWidth(nvmlDevice_t device, unsigned int *currLinkWidth); + +/** + * Retrieve PCIe utilization information. + * This function is querying a byte counter over a 20ms interval and thus is the + * PCIe throughput over that interval. + * + * For Maxwell &tm; or newer fully supported devices. + * + * This method is not supported in virtual machines running virtual GPU (vGPU). + * + * @param device The identifier of the target device + * @param counter The specific counter that should be queried \ref nvmlPcieUtilCounter_t + * @param value Reference in which to return throughput in KB/s + * + * @return + * - \ref NVML_SUCCESS if \a value has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a counter is invalid, or \a value is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPcieThroughput(nvmlDevice_t device, nvmlPcieUtilCounter_t counter, unsigned int *value); + +/** + * Retrieve the PCIe replay counter. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param value Reference in which to return the counter's value + * + * @return + * - \ref NVML_SUCCESS if \a value has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a value is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPcieReplayCounter(nvmlDevice_t device, unsigned int *value); + +/** + * Retrieves the current clock speeds for the device. + * + * For Fermi &tm; or newer fully supported devices. + * + * See \ref nvmlClockType_t for details on available clock information. + * + * @param device The identifier of the target device + * @param type Identify which clock domain to query + * @param clock Reference in which to return the clock speed in MHz + * + * @return + * - \ref NVML_SUCCESS if \a clock has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clock is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device cannot report the specified clock + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetClockInfo(nvmlDevice_t device, nvmlClockType_t type, unsigned int *clock); + +/** + * Retrieves the maximum clock speeds for the device. + * + * For Fermi &tm; or newer fully supported devices. + * + * See \ref nvmlClockType_t for details on available clock information. + * + * \note On GPUs from Fermi family current P0 clocks (reported by \ref nvmlDeviceGetClockInfo) can differ from max clocks + * by few MHz. + * + * @param device The identifier of the target device + * @param type Identify which clock domain to query + * @param clock Reference in which to return the clock speed in MHz + * + * @return + * - \ref NVML_SUCCESS if \a clock has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clock is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device cannot report the specified clock + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMaxClockInfo(nvmlDevice_t device, nvmlClockType_t type, unsigned int *clock); + +/** + * Retrieve the GPCCLK VF offset value + * @param[in] device The identifier of the target device + * @param[out] offset The retrieved GPCCLK VF offset value + * + * @return + * - \ref NVML_SUCCESS if \a offset has been successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpcClkVfOffset(nvmlDevice_t device, int *offset); + +/** + * @deprecated Applications clocks are deprecated and will be removed in CUDA 14.0. + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetApplicationsClock(nvmlDevice_t device, nvmlClockType_t clockType, unsigned int *clockMHz); + +/** + * @deprecated Applications clocks are deprecated and will be removed in CUDA 14.0. + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetDefaultApplicationsClock(nvmlDevice_t device, nvmlClockType_t clockType, unsigned int *clockMHz); + +/** + * Retrieves the clock speed for the clock specified by the clock type and clock ID. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param clockType Identify which clock domain to query + * @param clockId Identify which clock in the domain to query + * @param clockMHz Reference in which to return the clock in MHz + * + * @return + * - \ref NVML_SUCCESS if \a clockMHz has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clockMHz is NULL or \a clockType is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetClock(nvmlDevice_t device, nvmlClockType_t clockType, nvmlClockId_t clockId, unsigned int *clockMHz); + +/** + * Retrieves the customer defined maximum boost clock speed specified by the given clock type. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param clockType Identify which clock domain to query + * @param clockMHz Reference in which to return the clock in MHz + * + * @return + * - \ref NVML_SUCCESS if \a clockMHz has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clockMHz is NULL or \a clockType is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device or the \a clockType on this device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMaxCustomerBoostClock(nvmlDevice_t device, nvmlClockType_t clockType, unsigned int *clockMHz); + +/** + * Retrieves the list of possible memory clocks that can be used as an argument for \ref nvmlDeviceSetMemoryLockedClocks. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param count Reference in which to provide the \a clocksMHz array size, and + * to return the number of elements + * @param clocksMHz Reference in which to return the clock in MHz + * + * @return + * - \ref NVML_SUCCESS if \a count and \a clocksMHz have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a count is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a count is too small (\a count is set to the number of + * required elements) + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetMemoryLockedClocks + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedMemoryClocks(nvmlDevice_t device, unsigned int *count, unsigned int *clocksMHz); + +/** + * Retrieves the list of possible graphics clocks that can be used as an argument for \ref nvmlDeviceSetGpuLockedClocks. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param memoryClockMHz Memory clock for which to return possible graphics clocks + * @param count Reference in which to provide the \a clocksMHz array size, and + * to return the number of elements + * @param clocksMHz Reference in which to return the clocks in MHz + * + * @return + * - \ref NVML_SUCCESS if \a count and \a clocksMHz have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NOT_FOUND if the specified \a memoryClockMHz is not a supported frequency + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clock is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a count is too small + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetGpuLockedClocks + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedGraphicsClocks(nvmlDevice_t device, unsigned int memoryClockMHz, unsigned int *count, unsigned int *clocksMHz); + +/** + * Retrieve the current state of Auto Boosted clocks on a device and store it in \a isEnabled + * + * For Kepler &tm; 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 Aoosted clocks are controlled through application clocks. + * Use \ref nvmlDeviceSetApplicationsClocks and \ref nvmlDeviceResetApplicationsClocks to control Auto Boost + * behavior. + * + * @param device The identifier of the target device + * @param isEnabled Where to store the current state of Auto Boosted clocks of the target device + * @param defaultIsEnabled Where to store the default Auto Boosted clocks behavior of the target device that the device will + * revert to when no applications are using the GPU + * + * @return + * - \ref NVML_SUCCESS If \a isEnabled has been been set with the Auto Boosted clocks state of \a device + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a isEnabled is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support Auto Boosted clocks + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAutoBoostedClocksEnabled(nvmlDevice_t device, nvmlEnableState_t *isEnabled, nvmlEnableState_t *defaultIsEnabled); + +/** + * Retrieves the intended operating speed of the device's fan. + * + * Note: The reported speed is the intended fan speed. If the fan is physically blocked and unable to spin, the + * output will 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. + * + * @param device The identifier of the target device + * @param speed Reference in which to return the fan speed percentage + * + * @return + * - \ref NVML_SUCCESS if \a speed has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a speed is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a fan + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetFanSpeed(nvmlDevice_t device, unsigned int *speed); + +/** + * Retrieves the intended operating speed of the device's specified fan. + * + * Note: The reported speed is the intended fan speed. If the fan is physically blocked and unable to spin, the + * output will 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. + * + * @param device The identifier of the target device + * @param fan The index of the target fan, zero indexed. + * @param speed Reference in which to return the fan speed percentage + * + * @return + * - \ref NVML_SUCCESS if \a speed has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a fan is not an acceptable index, or \a speed is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a fan or is newer than Maxwell + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetFanSpeed_v2(nvmlDevice_t device, unsigned int fan, unsigned int * speed); + +/** + * Retrieves the intended operating speed in rotations per minute (RPM) of the device's specified fan. + * + * For Maxwell &tm; or newer fully supported devices. + * + * For all discrete products with dedicated fans. + * + * Note: The reported speed is the intended fan speed. If the fan is physically blocked and unable to spin, the + * output will not match the actual fan speed. + * + * @param device The identifier of the target device + * @param fanSpeed Structure specifying the index of the target fan (input) and + * retrieved fan speed value (output) + * + * @return + * - \ref NVML_SUCCESS If everything worked + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, \a fan is not an acceptable + * index, or \a speed is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED If the \a device does not support this feature + */ +nvmlReturn_t DECLDIR nvmlDeviceGetFanSpeedRPM(nvmlDevice_t device, nvmlFanSpeedInfo_t *fanSpeed); + +/** + * Retrieves the intended target speed of the device's specified fan. + * + * Normally, the driver dynamically adjusts the fan based on + * the needs of the GPU. But when user set fan speed using nvmlDeviceSetFanSpeed_v2, + * the driver will attempt to make the fan achieve the setting in + * nvmlDeviceSetFanSpeed_v2. The actual current speed of the fan + * is reported in nvmlDeviceGetFanSpeed_v2. + * + * 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. + * + * @param device The identifier of the target device + * @param fan The index of the target fan, zero indexed. + * @param targetSpeed Reference in which to return the fan speed percentage + * + * @return + * - \ref NVML_SUCCESS if \a speed has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a fan is not an acceptable index, or \a speed is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a fan or is newer than Maxwell + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTargetFanSpeed(nvmlDevice_t device, unsigned int fan, unsigned int *targetSpeed); + +/** + * Retrieves the min and max fan speed that user can set for the GPU fan. + * + * For all cuda-capable discrete products with fans + * + * @param device The identifier of the target device + * @param minSpeed The minimum speed allowed to set + * @param maxSpeed The maximum speed allowed to set + * + * return + * NVML_SUCCESS if speed has been adjusted + * NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * NVML_ERROR_INVALID_ARGUMENT if device is invalid + * NVML_ERROR_NOT_SUPPORTED if the device does not support this + * (doesn't have fans) + * NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMinMaxFanSpeed(nvmlDevice_t device, unsigned int * minSpeed, + unsigned int * maxSpeed); + +/** + * Gets current fan control policy. + * + * For Maxwell &tm; or newer fully supported devices. + * + * For all cuda-capable discrete products with fans + * + * device The identifier of the target \a device + * policy Reference in which to return the fan control \a policy + * + * return + * NVML_SUCCESS if \a policy has been populated + * NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a policy is null or the \a fan given doesn't reference + * a fan that exists. + * NVML_ERROR_NOT_SUPPORTED if the \a device is older than Maxwell + * NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetFanControlPolicy_v2(nvmlDevice_t device, unsigned int fan, + nvmlFanControlPolicy_t *policy); + +/** + * Retrieves the number of fans on the device. + * + * For all discrete products with dedicated fans. + * + * @param device The identifier of the target device + * @param numFans The number of fans + * + * @return + * - \ref NVML_SUCCESS if \a fan number query was successful + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a numFans is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a fan + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNumFans(nvmlDevice_t device, unsigned int *numFans); + +/** + * @deprecated Use \ref nvmlDeviceGetTemperatureV instead + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetTemperature(nvmlDevice_t device, nvmlTemperatureSensors_t sensorType, unsigned int *temp); + +/** + * Retrieves the cooler's information. + * Returns a cooler's control signal characteristics. The possible types are restricted, Variable and Toggle. + * See \ref nvmlCoolerControl_t for details on available signal types. + * Returns objects that cooler cools. Targets may be GPU, Memory, Power Supply or All of these. + * See \ref nvmlCoolerTarget_t for details on available targets. + * + * For Maxwell &tm; or newer fully supported devices. + * + * For all discrete products with dedicated fans. + * + * @param[in] device The identifier of the target device + * @param[out] coolerInfo Structure specifying the cooler's control signal characteristics (out) + * and the target that cooler cools (out) + * + * @return + * - \ref NVML_SUCCESS If everything worked + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, \a signalType or \a target is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED If the \a device does not support this feature + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCoolerInfo(nvmlDevice_t device, nvmlCoolerInfo_t *coolerInfo); + +/** + * Structure used to encapsulate temperature info + */ +typedef struct +{ + unsigned int version; + nvmlTemperatureSensors_t sensorType; + int temperature; +} nvmlTemperature_v1_t; + +typedef nvmlTemperature_v1_t nvmlTemperature_t; + +#define nvmlTemperature_v1 NVML_STRUCT_VERSION(Temperature, 1) + +/** + * Retrieves the current temperature readings (in degrees C) for the given device. + * + * For all products. + * + * @param[in] device Target device identifier. + * @param[in,out] temperature Structure specifying the sensor type (input) and retrieved + * temperature value (output). + * + * @return + * - \ref NVML_SUCCESS if \a temp has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a sensorType is invalid or \a temp is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have the specified sensor + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTemperatureV(nvmlDevice_t device, nvmlTemperature_t *temperature); + + +/** + * Retrieves the temperature threshold for the GPU with the specified threshold type in degrees C. + * + * For Kepler &tm; or newer fully supported devices. + * + * See \ref nvmlTemperatureThresholds_t for details on available temperature thresholds. + * + * Note: This API is no longer the preferred interface for retrieving the following temperature thresholds + * on Ada and later architectures: NVML_TEMPERATURE_THRESHOLD_SHUTDOWN, NVML_TEMPERATURE_THRESHOLD_SLOWDOWN, + * NVML_TEMPERATURE_THRESHOLD_MEM_MAX and NVML_TEMPERATURE_THRESHOLD_GPU_MAX. + * + * Support for reading these temperature thresholds for Ada and later architectures would be removed from this + * API in future releases. Please use \ref nvmlDeviceGetFieldValues with NVML_FI_DEV_TEMPERATURE_* fields to retrieve + * temperature thresholds on these architectures. + * + * @param device The identifier of the target device + * @param thresholdType The type of threshold value queried + * @param temp Reference in which to return the temperature reading + * @return + * - \ref NVML_SUCCESS if \a temp has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a thresholdType is invalid or \a temp is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a temperature sensor or is unsupported + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTemperatureThreshold(nvmlDevice_t device, nvmlTemperatureThresholds_t thresholdType, unsigned int *temp); + +/** + * Retrieves the thermal margin temperature (distance to nearest slowdown threshold). + * + * @param[in] device The identifier of the target device + * @param[in,out] marginTempInfo Versioned structure in which to return the temperature reading + * + * @returns + * - \ref NVML_SUCCESS if the margin temperature was retrieved successfully + * - \ref NVML_ERROR_NOT_SUPPORTED if request is not supported on the current platform + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a temperature is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the right versioned structure is not used + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMarginTemperature(nvmlDevice_t device, nvmlMarginTemperature_t *marginTempInfo); + +/** + * Used to execute a list of thermal system instructions. + * + * @param device The identifier of the target device + * @param sensorIndex The index of the thermal sensor + * @param pThermalSettings Reference in which to return the thermal sensor information + * + * @return + * - \ref NVML_SUCCESS if \a pThermalSettings has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pThermalSettings is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetThermalSettings(nvmlDevice_t device, unsigned int sensorIndex, nvmlGpuThermalSettings_t *pThermalSettings); + +/** + * Retrieves the current performance state for the device. + * + * For Fermi &tm; or newer fully supported devices. + * + * See \ref nvmlPstates_t for details on allowed performance states. + * + * @param device The identifier of the target device + * @param pState Reference in which to return the performance state reading + * + * @return + * - \ref NVML_SUCCESS if \a pState has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pState is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPerformanceState(nvmlDevice_t device, nvmlPstates_t *pState); + +/** + * Retrieves current clocks event reasons. + * + * For all fully supported products. + * + * \note More than one bit can be enabled at the same time. Multiple reasons can be affecting clocks at once. + * + * @param device The identifier of the target device + * @param clocksEventReasons Reference in which to return bitmask of active clocks event + * reasons + * + * @return + * - \ref NVML_SUCCESS if \a clocksEventReasons has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a clocksEventReasons is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlClocksEventReasons + * @see nvmlDeviceGetSupportedClocksEventReasons + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCurrentClocksEventReasons(nvmlDevice_t device, unsigned long long *clocksEventReasons); + +/** + * @deprecated Use \ref nvmlDeviceGetCurrentClocksEventReasons instead + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetCurrentClocksThrottleReasons(nvmlDevice_t device, unsigned long long *clocksThrottleReasons); + +/** + * Retrieves bitmask of supported clocks event reasons that can be returned by + * \ref nvmlDeviceGetCurrentClocksEventReasons + * + * For all fully supported products. + * + * This method is not supported in virtual machines running virtual GPU (vGPU). + * + * @param device The identifier of the target device + * @param supportedClocksEventReasons Reference in which to return bitmask of supported + * clocks event reasons + * + * @return + * - \ref NVML_SUCCESS if \a supportedClocksEventReasons has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a supportedClocksEventReasons is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlClocksEventReasons + * @see nvmlDeviceGetCurrentClocksEventReasons + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedClocksEventReasons(nvmlDevice_t device, unsigned long long *supportedClocksEventReasons); + +/** + * @deprecated Use \ref nvmlDeviceGetSupportedClocksEventReasons instead + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetSupportedClocksThrottleReasons(nvmlDevice_t device, unsigned long long *supportedClocksThrottleReasons); + +/** + * @deprecated Use \ref nvmlDeviceGetPerformanceState. This function exposes an incorrect generalization. + * + * Retrieve the current performance state for the device. + * + * For Fermi &tm; or newer fully supported devices. + * + * See \ref nvmlPstates_t for details on allowed performance states. + * + * @param device The identifier of the target device + * @param pState Reference in which to return the performance state reading + * + * @return + * - \ref NVML_SUCCESS if \a pState has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pState is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetPowerState(nvmlDevice_t device, nvmlPstates_t *pState); + +/** + * Retrieve performance monitor samples from the associated subdevice. + * + * @param device + * @param pDynamicPstatesInfo + * + * @return + * - \ref NVML_SUCCESS if \a pDynamicPstatesInfo has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pDynamicPstatesInfo is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDynamicPstatesInfo(nvmlDevice_t device, nvmlGpuDynamicPstatesInfo_t *pDynamicPstatesInfo); + +/** + * Retrieve the MemClk (Memory Clock) VF offset value. + * @param[in] device The identifier of the target device + * @param[out] offset The retrieved MemClk VF offset value + * + * @return + * - \ref NVML_SUCCESS if \a offset has been successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemClkVfOffset(nvmlDevice_t device, int *offset); + +/** + * Retrieve min and max clocks of some clock domain for a given PState + * + * @param device The identifier of the target device + * @param type Clock domain + * @param pstate PState to query + * @param minClockMHz Reference in which to return min clock frequency + * @param maxClockMHz Reference in which to return max clock frequency + * + * @return + * - \ref NVML_SUCCESS if everything worked + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a type or \a pstate are invalid or both + * \a minClockMHz and \a maxClockMHz are NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMinMaxClockOfPState(nvmlDevice_t device, nvmlClockType_t type, nvmlPstates_t pstate, + unsigned int * minClockMHz, unsigned int * maxClockMHz); + +/** + * Get all supported Performance States (P-States) for the device. + * + * The returned array would contain a contiguous list of valid P-States supported by + * the device. If the number of supported P-States is fewer than the size of the array + * supplied missing elements would contain \a NVML_PSTATE_UNKNOWN. + * + * The number of elements in the returned list will never exceed \a NVML_MAX_GPU_PERF_PSTATES. + * + * @param device The identifier of the target device + * @param pstates Container to return the list of performance states + * supported by device + * @param size Size of the supplied \a pstates array in bytes + * + * @return + * - \ref NVML_SUCCESS if \a pstates array has been retrieved + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if the the container supplied was not large enough to + * hold the resulting list + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a pstates is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support performance state readings + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedPerformanceStates(nvmlDevice_t device, + nvmlPstates_t *pstates, unsigned int size); + +/** + * Retrieve the GPCCLK min max VF offset value. + * @param[in] device The identifier of the target device + * @param[out] minOffset The retrieved GPCCLK VF min offset value + * @param[out] maxOffset The retrieved GPCCLK VF max offset value + * + * @return + * - \ref NVML_SUCCESS if \a offset has been successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpcClkMinMaxVfOffset(nvmlDevice_t device, + int *minOffset, int *maxOffset); + +/** + * Retrieve the MemClk (Memory Clock) min max VF offset value. + * @param[in] device The identifier of the target device + * @param[out] minOffset The retrieved MemClk VF min offset value + * @param[out] maxOffset The retrieved MemClk VF max offset value + * + * @return + * - \ref NVML_SUCCESS if \a offset has been successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemClkMinMaxVfOffset(nvmlDevice_t device, + int *minOffset, int *maxOffset); + +/** + * Retrieve min, max and current clock offset of some clock domain for a given PState + * + * For Maxwell &tm; or newer fully supported devices. + * + * Note: \ref nvmlDeviceGetGpcClkVfOffset, \ref nvmlDeviceGetMemClkVfOffset, \ref nvmlDeviceGetGpcClkMinMaxVfOffset and + * \ref nvmlDeviceGetMemClkMinMaxVfOffset will be deprecated in a future release. + Use \ref nvmlDeviceGetClockOffsets instead. + * + * @param device The identifier of the target device + * @param info Structure specifying the clock type (input) and the pstate (input) + * retrieved clock offset value (output), min clock offset (output) + * and max clock offset (output) + * + * @return + * - \ref NVML_SUCCESS If everything worked + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a type or \a pstate are invalid or both + * \a minClockOffsetMHz and \a maxClockOffsetMHz are NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + */ +nvmlReturn_t DECLDIR nvmlDeviceGetClockOffsets(nvmlDevice_t device, nvmlClockOffset_t *info); + +/** + * Control current clock offset of some clock domain for a given PState + * + * For Maxwell &tm; or newer fully supported devices. + * + * Requires privileged user. + * + * @param device The identifier of the target device + * @param info Structure specifying the clock type (input), the pstate (input) + * and clock offset value (input) + * + * @return + * - \ref NVML_SUCCESS If everything worked + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_NO_PERMISSION If the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a type or \a pstate are invalid or both + * \a clockOffsetMHz is out of allowed range. + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + */ +nvmlReturn_t DECLDIR nvmlDeviceSetClockOffsets(nvmlDevice_t device, nvmlClockOffset_t *info); + +/** + * Retrieves 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 will be reported on all GPUs, and additional tokens + * may be added in the future. + * For backwards compatibility we still provide nvclock and memclock; + * those are the same as nvclockmin and memclockmin. + * + * Note: These clock values take into account the offset + * set by clients through /ref nvmlDeviceSetClockOffsets. + * + * Maximum available Pstate (P15) shows the minimum performance level (0) and vice versa. + * + * Each performance modes are returned as a comma-separated list of + * "token=value" pairs. Each set of performance mode tokens are separated + * by a ";". Valid tokens: + * + * Token Value + * "perf" unsigned int - the Performance level + * "nvclock" unsigned int - the GPU clocks (in MHz) for the perf level + * "nvclockmin" unsigned int - the GPU clocks min (in MHz) for the perf level + * "nvclockmax" unsigned int - the GPU clocks max (in MHz) for the perf level + * "nvclockeditable" unsigned int - if the GPU clock domain is editable for the perf level + * "memclock" unsigned int - the memory clocks (in MHz) for the perf level + * "memclockmin" unsigned int - the memory clocks min (in MHz) for the perf level + * "memclockmax" unsigned int - the memory clocks max (in MHz) for the perf level + * "memclockeditable" unsigned int - if the memory clock domain is editable for the perf level + * "memtransferrate" unsigned int - the memory transfer rate (in MHz) for the perf level + * "memtransferratemin" unsigned int - the memory transfer rate min (in MHz) for the perf level + * "memtransferratemax" unsigned int - the memory transfer rate max (in MHz) for the perf level + * "memtransferrateeditable" unsigned int - if the memory transfer rate is editable for the perf 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 ; + * + * + * @param device The identifier of the target device + * @param perfModes Reference in which to return the performance level string + * + * @return + * - \ref NVML_SUCCESS if \a perfModes has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a name is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPerformanceModes(nvmlDevice_t device, nvmlDevicePerfModes_t *perfModes); + +/** + * Retrieves a string with the associated current GPU Clock and Memory Clock values. + * + * Not all tokens will be reported on all GPUs, and additional tokens + * may be added in the future. + * + * Note: These clock values take into account the offset + * set by clients through /ref nvmlDeviceSetClockOffsets. + * + * Clock values are returned as a comma-separated list of + * "token=value" pairs. + * Valid tokens: + * + * Token Value + * "perf" unsigned int - the Performance level + * "nvclock" unsigned int - the GPU clocks (in MHz) for the perf level + * "nvclockmin" unsigned int - the GPU clocks min (in MHz) for the perf level + * "nvclockmax" unsigned int - the GPU clocks max (in MHz) for the perf level + * "nvclockeditable" unsigned int - if the GPU clock domain is editable for the perf level + * "memclock" unsigned int - the memory clocks (in MHz) for the perf level + * "memclockmin" unsigned int - the memory clocks min (in MHz) for the perf level + * "memclockmax" unsigned int - the memory clocks max (in MHz) for the perf level + * "memclockeditable" unsigned int - if the memory clock domain is editable for the perf level + * "memtransferrate" unsigned int - the memory transfer rate (in MHz) for the perf level + * "memtransferratemin" unsigned int - the memory transfer rate min (in MHz) for the perf level + * "memtransferratemax" unsigned int - the memory transfer rate max (in MHz) for the perf level + * "memtransferrateeditable" unsigned int - if the memory transfer rate is editable for the perf 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 ; + * + * + * @param device The identifier of the target device + * @param currentClockFreqs Reference in which to return the performance level string + * + * @return + * - \ref NVML_SUCCESS if \a currentClockFreqs has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a name is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCurrentClockFreqs(nvmlDevice_t device, nvmlDeviceCurrentClockFreqs_t *currentClockFreqs); + +/** + * @deprecated This API has been deprecated. + * + * Retrieves the power management mode associated with this device. + * + * For products from the Fermi family. + * - Requires \a NVML_INFOROM_POWER version 3.0 or higher. + * + * For from the Kepler or newer families. + * - Does not require \a NVML_INFOROM_POWER object. + * + * This flag indicates whether any power management algorithm is currently active on the device. An + * enabled state does not necessarily mean the device is being actively throttled -- only that + * that the driver will do so if the appropriate conditions are met. + * + * See \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param mode Reference in which to return the current power management mode + * + * @return + * - \ref NVML_SUCCESS if \a mode has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetPowerManagementMode(nvmlDevice_t device, nvmlEnableState_t *mode); + +/** + * Retrieves the power management limit associated with this device. + * + * For Fermi &tm; 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 \ref nvmlDeviceGetPowerManagementMode. + * + * @param device The identifier of the target device + * @param limit Reference in which to return the power management limit in milliwatts + * + * @return + * - \ref NVML_SUCCESS if \a limit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a limit is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPowerManagementLimit(nvmlDevice_t device, unsigned int *limit); + +/** + * Retrieves information about possible values of power management limits on this device. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param minLimit Reference in which to return the minimum power management limit in milliwatts + * @param maxLimit Reference in which to return the maximum power management limit in milliwatts + * + * @return + * - \ref NVML_SUCCESS if \a minLimit and \a maxLimit have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a minLimit or \a maxLimit is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetPowerManagementLimit + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPowerManagementLimitConstraints(nvmlDevice_t device, unsigned int *minLimit, unsigned int *maxLimit); + +/** + * Retrieves 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 &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param defaultLimit Reference in which to return the default power management limit in milliwatts + * + * @return + * - \ref NVML_SUCCESS if \a defaultLimit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a defaultLimit is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPowerManagementDefaultLimit(nvmlDevice_t device, unsigned int *defaultLimit); + +/** + * Retrieves power usage for this GPU in milliwatts and its associated circuitry (e.g. memory) + * + * For Fermi &tm; 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, the API returns power averaged over 1 sec interval. On GA100 and + * older architectures, instantaneous power is returned. + * + * See \ref NVML_FI_DEV_POWER_AVERAGE and \ref NVML_FI_DEV_POWER_INSTANT to query specific power + * values. + * + * It is only available if power management mode is supported. See \ref nvmlDeviceGetPowerManagementMode. + * + * @param device The identifier of the target device + * @param power Reference in which to return the power usage information + * + * @return + * - \ref NVML_SUCCESS if \a power has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a power is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support power readings + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPowerUsage(nvmlDevice_t device, unsigned int *power); + +/** + * Retrieves 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 &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param powerMizerMode Reference in which to return the power mizer mode + * @param supportedPowerMizerModes Reference in which to return the bitmask of supported power mizer modes on this device. + * The supported modes can be combined using the bitwise OR operator '|'. + * For example, if a device supports all PowerMizer modes, the bitmask would be: + * supportedPowerMizerModes = ((1 << NVML_POWER_MIZER_MODE_ADAPTIVE) | + * (1 << NVML_POWER_MIZER_MODE_PREFER_MAXIMUM_PERFORMANCE) | + * (1 << NVML_POWER_MIZER_MODE_AUTO) | + * (1 << NVML_POWER_MIZER_MODE_PREFER_CONSISTENT_PERFORMANCE)); + * This bitmask can be used to check which power mizer modes are available on the device by performing + * a bitwise AND operation with the specific mode you want to check. + * + * @return + * - \ref NVML_SUCCESS if \a powerMizerMode has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a powerMizerMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support powerMizerMode readings + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ + +nvmlReturn_t DECLDIR nvmlDeviceGetPowerMizerMode_v1(nvmlDevice_t device, nvmlDevicePowerMizerModes_v1_t *powerMizerMode); + +/** + * Sets the new power mizer mode. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param powerMizerMode Reference in which to set the power mizer mode. + * + * @return + * - \ref NVML_SUCCESS if \a powerMizerMode has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a powerMizerMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support powerMizerMode readings + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ + +nvmlReturn_t DECLDIR nvmlDeviceSetPowerMizerMode_v1(nvmlDevice_t device, nvmlDevicePowerMizerModes_v1_t *powerMizerMode); + + +/** + * Retrieves total energy consumption for this GPU in millijoules (mJ) since the driver was last reloaded + * + * For Volta &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param energy Reference in which to return the energy consumption information + * + * @return + * - \ref NVML_SUCCESS if \a energy has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a energy is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support energy readings + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTotalEnergyConsumption(nvmlDevice_t device, unsigned long long *energy); + +/** + * Get the effective power limit that the driver enforces after taking into account all limiters + * + * Note: This can be different from the \ref nvmlDeviceGetPowerManagementLimit if other limits are set elsewhere + * This includes the out of band power limit interface + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The device to communicate with + * @param limit Reference in which to return the power management limit in milliwatts + * + * @return + * - \ref NVML_SUCCESS if \a limit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a limit is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEnforcedPowerLimit(nvmlDevice_t device, unsigned int *limit); + +/** + * Retrieves the current GOM and pending GOM (the one that GPU will switch to after reboot). + * + * For GK110 M-class and X-class Tesla &tm; products from the Kepler family. + * Modes \ref NVML_GOM_LOW_DP and \ref NVML_GOM_ALL_ON are supported on fully supported GeForce products. + * Not supported on Quadro ® and Tesla &tm; C-class products. + * + * @param device The identifier of the target device + * @param current Reference in which to return the current GOM + * @param pending Reference in which to return the pending GOM + * + * @return + * - \ref NVML_SUCCESS if \a mode has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a current or \a pending is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlGpuOperationMode_t + * @see nvmlDeviceSetGpuOperationMode + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuOperationMode(nvmlDevice_t device, nvmlGpuOperationMode_t *current, nvmlGpuOperationMode_t *pending); + +/** + * Retrieves the amount of used, free, reserved and total memory available on the device, in bytes. + * The reserved amount is supported on version 2 only. + * + * For all products. + * + * Enabling ECC reduces the amount of total available memory, due to the extra required parity bits. + * Under WDDM most device memory is allocated and managed on startup by Windows. + * + * Under Linux and Windows TCC, the reported amount of used memory is equal to the sum of memory allocated + * by all active channels on the device. + * + * See \ref nvmlMemory_v2_t for details on available memory info. + * + * @note In MIG mode, if device handle is provided, the API returns aggregate + * information, only if the caller has appropriate privileges. Per-instance + * information can be queried by using specific MIG device handles. + * + * @note nvmlDeviceGetMemoryInfo_v2 adds additional memory information. + * + * @note On systems where GPUs are NUMA nodes, the accuracy of FB memory utilization + * provided by this API depends on the memory accounting of the operating system. + * This is because FB memory is managed by the operating system instead of the NVIDIA GPU driver. + * Typically, pages allocated from FB memory are not released even after + * the process terminates to enhance performance. In scenarios where + * the operating system is under memory pressure, it may resort to utilizing FB memory. + * Such actions can result in discrepancies in the accuracy of memory reporting. + * + * @param device The identifier of the target device + * @param memory Reference in which to return the memory information + * + * @return + * - \ref NVML_SUCCESS if \a memory has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemoryInfo(nvmlDevice_t device, nvmlMemory_t *memory); + +/** + * nvmlDeviceGetMemoryInfo_v2 accounts separately for reserved memory and includes it in the used memory amount. + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemoryInfo_v2(nvmlDevice_t device, nvmlMemory_v2_t *memory); + +/** + * Retrieves the current compute mode for the device. + * + * For all products. + * + * See \ref nvmlComputeMode_t for details on allowed compute modes. + * + * @param device The identifier of the target device + * @param mode Reference in which to return the current compute mode + * + * @return + * - \ref NVML_SUCCESS if \a mode has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetComputeMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetComputeMode(nvmlDevice_t device, nvmlComputeMode_t *mode); + +/** + * Retrieves 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 that would be + * returned by CUDA's cuDeviceGetAttribute(). + * + * @param device The identifier of the target device + * @param major Reference in which to return the major CUDA compute capability + * @param minor Reference in which to return the minor CUDA compute capability + * + * @return + * - \ref NVML_SUCCESS if \a major and \a minor have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a major or \a minor are NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCudaComputeCapability(nvmlDevice_t device, int *major, int *minor); + +/** + * Retrieves the current and pending DRAM Encryption modes for the device. + * + * %BLACKWELL_OR_NEWER% + * Only applicable to devices that support DRAM Encryption + * Requires \a NVML_INFOROM_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 \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param current Reference in which to return the current DRAM Encryption mode + * @param pending Reference in which to return the pending DRAM Encryption mode + * + * @return + * - \ref NVML_SUCCESS if \a current and \a pending have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or either \a current or \a pending is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the argument version is not supported + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetDramEncryptionMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDramEncryptionMode(nvmlDevice_t device, nvmlDramEncryptionInfo_t *current, nvmlDramEncryptionInfo_t *pending); + +/** + * Set the DRAM Encryption mode for the device. + * + * For Kepler &tm; or newer fully supported devices. + * Only applicable to devices that support DRAM Encryption. + * Requires \a NVML_INFOROM_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 \ref nvmlEnableState_t for details on available modes. + * + * @param device The identifier of the target device + * @param dramEncryption The target DRAM Encryption mode + * + * @return + * - \ref NVML_SUCCESS if the DRAM Encryption mode was set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a DRAM Encryption is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the argument version is not supported + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetDramEncryptionMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceSetDramEncryptionMode(nvmlDevice_t device, const nvmlDramEncryptionInfo_t *dramEncryption); + +/** + * Retrieves the current and pending ECC modes for the device. + * + * For Fermi &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_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 \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param current Reference in which to return the current ECC mode + * @param pending Reference in which to return the pending ECC mode + * + * @return + * - \ref NVML_SUCCESS if \a current and \a pending have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or either \a current or \a pending is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetEccMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEccMode(nvmlDevice_t device, nvmlEnableState_t *current, nvmlEnableState_t *pending); + +/** + * Retrieves the default ECC modes for the device. + * + * For Fermi &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_ECC version 1.0 or higher. + * + * See \ref nvmlEnableState_t for details on allowed modes. + * + * @param device The identifier of the target device + * @param defaultMode Reference in which to return the default ECC mode + * + * @return + * - \ref NVML_SUCCESS if \a current and \a pending have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a default is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetEccMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDefaultEccMode(nvmlDevice_t device, nvmlEnableState_t *defaultMode); + +/** + * Retrieves the device boardId from 0-N. + * Devices with the same boardId indicate GPUs connected to the same PLX. Use in conjunction with + * \ref nvmlDeviceGetMultiGpuBoard() to decide if they are on the same board as well. + * The boardId returned is a unique ID for the current configuration. Uniqueness and ordering across + * reboots and system configurations is not guaranteed (i.e. if a Tesla K40c returns 0x100 and + * the two GPUs on a Tesla K10 in the same system returns 0x200 it is not guaranteed they will + * always return those values but they will always be different from each other). + * + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param boardId Reference in which to return the device's board ID + * + * @return + * - \ref NVML_SUCCESS if \a boardId has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a boardId is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBoardId(nvmlDevice_t device, unsigned int *boardId); + +/** + * Retrieves whether the device is on a Multi-GPU Board + * Devices that are on multi-GPU boards will set \a multiGpuBool to a non-zero value. + * + * For Fermi &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param multiGpuBool Reference in which to return a zero or non-zero value + * to indicate whether the device is on a multi GPU board + * + * @return + * - \ref NVML_SUCCESS if \a multiGpuBool has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a multiGpuBool is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMultiGpuBoard(nvmlDevice_t device, unsigned int *multiGpuBool); + +/** + * Retrieves the total ECC error counts for the device. + * + * For Fermi &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_ECC version 1.0 or higher. + * Requires ECC Mode to be enabled. + * + * The total error count is the sum of errors across each of the separate memory systems, i.e. the total set of + * errors across the entire device. + * + * See \ref nvmlMemoryErrorType_t for a description of available error types.\n + * See \ref nvmlEccCounterType_t for a description of available counter types. + * + * @param device The identifier of the target device + * @param errorType Flag that specifies the type of the errors. + * @param counterType Flag that specifies the counter-type of the errors. + * @param eccCounts Reference in which to return the specified ECC errors + * + * @return + * - \ref NVML_SUCCESS if \a eccCounts has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a errorType or \a counterType is invalid, or \a eccCounts is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceClearEccErrorCounts() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetTotalEccErrors(nvmlDevice_t device, nvmlMemoryErrorType_t errorType, nvmlEccCounterType_t counterType, unsigned long long *eccCounts); + +/** + * Retrieves the detailed ECC error counts for the device. + * + * @deprecated This API supports only a fixed set of ECC error locations + * On different GPU architectures different locations are supported + * See \ref nvmlDeviceGetMemoryErrorCounter + * + * For Fermi &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_ECC version 2.0 or higher to report aggregate location-based ECC counts. + * Requires \a NVML_INFOROM_ECC version 1.0 or higher to report all other ECC counts. + * Requires ECC Mode to be enabled. + * + * Detailed errors provide separate ECC counts for specific parts of the memory system. + * + * Reports zero for unsupported ECC error counters when a subset of ECC error counters are supported. + * + * See \ref nvmlMemoryErrorType_t for a description of available bit types.\n + * See \ref nvmlEccCounterType_t for a description of available counter types.\n + * See \ref nvmlEccErrorCounts_t for a description of provided detailed ECC counts. + * + * @param device The identifier of the target device + * @param errorType Flag that specifies the type of the errors. + * @param counterType Flag that specifies the counter-type of the errors. + * @param eccCounts Reference in which to return the specified ECC errors + * + * @return + * - \ref NVML_SUCCESS if \a eccCounts has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a errorType or \a counterType is invalid, or \a eccCounts is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceClearEccErrorCounts() + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetDetailedEccErrors(nvmlDevice_t device, nvmlMemoryErrorType_t errorType, nvmlEccCounterType_t counterType, nvmlEccErrorCounts_t *eccCounts); + +/** + * Retrieves the requested memory error counter for the device. + * + * For Fermi &tm; or newer fully supported devices. + * Requires \a NVML_INFOROM_ECC version 2.0 or higher to report aggregate location-based memory error counts. + * Requires \a NVML_INFOROM_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. + * + * @note 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 \ref nvmlMemoryErrorType_t for a description of available memory error types.\n + * See \ref nvmlEccCounterType_t for a description of available counter types.\n + * See \ref nvmlMemoryLocation_t for a description of available counter locations.\n + * + * @param device The identifier of the target device + * @param errorType Flag that specifies the type of error. + * @param counterType Flag that specifies the counter-type of the errors. + * @param locationType Specifies the location of the counter. + * @param count Reference in which to return the ECC counter + * + * @return + * - \ref NVML_SUCCESS if \a count has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a bitTyp,e \a counterType or \a locationType is + * invalid, or \a count is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support ECC error reporting in the specified memory + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemoryErrorCounter(nvmlDevice_t device, nvmlMemoryErrorType_t errorType, + nvmlEccCounterType_t counterType, + nvmlMemoryLocation_t locationType, unsigned long long *count); + +/** + * Retrieves the current utilization rates for the device's major subsystems. + * + * For Fermi &tm; or newer fully supported devices. + * + * See \ref nvmlUtilization_t for details on available utilization rates. + * + * \note During driver initialization when ECC is enabled one can see high GPU and Memory Utilization readings. + * This is caused by ECC Memory Scrubbing mechanism that is performed during driver initialization. + * + * @note On MIG-enabled GPUs, querying device utilization rates is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Reference in which to return the utilization information + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a utilization is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetUtilizationRates(nvmlDevice_t device, nvmlUtilization_t *utilization); + +/** + * Retrieves the current utilization and sampling size in microseconds for the Encoder + * + * For Kepler &tm; or newer fully supported devices. + * + * @note On MIG-enabled GPUs, querying encoder utilization is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Reference to an unsigned int for encoder utilization info + * @param samplingPeriodUs Reference to an unsigned int for the sampling period in US + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a utilization is NULL, or \a samplingPeriodUs is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEncoderUtilization(nvmlDevice_t device, unsigned int *utilization, unsigned int *samplingPeriodUs); + +/** + * Retrieves 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 &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param encoderQueryType Type of encoder to query + * @param encoderCapacity Reference to an unsigned int for the encoder capacity + * + * @return + * - \ref NVML_SUCCESS if \a encoderCapacity is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a encoderCapacity is NULL, or \a device or \a encoderQueryType + * are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if device does not support the encoder specified in \a encodeQueryType + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEncoderCapacity (nvmlDevice_t device, nvmlEncoderType_t encoderQueryType, unsigned int *encoderCapacity); + +/** + * Retrieves the current encoder statistics for a given device. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param sessionCount Reference to an unsigned int for count of active encoder sessions + * @param averageFps Reference to an unsigned int for trailing average FPS of all active sessions + * @param averageLatency Reference to an unsigned int for encode latency in microseconds + * + * @return + * - \ref NVML_SUCCESS if \a sessionCount, \a averageFps and \a averageLatency is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a sessionCount, or \a device or \a averageFps, + * or \a averageLatency is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEncoderStats (nvmlDevice_t device, unsigned int *sessionCount, + unsigned int *averageFps, unsigned int *averageLatency); + +/** + * Retrieves information about active encoder sessions on a target device. + * + * An array of active encoder sessions is returned in the caller-supplied buffer pointed at by \a sessionInfos. The + * array element count is passed in \a sessionCount, and \a sessionCount is used to return the number of sessions + * written to the buffer. + * + * If the supplied buffer is not large enough to accommodate the active session array, the function returns + * NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlEncoderSessionInfo_t array required in \a sessionCount. + * To query the number of active encoder sessions, call this function with *sessionCount = 0. The code will return + * NVML_SUCCESS with number of active encoder sessions updated in *sessionCount. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param sessionCount Reference to caller supplied array size, and returns the number of sessions. + * @param sessionInfos Reference in which to return the session information + * + * @return + * - \ref NVML_SUCCESS if \a sessionInfos is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a sessionCount is too small, array element count is returned in \a sessionCount + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a sessionCount is NULL. + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by \a device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetEncoderSessions(nvmlDevice_t device, unsigned int *sessionCount, nvmlEncoderSessionInfo_t *sessionInfos); + +/** + * Retrieves the current utilization and sampling size in microseconds for the Decoder + * + * For Kepler &tm; or newer fully supported devices. + * + * @note On MIG-enabled GPUs, querying decoder utilization is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Reference to an unsigned int for decoder utilization info + * @param samplingPeriodUs Reference to an unsigned int for the sampling period in US + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a utilization is NULL, or \a samplingPeriodUs is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDecoderUtilization(nvmlDevice_t device, unsigned int *utilization, unsigned int *samplingPeriodUs); + +/** + * Retrieves the current utilization and sampling size in microseconds for the JPG + * + * %TURING_OR_NEWER% + * + * @note On MIG-enabled GPUs, querying decoder utilization is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Reference to an unsigned int for jpg utilization info + * @param samplingPeriodUs Reference to an unsigned int for the sampling period in US + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a utilization is NULL, or \a samplingPeriodUs is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetJpgUtilization(nvmlDevice_t device, unsigned int *utilization, unsigned int *samplingPeriodUs); + +/** + * Retrieves the current utilization and sampling size in microseconds for the OFA (Optical Flow Accelerator) + * + * %TURING_OR_NEWER% + * + * @note On MIG-enabled GPUs, querying decoder utilization is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Reference to an unsigned int for ofa utilization info + * @param samplingPeriodUs Reference to an unsigned int for the sampling period in US + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a utilization is NULL, or \a samplingPeriodUs is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetOfaUtilization(nvmlDevice_t device, unsigned int *utilization, unsigned int *samplingPeriodUs); + +/** +* Retrieves the active frame buffer capture sessions statistics for a given device. +* +* For Maxwell &tm; or newer fully supported devices. +* +* @param device The identifier of the target device +* @param fbcStats Reference to nvmlFBCStats_t structure containing NvFBC stats +* +* @return +* - \ref NVML_SUCCESS if \a fbcStats is fetched +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a fbcStats is NULL +* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlDeviceGetFBCStats(nvmlDevice_t device, nvmlFBCStats_t *fbcStats); + +/** +* Retrieves information about active frame buffer capture sessions on a target device. +* +* An array of active FBC sessions is returned in the caller-supplied buffer pointed at by \a sessionInfo. The +* array element count is passed in \a sessionCount, and \a sessionCount is used to return the number of sessions +* written to the buffer. +* +* If the supplied buffer is not large enough to accommodate the active session array, the function returns +* NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlFBCSessionInfo_t array required in \a sessionCount. +* To query the number of active FBC sessions, call this function with *sessionCount = 0. The code will return +* NVML_SUCCESS with number of active FBC sessions updated in *sessionCount. +* +* For Maxwell &tm; or newer fully supported devices. +* +* @note hResolution, vResolution, averageFPS and averageLatency data for a FBC session returned in \a sessionInfo may +* be zero if there are no new frames captured since the session started. +* +* @param device The identifier of the target device +* @param sessionCount Reference to caller supplied array size, and returns the number of sessions. +* @param sessionInfo Reference in which to return the session information +* +* @return +* - \ref NVML_SUCCESS if \a sessionInfo is fetched +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a sessionCount is too small, array element count is returned in \a sessionCount +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a sessionCount is NULL. +* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlDeviceGetFBCSessions(nvmlDevice_t device, unsigned int *sessionCount, nvmlFBCSessionInfo_t *sessionInfo); + +/** + * Retrieves the current and pending driver model for the device. + * + * For Kepler &tm; 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 \ref nvmlDriverModel_t for details on available driver models. + * + * @param device The identifier of the target device + * @param current Reference in which to return the current driver model + * @param pending Reference in which to return the pending driver model + * + * @return + * - \ref NVML_SUCCESS if either \a current and/or \a pending have been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or both \a current and \a pending are NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the platform is not windows + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceSetDriverModel_v2() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDriverModel_v2(nvmlDevice_t device, nvmlDriverModel_t *current, nvmlDriverModel_t *pending); + +/** + * Get VBIOS version of the device. + * + * For all products. + * + * The VBIOS version may change from time to time. It will not exceed 32 characters in length + * (including the NULL terminator). See \ref nvmlConstants::NVML_DEVICE_VBIOS_VERSION_BUFFER_SIZE. + * + * @param device The identifier of the target device + * @param version Reference to which to return the VBIOS version + * @param length The maximum allowed length of the string returned in \a version + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a version is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVbiosVersion(nvmlDevice_t device, char *version, unsigned int length); + +/** + * Get Bridge Chip Information for all the bridge chips on the board. + * + * For all fully supported products. + * Only applicable to multi-GPU products. + * + * @param device The identifier of the target device + * @param bridgeHierarchy Reference to the returned bridge chip Hierarchy + * + * @return + * - \ref NVML_SUCCESS if bridge chip exists + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a bridgeInfo is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if bridge chip not supported on the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBridgeChipInfo(nvmlDevice_t device, nvmlBridgeChipHierarchy_t *bridgeHierarchy); + +/** + * Get information about processes with a compute context on a device + * + * For Fermi &tm; or newer fully supported devices. + * + * This function returns information only about compute running processes (e.g. CUDA application which have + * active context). Any graphics applications (e.g. using OpenGL, DirectX) won't be listed by this function. + * + * To query the current number of running compute processes, call this function with *infoCount = 0. The + * return code will be NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if none are running. For this call + * \a infos is allowed to be NULL. + * + * The usedGpuMemory field returned is all of the 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. Allocate more space for \a infos table in case new compute processes are spawned. + * + * @note In MIG mode, if device handle is provided, the API returns 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. + * + * @param device The device handle or MIG device handle + * @param infoCount Reference in which to provide the \a infos array size, and + * to return the number of returned elements + * @param infos Reference in which to return the process information + * + * @return + * - \ref NVML_SUCCESS if \a infoCount and \a infos have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a infoCount indicates that the \a infos array is too small + * \a infoCount will contain minimal amount of space necessary for + * the call to complete + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, either of \a infoCount or \a infos is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by \a device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see \ref nvmlSystemGetProcessName + */ +nvmlReturn_t DECLDIR nvmlDeviceGetComputeRunningProcesses_v3(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_t *infos); + +/** + * Get information about processes with a graphics context on a device + * + * For Kepler &tm; or newer fully supported devices. + * + * This function returns information only about graphics based processes + * (eg. applications using OpenGL, DirectX) + * + * To query the current number of running graphics processes, call this function with *infoCount = 0. The + * return code will be NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if none are running. For this call + * \a infos is allowed to be NULL. + * + * The usedGpuMemory field returned is all of the 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. Allocate more space for \a infos table in case new graphics processes are spawned. + * + * @note In MIG mode, if device handle is provided, the API returns 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. + * + * @param device The device handle or MIG device handle + * @param infoCount Reference in which to provide the \a infos array size, and + * to return the number of returned elements + * @param infos Reference in which to return the process information + * + * @return + * - \ref NVML_SUCCESS if \a infoCount and \a infos have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a infoCount indicates that the \a infos array is too small + * \a infoCount will contain minimal amount of space necessary for + * the call to complete + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, either of \a infoCount or \a infos is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by \a device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see \ref nvmlSystemGetProcessName + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGraphicsRunningProcesses_v3(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_t *infos); + +/** + * Get information about processes with a Multi-Process Service (MPS) compute context on a device + * + * For Volta &tm; or newer fully supported devices. + * + * This function returns information only about compute running processes (e.g. CUDA application which have + * active context) utilizing MPS. Any graphics applications (e.g. using OpenGL, DirectX) won't be listed by + * this function. + * + * To query the current number of running compute processes, call this function with *infoCount = 0. The + * return code will be NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if none are running. For this call + * \a infos is allowed to be NULL. + * + * The usedGpuMemory field returned is all of the 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. Allocate more space for \a infos table in case new compute processes are spawned. + * + * @note In MIG mode, if device handle is provided, the API returns 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. + * + * @param device The device handle or MIG device handle + * @param infoCount Reference in which to provide the \a infos array size, and + * to return the number of returned elements + * @param infos Reference in which to return the process information + * + * @return + * - \ref NVML_SUCCESS if \a infoCount and \a infos have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a infoCount indicates that the \a infos array is too small + * \a infoCount will contain minimal amount of space necessary for + * the call to complete + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, either of \a infoCount or \a infos is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by \a device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see \ref nvmlSystemGetProcessName + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMPSComputeRunningProcesses_v3(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_t *infos); + +/** + * Get information about running processes on a device for input context + * + * For Hopper &tm; or newer fully supported devices. + * + * This function returns information only about running processes (e.g. CUDA application which have + * active context). + * + * To determine the size of the \a plist->procArray array to allocate, call the function with + * \a plist->numProcArrayEntries set to zero and \a plist->procArray set to NULL. The return + * code will be either NVML_ERROR_INSUFFICIENT_SIZE (if there are valid processes of type + * \a plist->mode to report on, in which case the \a plist->numProcArrayEntries field will + * indicate the required number of entries in the array) or NVML_SUCCESS (if no processes of type + * \a plist->mode exist). + * + * The usedGpuMemory field returned is all of the memory used by the application. + * The usedGpuCcProtectedMemory field returned 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. Allocate more space for \a plist->procArray table in case new processes are spawned. + * + * @note In MIG mode, if device handle is provided, the API returns 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 and in windows. + * + * @param device The device handle or MIG device handle + * @param plist Reference in which to process detail list + * \a plist->version The api version + * \a plist->mode The process mode + * \a plist->procArray Reference in which to return the process information + * \a plist->numProcArrayEntries Proc array size of returned entries + * + * @return + * - \ref NVML_SUCCESS if \a plist->numprocArrayEntries and \a plist->procArray have been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a plist->numprocArrayEntries indicates that the \a plist->procArray is too small + * \a plist->numprocArrayEntries will contain minimal amount of space necessary for + * the call to complete + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a plist is NULL, \a plist->version is invalid, + * \a plist->mode is invalid, + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by \a device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRunningProcessDetailList(nvmlDevice_t device, nvmlProcessDetailList_t *plist); + +/** + * Check if the GPU devices are on the same physical board. + * + * For all fully supported products. + * + * @param device1 The first GPU device + * @param device2 The second GPU device + * @param onSameBoard Reference in which to return the status. + * Non-zero indicates that the GPUs are on the same board. + * + * @return + * - \ref NVML_SUCCESS if \a onSameBoard has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a dev1 or \a dev2 are invalid or \a onSameBoard is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this check is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the either GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceOnSameBoard(nvmlDevice_t device1, nvmlDevice_t device2, int *onSameBoard); + +/** + * Retrieves the root/admin permissions on the target API. See \a nvmlRestrictedAPI_t for the list of supported APIs. + * If an API is restricted only root users can call that API. See \a nvmlDeviceSetAPIRestriction to change current permissions. + * + * For all fully supported products. + * + * @param device The identifier of the target device + * @param apiType Target API type for this operation + * @param isRestricted Reference in which to return the current restriction + * NVML_FEATURE_ENABLED indicates that the API is root-only + * NVML_FEATURE_DISABLED indicates that the API is accessible to all users + * + * @return + * - \ref NVML_SUCCESS if \a isRestricted has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a apiType incorrect or \a isRestricted is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device or the device does not support + * the feature that is being queried (E.G. Enabling/disabling Auto Boosted clocks is + * not supported by the device) + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlRestrictedAPI_t + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAPIRestriction(nvmlDevice_t device, nvmlRestrictedAPI_t apiType, nvmlEnableState_t *isRestricted); + +/** + * Gets recent samples for the GPU. + * + * For Kepler &tm; or newer fully supported devices. + * + * Based on type, this method can be used to fetch the power, utilization or clock samples maintained in the buffer by + * the driver. + * + * Power, Utilization and Clock samples are returned as type "unsigned int" for the union nvmlValue_t. + * + * To get the size of samples that user needs to allocate, the method is invoked with samples set to NULL. + * The returned samplesCount will provide the number of samples that can be queried. The user needs to + * allocate the buffer with size as samplesCount * sizeof(nvmlSample_t). + * + * lastSeenTimeStamp represents CPU timestamp in microseconds. Set it to 0 to fetch all the samples maintained by the + * underlying buffer. Set lastSeenTimeStamp to one of the timeStamps retrieved from the date of the previous query + * to get more recent samples. + * + * This method fetches the number of entries which can be accommodated in the provided samples array, and the + * reference samplesCount is updated to indicate how many samples were actually retrieved. The advantage of using this + * method for samples in contrast to polling via existing methods is to get get higher frequency data at lower polling cost. + * + * @note On MIG-enabled GPUs, querying the following sample types, NVML_GPU_UTILIZATION_SAMPLES, NVML_MEMORY_UTILIZATION_SAMPLES + * NVML_ENC_UTILIZATION_SAMPLES and NVML_DEC_UTILIZATION_SAMPLES, is not currently supported. + * + * @param device The identifier for the target device + * @param type Type of sampling event + * @param lastSeenTimeStamp Return only samples with timestamp greater than lastSeenTimeStamp. + * @param sampleValType Output parameter to represent the type of sample value as described in nvmlSampleVal_t + * @param sampleCount Reference to provide the number of elements which can be queried in samples array + * @param samples Reference in which samples are returned + + * @return + * - \ref NVML_SUCCESS if samples are successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a samplesCount is NULL or + * reference to \a sampleCount is 0 for non null \a samples + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_FOUND if sample entries are not found + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSamples(nvmlDevice_t device, nvmlSamplingType_t type, unsigned long long lastSeenTimeStamp, + nvmlValueType_t *sampleValType, unsigned int *sampleCount, nvmlSample_t *samples); + +/** + * Gets Total, Available and Used size of BAR1 memory. + * + * BAR1 is used to map the FB (device memory) so that it can be directly accessed by the CPU or by 3rd party + * devices (peer-to-peer on the PCIE bus). + * + * @note In MIG mode, if device handle is provided, the API returns aggregate + * information, only if the caller has appropriate privileges. Per-instance + * information can be queried by using specific MIG device handles. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param bar1Memory Reference in which BAR1 memory + * information is returned. + * + * @return + * - \ref NVML_SUCCESS if BAR1 memory is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a bar1Memory is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBAR1MemoryInfo(nvmlDevice_t device, nvmlBAR1Memory_t *bar1Memory); + +/** + * @deprecated Use \ref nvmlDeviceGetFieldValues to query this data. + * This API will be removed in CUDA 14.0. + * + * Translations are as follows: + + * + * NVML_PERF_POLICY_POWER -> NVML_FI_DEV_CLOCKS_EVENT_REASON_SW_POWER_CAP + * NVML_PERF_POLICY_THERMAL -> NVML_FI_DEV_CLOCKS_EVENT_REASON_SW_THERM_SLOWDOWN + * NVML_PERF_POLICY_SYNC_BOOST -> NVML_FI_DEV_CLOCKS_EVENT_REASON_SYNC_BOOST + * NVML_PERF_POLICY_BOARD_LIMIT -> NVML_FI_DEV_PERF_POLICY_BOARD_LIMIT + * NVML_PERF_POLICY_LOW_UTILIZATION -> NVML_FI_DEV_PERF_POLICY_LOW_UTILIZATION + * NVML_PERF_POLICY_RELIABILITY -> NVML_FI_DEV_PERF_POLICY_RELIABILITY + * NVML_PERF_POLICY_TOTAL_APP_CLOCKS -> DEPRECATED, Do not use + * NVML_PERF_POLICY_TOTAL_BASE_CLOCKS -> NVML_FI_DEV_PERF_POLICY_TOTAL_BASE_CLOCKS + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetViolationStatus(nvmlDevice_t device, nvmlPerfPolicyType_t perfPolicyType, nvmlViolationTime_t *violTime); + +/** + * Gets the device's interrupt number + * + * @param device The identifier of the target device + * @param irqNum The interrupt number associated with the specified device + * + * @return + * - \ref NVML_SUCCESS if irq number is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a irqNum is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetIrqNum(nvmlDevice_t device, unsigned int *irqNum); + +/** + * Gets the device's core count + * + * @note On MIG-enabled GPUs, querying the device's core count is currently not supported using this API. + * Please use \ref nvmlDeviceGetGpuInstanceProfileInfo to fetch the MIG device's core count. + * + * @param device The identifier of the target device + * @param numCores The number of cores for the specified device + * + * @return + * - \ref NVML_SUCCESS if GPU core count is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a numCores is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device or a mig device. + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNumGpuCores(nvmlDevice_t device, unsigned int *numCores); + +/** + * Gets the devices power source + * + * @param device The identifier of the target device + * @param powerSource The power source of the device + * + * @return + * - \ref NVML_SUCCESS if the current power source was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a powerSource is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPowerSource(nvmlDevice_t device, nvmlPowerSource_t *powerSource); + +/** + * Gets the device's memory bus width + * + * @param device The identifier of the target device + * @param busWidth The devices's memory bus width + * + * @return + * - \ref NVML_SUCCESS if the memory bus width is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a busWidth is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMemoryBusWidth(nvmlDevice_t device, unsigned int *busWidth); + +/** + * Gets the device's PCIE Max Link speed in MBPS + * + * @param device The identifier of the target device + * @param maxSpeed The devices's PCIE Max Link speed in MBPS + * + * @return + * - \ref NVML_SUCCESS if PCIe Max Link Speed is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a maxSpeed is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPcieLinkMaxSpeed(nvmlDevice_t device, unsigned int *maxSpeed); + +/** + * Gets the device's PCIe Link speed in Mbps + * + * @param device The identifier of the target device + * @param pcieSpeed The devices's PCIe Max Link speed in Mbps + * + * @return + * - \ref NVML_SUCCESS if \a pcieSpeed has been retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pcieSpeed is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support PCIe speed getting + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPcieSpeed(nvmlDevice_t device, unsigned int *pcieSpeed); + +/** + * Gets the device's Adaptive Clock status + * + * @param device The identifier of the target device + * @param adaptiveClockStatus The current adaptive clocking status, either + * NVML_ADAPTIVE_CLOCKING_INFO_STATUS_DISABLED + * or NVML_ADAPTIVE_CLOCKING_INFO_STATUS_ENABLED + * + * @return + * - \ref NVML_SUCCESS if the current adaptive clocking status is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a adaptiveClockStatus is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAdaptiveClockInfoStatus(nvmlDevice_t device, unsigned int *adaptiveClockStatus); + +/** + * Get the type of the GPU Bus (PCIe, PCI, ...) + * + * @param device The identifier of the target device + * @param type The PCI Bus type + * + * return + * - \ref NVML_SUCCESS if the bus \a type is successfully retreived + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a type is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetBusType(nvmlDevice_t device, nvmlBusType_t *type); + + + /** + * @deprecated Will be deprecated in a future release. Use \ref nvmlDeviceGetGpuFabricInfoV instead + * + * Get fabric information associated with the device. + * + * For Hopper &tm; or newer fully supported devices. + * + * On Hopper + NVSwitch systems, GPU is registered with the NVIDIA Fabric Manager + * Upon successful registration, the GPU is added to the NVLink fabric to enable + * peer-to-peer communication. + * This API reports the current state of the GPU in the NVLink fabric + * along with other useful information. + * + * + * @param device The identifier of the target device + * @param gpuFabricInfo Information about GPU fabric state + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support gpu fabric + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetGpuFabricInfo(nvmlDevice_t device, nvmlGpuFabricInfo_t *gpuFabricInfo); + +/** +* Versioned wrapper around \ref nvmlDeviceGetGpuFabricInfo that accepts a versioned +* \ref nvmlGpuFabricInfo_v2_t or later output structure. +* +* @note The caller must set the \ref nvmlGpuFabricInfoV_t.version field to the +* appropriate version prior to calling this function. For example: +* \code +* nvmlGpuFabricInfoV_t fabricInfo = +* { .version = nvmlGpuFabricInfo_v2 }; +* nvmlReturn_t result = nvmlDeviceGetGpuFabricInfoV(device,&fabricInfo); +* \endcode +* +* For Hopper &tm; or newer fully supported devices. +* +* @param device The identifier of the target device +* @param gpuFabricInfo Information about GPU fabric state +* +* @return +* - \ref NVML_SUCCESS Upon success +* - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support gpu fabric +*/ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuFabricInfoV(nvmlDevice_t device, + nvmlGpuFabricInfoV_t *gpuFabricInfo); + +/** + * Get Conf Computing System capabilities. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param capabilities System CC capabilities + * + * @return + * - \ref NVML_SUCCESS if \a capabilities were successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a capabilities is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlSystemGetConfComputeCapabilities(nvmlConfComputeSystemCaps_t *capabilities); + +/** + * Get Conf Computing System State. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param state System CC State + * + * @return + * - \ref NVML_SUCCESS if \a state were successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a state is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlSystemGetConfComputeState(nvmlConfComputeSystemState_t *state); + +/** + * Get Conf Computing Protected and Unprotected Memory Sizes. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device Device handle + * @param memInfo Protected/Unprotected Memory sizes + * + * @return + * - \ref NVML_SUCCESS if \a memInfo were successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a memInfo or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlDeviceGetConfComputeMemSizeInfo(nvmlDevice_t device, nvmlConfComputeMemSizeInfo_t *memInfo); + +/** + * Get Conf Computing GPUs ready state. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param isAcceptingWork Returns GPU current work accepting state, + * NVML_CC_ACCEPTING_CLIENT_REQUESTS_TRUE or + * NVML_CC_ACCEPTING_CLIENT_REQUESTS_FALSE + * + * return + * - \ref NVML_SUCCESS if \a current GPUs ready state were successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a isAcceptingWork is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlSystemGetConfComputeGpusReadyState(unsigned int *isAcceptingWork); + +/** + * Get Conf Computing protected memory usage. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device The identifier of the target device + * @param memory Reference in which to return the memory information + * + * @return + * - \ref NVML_SUCCESS if \a memory has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetConfComputeProtectedMemoryUsage(nvmlDevice_t device, nvmlMemory_t *memory); + +/** + * Get Conf Computing GPU certificate details. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device The identifier of the target device + * @param gpuCert Reference in which to return the gpu certificate information + * + * @return + * - \ref NVML_SUCCESS if \a gpu certificate info has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetConfComputeGpuCertificate(nvmlDevice_t device, + nvmlConfComputeGpuCertificate_t *gpuCert); + +/** + * Get Conf Computing GPU attestation report. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device The identifier of the target device + * @param gpuAtstReport Reference in which to return the gpu attestation report + * + * @return + * - \ref NVML_SUCCESS if \a gpu attestation report has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetConfComputeGpuAttestationReport(nvmlDevice_t device, + nvmlConfComputeGpuAttestationReport_t *gpuAtstReport); +/** + * Get Conf Computing key rotation threshold detail. + * + * For Hopper &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param pKeyRotationThrInfo Reference in which to return the key rotation threshold data + * + * @return + * - \ref NVML_SUCCESS if \a gpu key rotation threshold info has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlSystemGetConfComputeKeyRotationThresholdInfo( + nvmlConfComputeGetKeyRotationThresholdInfo_t *pKeyRotationThrInfo); + +/** + * Set Conf Computing Unprotected Memory Size. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device Device Handle + * @param sizeKiB Unprotected Memory size to be set in KiB + * + * @return + * - \ref NVML_SUCCESS if \a sizeKiB successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlDeviceSetConfComputeUnprotectedMemSize(nvmlDevice_t device, unsigned long long sizeKiB); + +/** + * Set Conf Computing GPUs ready state. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param isAcceptingWork GPU accepting new work, NVML_CC_ACCEPTING_CLIENT_REQUESTS_TRUE or + * NVML_CC_ACCEPTING_CLIENT_REQUESTS_FALSE + * + * return + * - \ref NVML_SUCCESS if \a current GPUs ready state is successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a isAcceptingWork is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlSystemSetConfComputeGpusReadyState(unsigned int isAcceptingWork); + +/** + * Set Conf Computing key rotation threshold. + * + * For Hopper &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * This function is to set the confidential compute key rotation threshold parameters. + * \a pKeyRotationThrInfo->maxAttackerAdvantage should be in the range from + * NVML_CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MIN to NVML_CC_KEY_ROTATION_THRESHOLD_ATTACKER_ADVANTAGE_MAX. + * Default value is 60. + * + * @param pKeyRotationThrInfo Reference to the key rotation threshold data + * + * @return + * - \ref NVML_SUCCESS if \a key rotation threashold max attacker advantage has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a memory is NULL + * - \ref NVML_ERROR_INVALID_STATE if confidential compute GPU ready state is enabled + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlSystemSetConfComputeKeyRotationThresholdInfo( + nvmlConfComputeSetKeyRotationThresholdInfo_t *pKeyRotationThrInfo); + +/** + * Get Conf Computing System Settings. + * + * For Hopper &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param settings System CC settings + * + * @return + * - \ref NVML_SUCCESS If the query is success + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid or \a counters is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlSystemGetConfComputeSettings(nvmlSystemConfComputeSettings_t *settings); + +/** + * Retrieve GSP firmware version. + * + * The caller passes in buffer via \a version and corresponding GSP firmware numbered version + * is returned with the same parameter in string format. + * + * @param device Device handle + * @param version The retrieved GSP firmware version + * + * @return + * - \ref NVML_SUCCESS if GSP firmware version is sucessfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or GSP \a version pointer is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if GSP firmware is not enabled for GPU + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGspFirmwareVersion(nvmlDevice_t device, char *version); + +/** + * Retrieve GSP firmware mode. + * + * The caller passes in integer pointers. GSP firmware enablement and default mode information is returned with + * corresponding parameters. The return value in \a isEnabled and \a defaultMode should be treated as boolean. + * + * @param device Device handle + * @param isEnabled Pointer to specify if GSP firmware is enabled + * @param defaultMode Pointer to specify if GSP firmware is supported by default on \a device + * + * @return + * - \ref NVML_SUCCESS if GSP firmware mode is sucessfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or any of \a isEnabled or \a defaultMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if GSP firmware is not enabled for GPU + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGspFirmwareMode(nvmlDevice_t device, unsigned int *isEnabled, unsigned int *defaultMode); + +/** + * Get SRAM ECC error status of this device. + * + * For Ampere &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * See \ref nvmlEccSramErrorStatus_v1_t for more information on the struct. + * + * @param device The identifier of the target device + * @param status Returns SRAM ECC error status + * + * @return + * - \ref NVML_SUCCESS If \a limit has been set + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid or \a counters is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a nvmlEccSramErrorStatus_t is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSramEccErrorStatus(nvmlDevice_t device, + nvmlEccSramErrorStatus_t *status); + +/** + * Set new power limit of this device. + * + * For Kepler &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. + * + * See \ref nvmlPowerValue_v2_t for more information on the struct. + * + * \note Limit is not persistent across reboots or driver unloads. + * Enable persistent mode to prevent driver from unloading when no application is using the device. + * + * This API replaces nvmlDeviceSetPowerManagementLimit. It can be used as a drop-in replacement for the older version. + * + * @param device The identifier of the target device + * @param powerValue Power management limit in milliwatts to set + * + * @return + * - \ref NVML_SUCCESS if \a limit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a powerValue is NULL or contains invalid values + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see NVML_FI_DEV_POWER_AVERAGE + * @see NVML_FI_DEV_POWER_INSTANT + * @see NVML_FI_DEV_POWER_MIN_LIMIT + * @see NVML_FI_DEV_POWER_MAX_LIMIT + * @see NVML_FI_DEV_POWER_CURRENT_LIMIT + */ +nvmlReturn_t DECLDIR nvmlDeviceSetPowerManagementLimit_v2(nvmlDevice_t device, nvmlPowerValue_v2_t *powerValue); + +/** + * @} // @defgroup nvmlDeviceQueries Device Queries + */ + +/** @addtogroup nvmlAccountingStats + * @{ + */ + +/** + * Queries the state of per process accounting mode. + * + * For Kepler &tm; or newer fully supported devices. + * + * See \ref nvmlDeviceGetAccountingStats for more details. + * See \ref nvmlDeviceSetAccountingMode + * + * @param device The identifier of the target device + * @param mode Reference in which to return the current accounting mode + * + * @return + * - \ref NVML_SUCCESS if the mode has been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode are NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAccountingMode(nvmlDevice_t device, nvmlEnableState_t *mode); + +/** + * Queries process's accounting stats. + * + * For Kepler &tm; 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 life time of the process and after its termination. + * The time field in \ref nvmlAccountingStats_t is reported as 0 during the lifetime of the process and + * updated to actual running time after its termination. + * Accounting stats are kept in a circular buffer, newly created processes overwrite information about old + * processes. + * + * See \ref nvmlAccountingStats_t for description of each returned metric. + * List of processes that can be queried can be retrieved from \ref nvmlDeviceGetAccountingPids. + * + * @note Accounting Mode needs to be on. See \ref nvmlDeviceGetAccountingMode. + * @note Only compute and graphics applications stats can be queried. Monitoring applications stats can't be + * queried since they don't contribute to GPU utilization. + * @note In case of pid collision stats of only the latest process (that terminated last) will be reported + * + * @warning On Kepler devices per process statistics are accurate only if there's one process running on a GPU. + * + * @param device The identifier of the target device + * @param pid Process Id of the target process to query stats for + * @param stats Reference in which to return the process's accounting stats + * + * @return + * - \ref NVML_SUCCESS if stats have been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a stats are NULL + * - \ref NVML_ERROR_NOT_FOUND if process stats were not found + * - \ref NVML_ERROR_NOT_SUPPORTED if \a device doesn't support this feature or accounting mode is disabled + * or on vGPU host. + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetAccountingBufferSize + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAccountingStats(nvmlDevice_t device, unsigned int pid, nvmlAccountingStats_t *stats); + +/** + * Queries list of processes that can be queried for accounting stats. The list of processes returned + * can be in running or terminated state. + * + * For Kepler &tm; or newer fully supported devices. + * + * To query the number of processes under Accounting Mode, call this function with *count = 0 and pids=NULL. + * The return code will be NVML_ERROR_INSUFFICIENT_SIZE with an updated count value indicating the number of processes. + * + * For more details see \ref nvmlDeviceGetAccountingStats. + * + * @note In case of PID collision some processes might not be accessible before the circular buffer is full. + * + * @param device The identifier of the target device + * @param count Reference in which to provide the \a pids array size, and + * to return the number of elements ready to be queried + * @param pids Reference in which to return list of process ids + * + * @return + * - \ref NVML_SUCCESS if pids were successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a count is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if \a device doesn't support this feature or accounting mode is disabled + * or on vGPU host. + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a count is too small (\a count is set to + * expected value) + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetAccountingBufferSize + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAccountingPids(nvmlDevice_t device, unsigned int *count, unsigned int *pids); + +/** + * Returns the number of processes that the circular buffer with accounting pids can hold. + * + * For Kepler &tm; or newer fully supported devices. + * + * This is the maximum number of processes that accounting information will be stored for before information + * about oldest processes will get overwritten by information about new processes. + * + * @param device The identifier of the target device + * @param bufferSize Reference in which to provide the size (in number of elements) + * of the circular buffer for accounting stats. + * + * @return + * - \ref NVML_SUCCESS if buffer size was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a bufferSize is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature or accounting mode is disabled + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetAccountingStats + * @see nvmlDeviceGetAccountingPids + */ +nvmlReturn_t DECLDIR nvmlDeviceGetAccountingBufferSize(nvmlDevice_t device, unsigned int *bufferSize); + +/** @} */ + +/** @addtogroup nvmlDeviceQueries + * @{ + */ + +/** + * Returns the list of retired pages by source, including pages that are pending retirement + * The address information provided from this API is the hardware address of the page that was retired. Note + * that this does not match the virtual address used in CUDA, but will match the address information in Xid 63 + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param cause Filter page addresses by cause of retirement + * @param pageCount Reference in which to provide the \a addresses buffer size, and + * to return the number of retired pages that match \a cause + * Set to 0 to query the size without allocating an \a addresses buffer + * @param addresses Buffer to write the page addresses into + * + * @return + * - \ref NVML_SUCCESS if \a pageCount was populated and \a addresses was filled + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a pageCount indicates the buffer is not large enough to store all the + * matching page addresses. \a pageCount is set to the needed size. + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a pageCount is NULL, \a cause is invalid, or + * \a addresses is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRetiredPages(nvmlDevice_t device, nvmlPageRetirementCause_t cause, + unsigned int *pageCount, unsigned long long *addresses); + +/** + * Returns the list of retired pages by source, including pages that are pending retirement + * The address information provided from this API is the hardware address of the page that was retired. Note + * that this does not match the virtual address used in CUDA, but will match the address information in Xid 63 + * + * \note nvmlDeviceGetRetiredPages_v2 adds an additional timestamps parameter to return the time of each page's + * retirement. This is supported for Pascal and newer architecture. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param cause Filter page addresses by cause of retirement + * @param pageCount Reference in which to provide the \a addresses buffer size, and + * to return the number of retired pages that match \a cause + * Set to 0 to query the size without allocating an \a addresses buffer + * @param addresses Buffer to write the page addresses into + * @param timestamps Buffer to write the timestamps of page retirement, additional for _v2 + * + * @return + * - \ref NVML_SUCCESS if \a pageCount was populated and \a addresses was filled + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a pageCount indicates the buffer is not large enough to store all the + * matching page addresses. \a pageCount is set to the needed size. + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a pageCount is NULL, \a cause is invalid, or + * \a addresses is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRetiredPages_v2(nvmlDevice_t device, nvmlPageRetirementCause_t cause, + unsigned int *pageCount, unsigned long long *addresses, unsigned long long *timestamps); + +/** + * Check if any pages are pending retirement and need a reboot to fully retire. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param isPending Reference in which to return the pending status + * + * @return + * - \ref NVML_SUCCESS if \a isPending was populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a isPending is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRetiredPagesPendingStatus(nvmlDevice_t device, nvmlEnableState_t *isPending); + +/** + * Get number of remapped rows. The number of rows reported will be based on + * the cause of the remapping. isPending indicates whether or not there are + * pending remappings. A reset will be required to actually remap the row. + * failureOccurred will be set if a row remapping ever failed in the past. A + * pending remapping won't affect future work on the GPU since + * error-containment and dynamic page blacklisting will take care of that. + * + * @note On MIG-enabled GPUs with active instances, querying the number of + * remapped rows is not supported + * + * For Ampere &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param corrRows Reference for number of rows remapped due to correctable errors + * @param uncRows Reference for number of rows remapped due to uncorrectable errors + * @param isPending Reference for whether or not remappings are pending + * @param failureOccurred Reference that is set when a remapping has failed in the past + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a corrRows, \a uncRows, \a isPending or \a failureOccurred is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN Unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRemappedRows(nvmlDevice_t device, unsigned int *corrRows, unsigned int *uncRows, + unsigned int *isPending, unsigned int *failureOccurred); + +/** + * Get the row remapper histogram. Returns the remap availability for each bank + * on the GPU. + * + * @param device Device handle + * @param values Histogram values + * + * @return + * - \ref NVML_SUCCESS On success + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetRowRemapperHistogram(nvmlDevice_t device, nvmlRowRemapperHistogramValues_t *values); + +/** + * Get architecture for device + * + * @param device The identifier of the target device + * @param arch Reference where architecture is returned, if call successful. + * Set to NVML_DEVICE_ARCH_* upon success + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device or \a arch (output refererence) are invalid + */ +nvmlReturn_t DECLDIR nvmlDeviceGetArchitecture(nvmlDevice_t device, nvmlDeviceArchitecture_t *arch); + +/** + * Retrieves the frequency monitor fault status for the device. + * + * For Ampere &tm; or newer fully supported devices. + * Requires root user. + * + * See \ref nvmlClkMonStatus_t for details on decoding the status output. + * + * @param device The identifier of the target device + * @param status Reference in which to return the clkmon fault status + * + * @return + * - \ref NVML_SUCCESS if \a status has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a status is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetClkMonStatus() + */ +nvmlReturn_t DECLDIR nvmlDeviceGetClkMonStatus(nvmlDevice_t device, nvmlClkMonStatus_t *status); + +/** + * Retrieves the current utilization and process ID + * + * For Maxwell &tm; or newer fully supported devices. + * + * Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, and video decoder for processes running. + * Utilization values are returned as an array of utilization sample structures in the caller-supplied buffer pointed at + * by \a utilization. One utilization sample structure is returned per process running, that had some 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 int" values. If no valid sample entries are found since the lastSeenTimeStamp, NVML_ERROR_NOT_FOUND + * is returned. + * + * To read utilization values, first determine the size of buffer required to hold the samples by invoking the function with + * \a utilization set to NULL. The caller should allocate a buffer of size + * processSamplesCount * sizeof(nvmlProcessUtilizationSample_t). Invoke the function again with the allocated buffer passed + * in \a utilization, and \a processSamplesCount set to the number of entries the buffer is sized for. + * + * On successful return, the function updates \a processSamplesCount with 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. + * + * lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * @note On MIG-enabled GPUs, querying process utilization is not currently supported. + * + * @param device The identifier of the target device + * @param utilization Pointer to caller-supplied buffer in which guest process utilization samples are returned + * @param processSamplesCount Pointer to caller-supplied array size, and returns number of processes running + * @param lastSeenTimeStamp Return only samples with timestamp greater than lastSeenTimeStamp. + + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a utilization is NULL, or \a samplingPeriodUs is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NOT_FOUND if sample entries are not found + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetProcessUtilization(nvmlDevice_t device, nvmlProcessUtilizationSample_t *utilization, + unsigned int *processSamplesCount, unsigned long long lastSeenTimeStamp); + +/** + * Retrieves the recent utilization and process ID for all running processes + * + * For Maxwell &tm; 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. Utilization values are returned as an array of utilization sample structures in the caller-supplied buffer pointed at + * by \a procesesUtilInfo->procUtilArray. One utilization sample structure is returned per process running, that had some 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 int" values. + * + * The caller should allocate a buffer of size processSamplesCount * sizeof(nvmlProcessUtilizationInfo_t). If the buffer is too small, the API will + * return \a NVML_ERROR_INSUFFICIENT_SIZE, with the recommended minimal buffer size at \a procesesUtilInfo->processSamplesCount. The caller should + * invoke the function again with the allocated buffer passed in \a procesesUtilInfo->procUtilArray, and \a procesesUtilInfo->processSamplesCount + * set to the number no less than the recommended value by the previous API return. + * + * On successful return, the function updates \a procesesUtilInfo->processSamplesCount with 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. + * + * \a procesesUtilInfo->lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set \a procesesUtilInfo->lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * \a procesesUtilInfo->version is the version number of the structure nvmlProcessesUtilizationInfo_t, the caller should set the correct version + * number to retrieve the specific version of processes utilization information. + * + * @note On MIG-enabled GPUs, querying process utilization is not currently supported. + * + * @param device The identifier of the target device + * @param procesesUtilInfo Pointer to the caller-provided structure of nvmlProcessesUtilizationInfo_t. + + * @return + * - \ref NVML_SUCCESS If \a procesesUtilInfo->procUtilArray has been populated + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, or \a procesesUtilInfo is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + * - \ref NVML_ERROR_NOT_FOUND If sample entries are not found + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a procesesUtilInfo is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If \a procesesUtilInfo->procUtilArray is NULL, or the buffer size of procesesUtilInfo->procUtilArray is too small. + * The caller should check the minimul array size from the returned procesesUtilInfo->processSamplesCount, and call + * the function again with a buffer no smaller than procesesUtilInfo->processSamplesCount * sizeof(nvmlProcessUtilizationInfo_t) + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetProcessesUtilizationInfo(nvmlDevice_t device, nvmlProcessesUtilizationInfo_t *procesesUtilInfo); + +/** + * Get platform information of this device. + * + * %BLACKWELL_OR_NEWER% + * + * See \ref nvmlPlatformInfo_v2_t for more information on the struct. + * + * @param device The identifier of the target device + * @param platformInfo Pointer to the caller-provided structure of nvmlPlatformInfo_t. + * + * @return + * - \ref NVML_SUCCESS If \a platformInfo has been retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid or \a platformInfo is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + * - \ref NVML_ERROR_MEMORY if system memory is insufficient + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a nvmlPlatformInfo_t is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPlatformInfo(nvmlDevice_t device, nvmlPlatformInfo_t *platformInfo); + +/** + * Retrieves the Per Device Identifier (PDI) associated with this device. + * + * For Pascal &tm; or newer fully supported devices. + * + * See \ref nvmlPdi_v1_t for more information on the struct. + * + * @param[in] device The identifier of the target device + * @param[out] pdi Reference to the caller-provided structure to return the GPU PDI + * + * @return + * - \ref NVML_SUCCESS if \a pdi has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a pdi is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPdi(nvmlDevice_t device, nvmlPdi_t *pdi); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlUnitCommands Unit Commands + * This chapter describes NVML operations that change the state of the unit. For S-class products. + * Each of these requires root/admin access. Non-admin users will see an NVML_ERROR_NO_PERMISSION + * error code when invoking any of these methods. + * @{ + */ +/***************************************************************************************************/ + +/** + * Set the LED state for the unit. The LED can be either green (0) or amber (1). + * + * For S-class products. + * Requires root/admin permissions. + * + * This operation takes effect immediately. + * + * + * Current S-Class products don't provide unique LEDs for each unit. As such, both front + * and back LEDs will be toggled in unison regardless of which unit is specified with this command. + * + * See \ref nvmlLedColor_t for available colors. + * + * @param unit The identifier of the target unit + * @param color The target LED color + * + * @return + * - \ref NVML_SUCCESS if the LED color has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a unit or \a color is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this is not an S-class product + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlUnitGetLedState() + */ +nvmlReturn_t DECLDIR nvmlUnitSetLedState(nvmlUnit_t unit, nvmlLedColor_t color); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlDeviceCommands Device Commands + * This chapter describes NVML operations that change the state of the device. + * Each of these requires root/admin access. Non-admin users will see an NVML_ERROR_NO_PERMISSION + * error code when invoking any of these methods. + * @{ + */ +/***************************************************************************************************/ + +/** + * Set 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 \ref nvmlEnableState_t for available modes. + * + * After calling this API with mode set to NVML_FEATURE_DISABLED on a device that has its own NUMA + * memory, the given device handle will no longer be valid, and to continue to interact with this + * device, a new handle should be obtained from one of the nvmlDeviceGetHandleBy*() APIs. This + * limitation is currently only applicable to devices that have a coherent NVLink connection to + * system memory. + * + * @param device The identifier of the target device + * @param mode The target persistence mode + * + * @return + * - \ref NVML_SUCCESS if the persistence mode was set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetPersistenceMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceSetPersistenceMode(nvmlDevice_t device, nvmlEnableState_t mode); + +/** + * Set 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 + * + * @note On MIG-enabled GPUs, compute mode would be set to DEFAULT and changing it is not supported. + * + * See \ref nvmlComputeMode_t for details on available compute modes. + * + * @param device The identifier of the target device + * @param mode The target compute mode + * + * @return + * - \ref NVML_SUCCESS if the compute mode was set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetComputeMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceSetComputeMode(nvmlDevice_t device, nvmlComputeMode_t mode); + +/** + * Set the ECC mode for the device. + * + * For Kepler &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_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 \ref nvmlEnableState_t for details on available modes. + * + * @param device The identifier of the target device + * @param ecc The target ECC mode + * + * @return + * - \ref NVML_SUCCESS if the ECC mode was set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a ecc is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetEccMode() + */ +nvmlReturn_t DECLDIR nvmlDeviceSetEccMode(nvmlDevice_t device, nvmlEnableState_t ecc); + +/** + * Clear the ECC error and other memory error counts for the device. + * + * For Kepler &tm; or newer fully supported devices. + * Only applicable to devices with ECC. + * Requires \a NVML_INFOROM_ECC version 2.0 or higher to clear aggregate location-based ECC counts. + * Requires \a NVML_INFOROM_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 \ref nvmlMemoryErrorType_t for details on available counter types. + * + * @param device The identifier of the target device + * @param counterType Flag that indicates which type of errors should be cleared. + * + * @return + * - \ref NVML_SUCCESS if the error counts were cleared + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a counterType is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see + * - nvmlDeviceGetDetailedEccErrors() + * - nvmlDeviceGetTotalEccErrors() + */ +nvmlReturn_t DECLDIR nvmlDeviceClearEccErrorCounts(nvmlDevice_t device, nvmlEccCounterType_t counterType); + +/** + * Set the driver model for the device. + * + * For Fermi &tm; 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). + * This should only be done if the host is subsequently powered down 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. + * + * Change driver model to WDDM is not supported when GPU doesn't support graphics acceleration or + * will not support it after reboot. See \ref nvmlDeviceSetGpuOperationMode. + * + * See \ref nvmlDriverModel_t for details on available driver models. + * See \ref nvmlFlagDefault and \ref nvmlFlagForce + * + * @param device The identifier of the target device + * @param driverModel The target driver model + * @param flags Flags that change the default behavior + * + * @return + * - \ref NVML_SUCCESS if the driver model has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a driverModel is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the platform is not windows or the device does not support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetDriverModel() + */ +nvmlReturn_t DECLDIR nvmlDeviceSetDriverModel(nvmlDevice_t device, nvmlDriverModel_t driverModel, unsigned int flags); + +typedef enum nvmlClockLimitId_enum { + NVML_CLOCK_LIMIT_ID_RANGE_START = 0xffffff00, + NVML_CLOCK_LIMIT_ID_TDP, + NVML_CLOCK_LIMIT_ID_UNLIMITED +} nvmlClockLimitId_t; + +/** + * Set clocks that device will lock to. + * + * Sets the clocks that the device will be running at to the value in the range of minGpuClockMHz to maxGpuClockMHz. + * + * Can be used as a setting to request constant performance. + * + * This can be called with a pair of integer clock frequencies in MHz, or a pair of /ref nvmlClockLimitId_t values. + * See the table below for valid combinations of these values. + * + * minGpuClock | maxGpuClock | Effect + * ------------+-------------+-------------------------------------------------- + * tdp | tdp | Lock clock to TDP + * unlimited | tdp | Upper bound is TDP but clock may drift below this + * tdp | unlimited | Lower bound is TDP but clock may boost above this + * unlimited | unlimited | Unlocked (== nvmlDeviceResetGpuLockedClocks) + * + * If one arg takes one of these values, the other must be one of these values as + * well. Mixed numeric and symbolic calls return NVML_ERROR_INVALID_ARGUMENT. + * + * Requires root/admin permissions. + * + * After system reboot or driver reload GPU clocks go back to their default value. + * See \ref nvmlDeviceResetGpuLockedClocks. + * + * For Volta &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param minGpuClockMHz Requested minimum gpu clock in MHz + * @param maxGpuClockMHz Requested maximum gpu clock in MHz + * + * @return + * - \ref NVML_SUCCESS if new settings were successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a minGpuClockMHz and \a maxGpuClockMHz + * is not a valid clock combination + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetGpuLockedClocks(nvmlDevice_t device, unsigned int minGpuClockMHz, unsigned int maxGpuClockMHz); + +/** + * Resets the gpu clock to the default value + * + * This is the gpu clock that will be used after system reboot or driver reload. + * Default values are idle clocks. + * + * @see nvmlDeviceSetGpuLockedClocks + * + * For Volta &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if new settings were successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceResetGpuLockedClocks(nvmlDevice_t device); + +/** + * Set memory clocks that device will lock to. + * + * Sets the device's memory clocks to the value in the range of minMemClockMHz to maxMemClockMHz. + * + * Can be used as a setting to request constant performance. + * + * Requires root/admin permissions. + * + * After system reboot or driver reload memory clocks go back to their default value. + * See \ref nvmlDeviceResetMemoryLockedClocks. + * + * For Ampere &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param minMemClockMHz Requested minimum memory clock in MHz + * @param maxMemClockMHz Requested maximum memory clock in MHz + * + * @return + * - \ref NVML_SUCCESS if new settings were successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a minGpuClockMHz and \a maxGpuClockMHz + * is not a valid clock combination + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetMemoryLockedClocks(nvmlDevice_t device, unsigned int minMemClockMHz, unsigned int maxMemClockMHz); + +/** + * Resets the memory clock to the default value + * + * This is the memory clock that will be used after system reboot or driver reload. + * Default values are idle clocks. + * + * @see nvmlDeviceSetMemoryLockedClocks + * + * For Ampere &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if new settings were successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceResetMemoryLockedClocks(nvmlDevice_t device); + +/** + * @deprecated Applications clocks are deprecated and will be removed in CUDA 14.0. + * + * Please use \ref nvmlDeviceSetMemoryLockedClocks for Memory Clocks and + * \ref nvmlDeviceSetGpuLockedClocks for Graphics Clocks. + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceSetApplicationsClocks(nvmlDevice_t device, unsigned int memClockMHz, unsigned int graphicsClockMHz); + +/** + * @deprecated Applications clocks are deprecated and will be removed in CUDA 14.0. + * + * Please use \ref nvmlDeviceResetMemoryLockedClocks for Memory Clocks and + * \ref nvmlDeviceResetGpuLockedClocks for Graphics Clocks. + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceResetApplicationsClocks(nvmlDevice_t device); + +/** + * Try to set the current state of Auto Boosted clocks on a device. + * + * For Kepler &tm; 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. Auto Boosted clocks should be disabled if fixed clock + * rates are desired. + * + * Non-root users may use this API by default but can be restricted by root from using this API by calling + * \ref nvmlDeviceSetAPIRestriction with apiType=NVML_RESTRICTED_API_SET_AUTO_BOOSTED_CLOCKS. + * Note: Persistence Mode is required to modify current Auto Boost settings, therefore, it must be enabled. + * + * On Pascal and newer hardware, Auto Boosted clocks are controlled through application clocks. + * Use \ref nvmlDeviceSetApplicationsClocks and \ref nvmlDeviceResetApplicationsClocks to control Auto Boost + * behavior. + * + * @param device The identifier of the target device + * @param enabled What state to try to set Auto Boosted clocks of the target device to + * + * @return + * - \ref NVML_SUCCESS If the Auto Boosted clocks were successfully set to the state specified by \a enabled + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support Auto Boosted clocks + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceSetAutoBoostedClocksEnabled(nvmlDevice_t device, nvmlEnableState_t enabled); + +/** + * Try to set the default state of Auto Boosted clocks on a device. This is the default state that Auto Boosted clocks will + * return to when no compute running processes (e.g. CUDA application which have an active context) are running + * + * For Kepler &tm; 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. Auto Boosted clocks should be disabled if fixed clock + * rates are desired. + * + * On Pascal and newer hardware, Auto Boosted clocks are controlled through application clocks. + * Use \ref nvmlDeviceSetApplicationsClocks and \ref nvmlDeviceResetApplicationsClocks to control Auto Boost + * behavior. + * + * @param device The identifier of the target device + * @param enabled What state to try to set default Auto Boosted clocks of the target device to + * @param flags Flags that change the default behavior. Currently Unused. + * + * @return + * - \ref NVML_SUCCESS If the Auto Boosted clock's default state was successfully set to the state specified by \a enabled + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NO_PERMISSION If the calling user does not have permission to change Auto Boosted clock's default state. + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support Auto Boosted clocks + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + */ +nvmlReturn_t DECLDIR nvmlDeviceSetDefaultAutoBoostedClocksEnabled(nvmlDevice_t device, nvmlEnableState_t enabled, unsigned int flags); + +/** + * Sets the speed of the fan control policy to default. + * + * For all cuda-capable discrete products with fans + * + * @param device The identifier of the target device + * @param fan The index of the fan, starting at zero + * + * return + * NVML_SUCCESS if speed has been adjusted + * NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * NVML_ERROR_INVALID_ARGUMENT if device is invalid + * NVML_ERROR_NOT_SUPPORTED if the device does not support this + * (doesn't have fans) + * NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetDefaultFanSpeed_v2(nvmlDevice_t device, unsigned int fan); + +/** + * Sets current fan control policy. + * + * For Maxwell &tm; or newer fully supported devices. + * + * Requires privileged user. + * + * For all cuda-capable discrete products with fans + * + * device The identifier of the target \a device + * policy The fan control \a policy to set + * + * return + * NVML_SUCCESS if \a policy has been set + * NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a policy is null or the \a fan given doesn't reference + * a fan that exists. + * NVML_ERROR_NOT_SUPPORTED if the \a device is older than Maxwell + * NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetFanControlPolicy(nvmlDevice_t device, unsigned int fan, + nvmlFanControlPolicy_t policy); + +/** + * Sets the temperature threshold for the GPU with the specified threshold type in degrees C. + * + * For Maxwell &tm; or newer fully supported devices. + * + * See \ref nvmlTemperatureThresholds_t for details on available temperature thresholds. + * + * @param device The identifier of the target device + * @param thresholdType The type of threshold value to be set + * @param temp Reference which hold the value to be set + * @return + * - \ref NVML_SUCCESS if \a temp has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a thresholdType is invalid or \a temp is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not have a temperature sensor or is unsupported + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetTemperatureThreshold(nvmlDevice_t device, nvmlTemperatureThresholds_t thresholdType, int *temp); + +/** + * Set new power limit of this device. + * + * For Kepler &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * See \ref nvmlDeviceGetPowerManagementLimitConstraints to check the allowed ranges of values. + * + * \note Limit is not persistent across reboots or driver unloads. + * Enable persistent mode to prevent driver from unloading when no application is using the device. + * + * @param device The identifier of the target device + * @param limit Power management limit in milliwatts to set + * + * @return + * - \ref NVML_SUCCESS if \a limit has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a defaultLimit is out of range + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceGetPowerManagementLimitConstraints + * @see nvmlDeviceGetPowerManagementDefaultLimit + */ +nvmlReturn_t DECLDIR nvmlDeviceSetPowerManagementLimit(nvmlDevice_t device, unsigned int limit); + +/** + * Sets new GOM. See \a nvmlGpuOperationMode_t for details. + * + * For GK110 M-class and X-class Tesla &tm; products from the Kepler family. + * Modes \ref NVML_GOM_LOW_DP and \ref NVML_GOM_ALL_ON are supported on fully supported GeForce products. + * Not supported on Quadro ® and Tesla &tm; C-class products. + * Requires root/admin permissions. + * + * Changing GOMs requires a reboot. + * The reboot requirement might be removed in the future. + * + * Compute only GOMs don't support graphics acceleration. Under windows switching to these GOMs when + * pending driver model is WDDM is not supported. See \ref nvmlDeviceSetDriverModel. + * + * @param device The identifier of the target device + * @param mode Target GOM + * + * @return + * - \ref NVML_SUCCESS if \a mode has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a mode incorrect + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support GOM or specific mode + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlGpuOperationMode_t + * @see nvmlDeviceGetGpuOperationMode + */ +nvmlReturn_t DECLDIR nvmlDeviceSetGpuOperationMode(nvmlDevice_t device, nvmlGpuOperationMode_t mode); + +/** + * Changes the root/admin restructions on certain APIs. See \a nvmlRestrictedAPI_t for the list of supported APIs. + * This method can be used by a root/admin user to give non-root/admin access to certain otherwise-restricted APIs. + * The new setting lasts for the lifetime of the NVIDIA driver; it is not persistent. See \a nvmlDeviceGetAPIRestriction + * to query the current restriction settings. + * + * For Kepler &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * @param device The identifier of the target device + * @param apiType Target API type for this operation + * @param isRestricted The target restriction + * + * @return + * - \ref NVML_SUCCESS if \a isRestricted has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a apiType incorrect + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support changing API restrictions or the device does not support + * the feature that api restrictions are being set for (E.G. Enabling/disabling auto + * boosted clocks is not supported by the device) + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlRestrictedAPI_t + */ +nvmlReturn_t DECLDIR nvmlDeviceSetAPIRestriction(nvmlDevice_t device, nvmlRestrictedAPI_t apiType, nvmlEnableState_t isRestricted); + +/** + * Sets the speed of a specified fan. + * + * WARNING: This function changes the fan control policy to manual. It means that YOU have to monitor + * the temperature and adjust the fan speed accordingly. + * If you set the fan speed too low you can burn your GPU! + * Use nvmlDeviceSetDefaultFanSpeed_v2 to restore default control policy. + * + * For all cuda-capable discrete products with fans that are Maxwell or Newer. + * + * device The identifier of the target device + * fan The index of the fan, starting at zero + * speed The target speed of the fan [0-100] in % of max speed + * + * return + * NVML_SUCCESS if the fan speed has been set + * NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * NVML_ERROR_INVALID_ARGUMENT if the device is not valid, or the speed is outside acceptable ranges, + * or if the fan index doesn't reference an actual fan. + * NVML_ERROR_NOT_SUPPORTED if the device is older than Maxwell. + * NVML_ERROR_UNKNOWN if there was an unexpected error. + */ +nvmlReturn_t DECLDIR nvmlDeviceSetFanSpeed_v2(nvmlDevice_t device, unsigned int fan, unsigned int speed); + +/** + * @deprecated Will be deprecated in a future release. Use \ref nvmlDeviceSetClockOffsets instead. It works + * on Maxwell onwards GPU architectures. + * + * Set the GPCCLK VF offset value + * @param[in] device The identifier of the target device + * @param[in] offset The GPCCLK VF offset value to set + * + * @return + * - \ref NVML_SUCCESS if \a offset has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceSetGpcClkVfOffset(nvmlDevice_t device, int offset); + +/** + * @deprecated Will be deprecated in a future release. Use \ref nvmlDeviceSetClockOffsets instead. It works + * on Maxwell onwards GPU architectures. + * + * Set the MemClk (Memory Clock) VF offset value. It requires elevated privileges. + * @param[in] device The identifier of the target device + * @param[in] offset The MemClk VF offset value to set + * + * @return + * - \ref NVML_SUCCESS if \a offset has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a offset is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceSetMemClkVfOffset(nvmlDevice_t device, int offset); + +/** + * @} + */ + +/** @addtogroup nvmlAccountingStats + * @{ + */ + +/** + * Enables or disables per process accounting. + * + * For Kepler &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * @note This setting is not persistent and will default to disabled after driver unloads. + * Enable persistence mode to be sure the setting doesn't switch off to disabled. + * + * @note Enabling accounting mode has no negative impact on the GPU performance. + * + * @note Disabling accounting clears all accounting pids information. + * + * @note On MIG-enabled GPUs, accounting mode would be set to DISABLED and changing it is not supported. + * + * See \ref nvmlDeviceGetAccountingMode + * See \ref nvmlDeviceGetAccountingStats + * See \ref nvmlDeviceClearAccountingPids + * + * @param device The identifier of the target device + * @param mode The target accounting mode + * + * @return + * - \ref NVML_SUCCESS if the new mode has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a mode are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetAccountingMode(nvmlDevice_t device, nvmlEnableState_t mode); + +/** + * Clears accounting information about all processes that have already terminated. + * + * For Kepler &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * See \ref nvmlDeviceGetAccountingMode + * See \ref nvmlDeviceGetAccountingStats + * See \ref nvmlDeviceSetAccountingMode + * + * @param device The identifier of the target device + * + * @return + * - \ref NVML_SUCCESS if accounting information has been cleared + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceClearAccountingPids(nvmlDevice_t device); + +/** @} */ // @addtogroup nvmlAccountingStats + +/***************************************************************************************************/ +/** @defgroup NvLink NvLink Methods + * This chapter describes methods that NVML can perform on NVLINK enabled devices. + * @{ + */ +/***************************************************************************************************/ + +#define NVML_NVLINK_BER_MANTISSA_SHIFT 8 +#define NVML_NVLINK_BER_MANTISSA_WIDTH 0xf + +#define NVML_NVLINK_BER_EXP_SHIFT 0 +#define NVML_NVLINK_BER_EXP_WIDTH 0xff + +/** + * Nvlink Error counter BER can be obtained using the below macros + * Ex - NVML_NVLINK_ERROR_COUNTER_BER_GET(var, BER_MANTISSA) + */ +#define NVML_NVLINK_ERROR_COUNTER_BER_GET(var, type) \ + (((var) >> NVML_NVLINK_##type##_SHIFT) & \ + (NVML_NVLINK_##type##_WIDTH)) \ + +/* + * NVML_FI_DEV_NVLINK_GET_STATE state enums + */ +#define NVML_NVLINK_STATE_INACTIVE 0x0 +#define NVML_NVLINK_STATE_ACTIVE 0x1 +#define NVML_NVLINK_STATE_SLEEP 0x2 + +#define NVML_NVLINK_TOTAL_SUPPORTED_BW_MODES 23 + +typedef struct +{ + unsigned int version; + unsigned char bwModes[NVML_NVLINK_TOTAL_SUPPORTED_BW_MODES]; + unsigned char totalBwModes; +} nvmlNvlinkSupportedBwModes_v1_t; +typedef nvmlNvlinkSupportedBwModes_v1_t nvmlNvlinkSupportedBwModes_t; +#define nvmlNvlinkSupportedBwModes_v1 NVML_STRUCT_VERSION(NvlinkSupportedBwModes, 1) + +typedef struct +{ + unsigned int version; + unsigned int bIsBest; + unsigned char bwMode; +} nvmlNvlinkGetBwMode_v1_t; +typedef nvmlNvlinkGetBwMode_v1_t nvmlNvlinkGetBwMode_t; +#define nvmlNvlinkGetBwMode_v1 NVML_STRUCT_VERSION(NvlinkGetBwMode, 1) + +typedef struct +{ + unsigned int version; + unsigned int bSetBest; + unsigned char bwMode; +} nvmlNvlinkSetBwMode_v1_t; +typedef nvmlNvlinkSetBwMode_v1_t nvmlNvlinkSetBwMode_t; +#define nvmlNvlinkSetBwMode_v1 NVML_STRUCT_VERSION(NvlinkSetBwMode, 1) + +/** + * Struct to represent per device NVLINK information v1 + */ +typedef struct +{ + unsigned int version; //!< IN - the API version number + unsigned int isNvleEnabled; //!< OUT - NVLINK encryption enablement +} nvmlNvLinkInfo_v1_t; +#define nvmlNvLinkInfo_v1 NVML_STRUCT_VERSION(NvLinkInfo, 1) + +#define NVML_NVLINK_FIRMWARE_UCODE_TYPE_MSE 0x1 +#define NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR 0x2 +#define NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_UPHY 0x3 +#define NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_CLN 0x4 +#define NVML_NVLINK_FIRMWARE_UCODE_TYPE_NETIR_DLN 0x5 +#define NVML_NVLINK_FIRMWARE_VERSION_LENGTH 100 + +/** + * Struct to represent NVLINK firmware Semantic versioning and ucode type + */ +typedef struct +{ + unsigned char ucodeType; + unsigned int major; + unsigned int minor; + unsigned int subMinor; +} nvmlNvlinkFirmwareVersion_t; + +/** + * Struct to represent NVLINK firmware information + */ +typedef struct +{ + nvmlNvlinkFirmwareVersion_t firmwareVersion[NVML_NVLINK_FIRMWARE_VERSION_LENGTH]; //!< OUT - NVLINK firmware version + unsigned int numValidEntries; //!< OUT - Number of valid firmware entries +} nvmlNvlinkFirmwareInfo_t; + +/** + * Struct to represent per device NVLINK information v2 + */ +typedef struct +{ + unsigned int version; //!< IN - the API version number + unsigned int isNvleEnabled; //!< OUT - NVLINK encryption enablement + nvmlNvlinkFirmwareInfo_t firmwareInfo; //!< OUT - NVLINK Firmware info +} nvmlNvLinkInfo_v2_t; +typedef nvmlNvLinkInfo_v2_t nvmlNvLinkInfo_t; +#define nvmlNvLinkInfo_v2 NVML_STRUCT_VERSION(NvLinkInfo, 2) + +/** + * Retrieves the state of the device's NvLink for the link specified + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param isActive \a nvmlEnableState_t where NVML_FEATURE_ENABLED indicates that + * the link is active and NVML_FEATURE_DISABLED indicates it + * is inactive + * + * @return + * - \ref NVML_SUCCESS if \a isActive has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a link is invalid or \a isActive is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkState(nvmlDevice_t device, unsigned int link, nvmlEnableState_t *isActive); + +/** + * Retrieves the version of the device's NvLink for the link specified + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param version Requested NvLink version from nvmlNvlinkVersion_t + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a link is invalid or \a version is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkVersion(nvmlDevice_t device, unsigned int link, unsigned int *version); + +/** + * Retrieves the requested capability from the device's NvLink for the link specified + * Please refer to the \a nvmlNvLinkCapability_t structure for the specific caps that can be queried + * The return value should be treated as a boolean. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param capability Specifies the \a nvmlNvLinkCapability_t to be queried + * @param capResult A boolean for the queried capability indicating that feature is available + * + * @return + * - \ref NVML_SUCCESS if \a capResult has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a link, or \a capability is invalid or \a capResult is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkCapability(nvmlDevice_t device, unsigned int link, + nvmlNvLinkCapability_t capability, unsigned int *capResult); + +/** + * Retrieves the PCI information for the remote node on a NvLink link + * Note: pciSubSystemId is not filled in this function and is indeterminate + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param pci \a nvmlPciInfo_t of the remote node for the specified link + * + * @return + * - \ref NVML_SUCCESS if \a pci has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a link is invalid or \a pci is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkRemotePciInfo_v2(nvmlDevice_t device, unsigned int link, nvmlPciInfo_t *pci); + +/** + * Retrieves the specified error counter value + * Please refer to \a nvmlNvLinkErrorCounter_t for error counters that are available + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param counter Specifies the NvLink counter to be queried + * @param counterValue Returned counter value + * + * @return + * - \ref NVML_SUCCESS if \a counter has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a link, or \a counter is invalid or \a counterValue is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkErrorCounter(nvmlDevice_t device, unsigned int link, + nvmlNvLinkErrorCounter_t counter, unsigned long long *counterValue); + +/** + * Resets all error counters to zero + * Please refer to \a nvmlNvLinkErrorCounter_t for the list of error counters that are reset + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * + * @return + * - \ref NVML_SUCCESS if the reset is successful + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a link is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceResetNvLinkErrorCounters(nvmlDevice_t device, unsigned int link); + +/** + * @deprecated Setting utilization counter control is no longer supported. + * + * Set the NVLINK utilization counter control information for the specified counter, 0 or 1. + * Please refer to \a nvmlNvLinkUtilizationControl_t for the structure definition. Performs a reset + * of the counters if the reset parameter is non-zero. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param counter Specifies the counter that should be set (0 or 1). + * @param link Specifies the NvLink link to be queried + * @param control A reference to the \a nvmlNvLinkUtilizationControl_t to set + * @param reset Resets the counters on set if non-zero + * + * @return + * - \ref NVML_SUCCESS if the control has been set successfully + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a counter, \a link, or \a control is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceSetNvLinkUtilizationControl(nvmlDevice_t device, unsigned int link, unsigned int counter, + nvmlNvLinkUtilizationControl_t *control, unsigned int reset); + +/** + * @deprecated Getting utilization counter control is no longer supported. + * + * Get the NVLINK utilization counter control information for the specified counter, 0 or 1. + * Please refer to \a nvmlNvLinkUtilizationControl_t for the structure definition + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param counter Specifies the counter that should be set (0 or 1). + * @param link Specifies the NvLink link to be queried + * @param control A reference to the \a nvmlNvLinkUtilizationControl_t to place information + * + * @return + * - \ref NVML_SUCCESS if the control has been set successfully + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a counter, \a link, or \a control is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkUtilizationControl(nvmlDevice_t device, unsigned int link, unsigned int counter, + nvmlNvLinkUtilizationControl_t *control); + + +/** + * @deprecated Use \ref nvmlDeviceGetFieldValues with NVML_FI_DEV_NVLINK_THROUGHPUT_* as field values instead. + * + * Retrieve the NVLINK utilization counter based on the current control for a specified counter. + * In general it is good practice to use \a nvmlDeviceSetNvLinkUtilizationControl + * before reading the utilization counters as they have no default state + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param counter Specifies the counter that should be read (0 or 1). + * @param rxcounter Receive counter return value + * @param txcounter Transmit counter return value + * + * @return + * - \ref NVML_SUCCESS if \a rxcounter and \a txcounter have been successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a counter, or \a link is invalid or \a rxcounter or \a txcounter are NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkUtilizationCounter(nvmlDevice_t device, unsigned int link, unsigned int counter, + unsigned long long *rxcounter, unsigned long long *txcounter); + +/** + * @deprecated Freezing NVLINK utilization counters is no longer supported. + * + * Freeze the NVLINK utilization counters + * Both the receive and transmit counters are operated on by this function + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be queried + * @param counter Specifies the counter that should be frozen (0 or 1). + * @param freeze NVML_FEATURE_ENABLED = freeze the receive and transmit counters + * NVML_FEATURE_DISABLED = unfreeze the receive and transmit counters + * + * @return + * - \ref NVML_SUCCESS if counters were successfully frozen or unfrozen + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a link, \a counter, or \a freeze is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceFreezeNvLinkUtilizationCounter (nvmlDevice_t device, unsigned int link, + unsigned int counter, nvmlEnableState_t freeze); + +/** + * @deprecated Resetting NVLINK utilization counters is no longer supported. + * + * Reset the NVLINK utilization counters + * Both the receive and transmit counters are operated on by this function + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param link Specifies the NvLink link to be reset + * @param counter Specifies the counter that should be reset (0 or 1) + * + * @return + * - \ref NVML_SUCCESS if counters were successfully reset + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a link, or \a counter is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlDeviceResetNvLinkUtilizationCounter (nvmlDevice_t device, unsigned int link, unsigned int counter); + +/** +* Get the NVLink device type of the remote device connected over the given link. +* +* @param device The device handle of the target GPU +* @param link The NVLink link index on the target GPU +* @param pNvLinkDeviceType Pointer in which the output remote device type is returned +* +* @return +* - \ref NVML_SUCCESS if \a pNvLinkDeviceType has been set +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_NOT_SUPPORTED if NVLink is not supported +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a link is invalid, or +* \a pNvLinkDeviceType is NULL +* - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is +* otherwise inaccessible +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkRemoteDeviceType(nvmlDevice_t device, unsigned int link, nvmlIntNvLinkDeviceType_t *pNvLinkDeviceType); + +/** + * Set NvLink Low Power Threshold for device. + * + * For Hopper &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param info Reference to \a nvmlNvLinkPowerThres_t struct + * input parameters + * + * @return + * - \ref NVML_SUCCESS if the \a Threshold is successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a Threshold is not within range + * - \ref NVML_ERROR_NOT_READY if an internal driver setting prevents the threshold from being used + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * + **/ +nvmlReturn_t DECLDIR nvmlDeviceSetNvLinkDeviceLowPowerThreshold(nvmlDevice_t device, nvmlNvLinkPowerThres_t *info); + +/** + * Set the global nvlink bandwith mode + * + * @param nvlinkBwMode nvlink bandwidth mode + * @return + * - \ref NVML_SUCCESS on success + * - \ref NVML_ERROR_INVALID_ARGUMENT if an invalid argument is provided + * - \ref NVML_ERROR_IN_USE if P2P object exists + * - \ref NVML_ERROR_NOT_SUPPORTED if GPU is not Hopper or newer architecture. + * - \ref NVML_ERROR_NO_PERMISSION if not root user + */ +nvmlReturn_t DECLDIR nvmlSystemSetNvlinkBwMode(unsigned int nvlinkBwMode); + +/** + * Get the global nvlink bandwith mode + * + * @param nvlinkBwMode reference of nvlink bandwidth mode + * @return + * - \ref NVML_SUCCESS on success + * - \ref NVML_ERROR_INVALID_ARGUMENT if an invalid pointer is provided + * - \ref NVML_ERROR_NOT_SUPPORTED if GPU is not Hopper or newer architecture. + * - \ref NVML_ERROR_NO_PERMISSION if not root user + */ +nvmlReturn_t DECLDIR nvmlSystemGetNvlinkBwMode(unsigned int *nvlinkBwMode); + +/** + * Get the supported NvLink Reduced Bandwidth Modes of the device + * + * %BLACKWELL_OR_NEWER% + * + * @param device The identifier of the target device + * @param supportedBwMode Reference to \a nvmlNvlinkSupportedBwModes_t + * + * @return + * - \ref NVML_SUCCESS if the query was successful + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or supportedBwMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version specified is not supported + **/ +nvmlReturn_t DECLDIR nvmlDeviceGetNvlinkSupportedBwModes(nvmlDevice_t device, + nvmlNvlinkSupportedBwModes_t *supportedBwMode); + +/** + * Get the NvLink Reduced Bandwidth Mode for the device + * + * %BLACKWELL_OR_NEWER% + * + * @param device The identifier of the target device + * @param getBwMode Reference to \a nvmlNvlinkGetBwMode_t + * + * @return + * - \ref NVML_SUCCESS if the query was successful + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or getBwMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version specified is not supported + **/ +nvmlReturn_t DECLDIR nvmlDeviceGetNvlinkBwMode(nvmlDevice_t device, + nvmlNvlinkGetBwMode_t *getBwMode); + +/** + * Set the NvLink Reduced Bandwidth Mode for the device + * + * %BLACKWELL_OR_NEWER% + * + * @param device The identifier of the target device + * @param setBwMode Reference to \a nvmlNvlinkSetBwMode_t + * + * @return + * - \ref NVML_SUCCESS if the Bandwidth mode was successfully set + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or setBwMode is NULL + * - \ref NVML_ERROR_NO_PERMISSION if user does not have permission to change Bandwidth mode + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version specified is not supported + **/ +nvmlReturn_t DECLDIR nvmlDeviceSetNvlinkBwMode(nvmlDevice_t device, + nvmlNvlinkSetBwMode_t *setBwMode); + +/** + * Query NVLINK information associated with this device. + * + * @param[in] device The identifier of the target device + * @param[out] info Reference to \a nvmlNvLinkInfo_t + * + * @return + * - \ref NVML_SUCCESS if query is success + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a info is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version is invalid/unsupported + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkInfo(nvmlDevice_t device, nvmlNvLinkInfo_t *info); + +/** @} */ // @defgroup NvLink NvLink Methods + +/***************************************************************************************************/ +/** @defgroup nvmlEvents Event Handling Methods + * This chapter describes methods that NVML can perform against each device to register and wait for + * some event to occur. + * @{ + */ +/***************************************************************************************************/ + +/** + * Create an empty set of events. + * Event set should be freed by \ref nvmlEventSetFree + * + * For Fermi &tm; or newer fully supported devices. + * @param set Reference in which to return the event handle + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a set is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlEventSetFree + */ +nvmlReturn_t DECLDIR nvmlEventSetCreate(nvmlEventSet_t *set); + +/** + * Starts recording of events on a specified devices and add the events to specified \ref nvmlEventSet_t + * + * For Fermi &tm; or newer fully supported devices. + * ECC events are available only on ECC-enabled devices (see \ref nvmlDeviceGetTotalEccErrors) + * Power capping events are available only on Power Management enabled devices (see \ref nvmlDeviceGetPowerManagementMode) + * + * For Linux only. + * + * This call starts recording of events on specific device. + * All events that occurred before this call are not recorded. + * Checking if some event occurred can be done with \ref nvmlEventSetWait_v2 + * + * If function reports NVML_ERROR_UNKNOWN, event set is in undefined state and should be freed. + * If function reports NVML_ERROR_NOT_SUPPORTED, event set can still be used. None of the requested eventTypes + * are registered in that case. + * + * @param device The identifier of the target device + * @param eventTypes Bitmask of \ref nvmlEventType to record + * @param set Set to which add new event types + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a eventTypes is invalid or \a set is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the platform does not support this feature or some of requested event types + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlEventType + * @see nvmlDeviceGetSupportedEventTypes + * @see nvmlEventSetWait + * @see nvmlEventSetFree + */ +nvmlReturn_t DECLDIR nvmlDeviceRegisterEvents(nvmlDevice_t device, unsigned long long eventTypes, nvmlEventSet_t set); + +/** + * Returns information about events supported on device + * + * For Fermi &tm; or newer fully supported devices. + * + * Events are not supported on Windows. So this function returns an empty mask in \a eventTypes on Windows. + * + * @param device The identifier of the target device + * @param eventTypes Reference in which to return bitmask of supported events + * + * @return + * - \ref NVML_SUCCESS if the eventTypes has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a eventType is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlEventType + * @see nvmlDeviceRegisterEvents + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedEventTypes(nvmlDevice_t device, unsigned long long *eventTypes); + +/** + * Waits on events and delivers events + * + * For Fermi &tm; or newer fully supported devices. + * + * If some events are ready to be delivered at the time of the call, function returns immediately. + * If there are no events ready to be delivered, function sleeps till event arrives + * but not longer than specified timeout. This function in certain conditions can return before + * specified timeout passes (e.g. when interrupt arrives) + * + * On Windows, in case of Xid error, the function returns the most recent Xid error type seen by the system. + * If there are multiple Xid errors generated before nvmlEventSetWait is invoked then the last seen Xid error + * type is returned for all Xid error events. + * + * On Linux, every Xid error event would return the associated event data and other information if applicable. + * + * In MIG mode, if device handle is provided, the API reports all the events for the available instances, + * only if the caller has appropriate privileges. In absence of required privileges, only the events which + * affect all the instances (i.e. whole device) are reported. + * + * This API does not currently support per-instance event reporting using MIG device handles. + * + * @param set Reference to set of events to wait on + * @param data Reference in which to return event data + * @param timeoutms Maximum amount of wait time in milliseconds for registered event + * + * @return + * - \ref NVML_SUCCESS if the data has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a data is NULL + * - \ref NVML_ERROR_TIMEOUT if no event arrived in specified timeout or interrupt arrived + * - \ref NVML_ERROR_GPU_IS_LOST if a GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlEventType + * @see nvmlDeviceRegisterEvents + */ +nvmlReturn_t DECLDIR nvmlEventSetWait_v2(nvmlEventSet_t set, nvmlEventData_t * data, unsigned int timeoutms); + +/** + * Releases events in the set + * + * For Fermi &tm; or newer fully supported devices. + * + * @param set Reference to events to be released + * + * @return + * - \ref NVML_SUCCESS if the event has been successfully released + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceRegisterEvents + */ +nvmlReturn_t DECLDIR nvmlEventSetFree(nvmlEventSet_t set); + +/** + * Create an empty set of system events. + * Event set should be freed by \ref nvmlSystemEventSetFree + * + * For Fermi &tm; or newer fully supported devices. + * @param request Reference to nvmlSystemEventSetCreateRequest_t + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if request is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH for unsupported version + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlSystemEventSetFree + */ +nvmlReturn_t DECLDIR nvmlSystemEventSetCreate(nvmlSystemEventSetCreateRequest_t *request); + +/** + * Releases system event set + * + * For Fermi &tm; or newer fully supported devices. + * + * @param request Reference to nvmlSystemEventSetFreeRequest_t + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if request is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH for unsupported version + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlDeviceRegisterEvents + */ +nvmlReturn_t DECLDIR nvmlSystemEventSetFree(nvmlSystemEventSetFreeRequest_t *request); + +/** + * Starts recording of events on system and add the events to specified \ref nvmlSystemEventSet_t + * + * For Linux only. + * + * This call starts recording of events on specific device. + * All events that occurred before this call are not recorded. + * Checking if some event occurred can be done with \ref nvmlSystemEventSetWait + * + * If function reports NVML_ERROR_UNKNOWN, event set is in undefined state and should be freed. + * If function reports NVML_ERROR_NOT_SUPPORTED, event set can still be used. None of the requested eventTypes + * are registered in that case. + * + * @param request Reference to the struct nvmlSystemRegisterEventRequest_t + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if request is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH for unsupported version + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlSystemEventType + * @see nvmlSystemEventSetWait + * @see nvmlEventSetFree + */ +nvmlReturn_t DECLDIR nvmlSystemRegisterEvents(nvmlSystemRegisterEventRequest_t *request); + +/** + * Waits on system events and delivers events + * + * For Fermi &tm; or newer fully supported devices. + * + * If some events are ready to be delivered at the time of the call, function returns immediately. + * If there are no events ready to be delivered, function sleeps till event arrives + * but not longer than specified timeout. This function in certain conditions can return before + * specified timeout passes (e.g. when interrupt arrives) + * + * if the return request->numEvent equals to request->dataSize, there might be outstanding + * event, it is recommended to call nvmlSystemEventSetWait again to query all the events. + * + * @param request Reference in which to nvmlSystemEventSetWaitRequest_t + * + * @return + * - \ref NVML_SUCCESS if the event has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if request is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH for unsupported version + * - \ref NVML_ERROR_TIMEOUT if no event notification after timeoutms + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlSystemEventType + * @see nvmlSystemRegisterEvents + */ +nvmlReturn_t DECLDIR nvmlSystemEventSetWait(nvmlSystemEventSetWaitRequest_t *request); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlZPI Drain states + * This chapter describes methods that NVML can perform against each device to control their drain state + * and recognition by NVML and NVIDIA kernel driver. These methods can be used with out-of-band tools to + * power on/off GPUs, enable robust reset scenarios, etc. + * @{ + */ +/***************************************************************************************************/ + +/** + * Modify the drain state of a GPU. This method forces a GPU to no longer accept new incoming requests. + * Any new NVML process will no longer see this GPU. Persistence mode for this GPU must be turned off before + * this call is made. + * Must be called as administrator. + * For Linux only. + * + * For Pascal &tm; or newer fully supported devices. + * Some Kepler devices supported. + * + * @param pciInfo The PCI address of the GPU drain state to be modified + * @param newState The drain state that should be entered, see \ref nvmlEnableState_t + * + * @return + * - \ref NVML_SUCCESS if counters were successfully reset + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a nvmlIndex or \a newState is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_NO_PERMISSION if the calling process has insufficient permissions to perform operation + * - \ref NVML_ERROR_IN_USE if the device has persistence mode turned on + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceModifyDrainState (nvmlPciInfo_t *pciInfo, nvmlEnableState_t newState); + +/** + * Query the drain state of a GPU. This method is used to check if a GPU is in a currently draining + * state. + * For Linux only. + * + * For Pascal &tm; or newer fully supported devices. + * Some Kepler devices supported. + * + * @param pciInfo The PCI address of the GPU drain state to be queried + * @param currentState The current drain state for this GPU, see \ref nvmlEnableState_t + * + * @return + * - \ref NVML_SUCCESS if counters were successfully reset + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a nvmlIndex or \a currentState is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceQueryDrainState (nvmlPciInfo_t *pciInfo, nvmlEnableState_t *currentState); + +/** + * This method will remove the specified GPU from the view of both NVML and the NVIDIA kernel driver + * as long as no other processes are attached. If other processes are attached, this call will return + * NVML_ERROR_IN_USE and the GPU will be returned to its original "draining" state. Note: the + * only situation where a process can still be attached after nvmlDeviceModifyDrainState() is called + * to initiate the draining state is if that process was using, and is still using, a GPU before the + * call was made. Also note, persistence mode counts as an attachment to the GPU thus it must be disabled + * prior to this call. + * + * For long-running NVML processes please note that this will change the enumeration of current GPUs. + * For example, if there are four GPUs present and GPU1 is removed, the new enumeration will be 0-2. + * Also, device handles after the removed GPU will not be valid and must be re-established. + * Must be run as administrator. + * For Linux only. + * + * For Pascal &tm; or newer fully supported devices. + * Some Kepler devices supported. + * + * @param pciInfo The PCI address of the GPU to be removed + * @param gpuState Whether the GPU is to be removed, from the OS + * see \ref nvmlDetachGpuState_t + * @param linkState Requested upstream PCIe link state, see \ref nvmlPcieLinkState_t + * + * @return + * - \ref NVML_SUCCESS if counters were successfully reset + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a nvmlIndex is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the device doesn't support this feature + * - \ref NVML_ERROR_IN_USE if the device is still in use and cannot be removed + */ +nvmlReturn_t DECLDIR nvmlDeviceRemoveGpu_v2(nvmlPciInfo_t *pciInfo, nvmlDetachGpuState_t gpuState, nvmlPcieLinkState_t linkState); + +/** + * Request the OS and the NVIDIA kernel driver to rediscover a portion of the PCI subsystem looking for GPUs that + * were previously removed. The portion of the PCI tree can be narrowed by specifying a domain, bus, and device. + * If all are zeroes then the entire PCI tree will be searched. Please note that for long-running NVML processes + * the enumeration will change based on how many GPUs are discovered and where they are inserted in bus order. + * + * In addition, all newly discovered GPUs will be initialized and their ECC scrubbed which may take several seconds + * per GPU. Also, all device handles are no longer guaranteed to be valid post discovery. + * + * Must be run as administrator. + * For Linux only. + * + * For Pascal &tm; or newer fully supported devices. + * Some Kepler devices supported. + * + * @param pciInfo The PCI tree to be searched. Only the domain, bus, and device + * fields are used in this call. + * + * @return + * - \ref NVML_SUCCESS if counters were successfully reset + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a pciInfo is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if the operating system does not support this feature + * - \ref NVML_ERROR_OPERATING_SYSTEM if the operating system is denying this feature + * - \ref NVML_ERROR_NO_PERMISSION if the calling process has insufficient permissions to perform operation + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceDiscoverGpus (nvmlPciInfo_t *pciInfo); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlFieldValueQueries Field Value Queries + * This chapter describes NVML operations that are associated with retrieving Field Values from NVML + * @{ + */ +/***************************************************************************************************/ + +/** + * Request values for a list of fields for a device. This API allows multiple fields to be queried at once. + * If any of the underlying fieldIds are populated by the same driver call, the results for those field IDs + * will be populated from a single call rather than making a driver call for each fieldId. + * + * @param device The device handle of the GPU to request field values for + * @param valuesCount Number of entries in values that should be retrieved + * @param values Array of \a valuesCount structures to hold field values. + * Each value's fieldId must be populated prior to this call + * + * @return + * - \ref NVML_SUCCESS if any values in \a values were populated. Note that you must + * check the nvmlReturn field of each value for each individual + * status + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a values is NULL + */ +nvmlReturn_t DECLDIR nvmlDeviceGetFieldValues(nvmlDevice_t device, int valuesCount, nvmlFieldValue_t *values); + +/** + * Clear values for a list of fields for a device. This API allows multiple fields to be cleared at once. + * + * @param device The device handle of the GPU to request field values for + * @param valuesCount Number of entries in values that should be cleared + * @param values Array of \a valuesCount structures to hold field values. + * Each value's fieldId must be populated prior to this call + * + * @return + * - \ref NVML_SUCCESS if any values in \a values were cleared. Note that you must + * check the nvmlReturn field of each value for each individual + * status + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a values is NULL + */ +nvmlReturn_t DECLDIR nvmlDeviceClearFieldValues(nvmlDevice_t device, int valuesCount, nvmlFieldValue_t *values); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlVirtualGpuQueries vGPU APIs + * This chapter describes operations that are associated with NVIDIA vGPU Software products. + * @{ + */ +/***************************************************************************************************/ + +/** + * This method is used to get the virtualization mode corresponding to the GPU. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device Identifier of the target device + * @param pVirtualMode Reference to virtualization mode. One of NVML_GPU_VIRTUALIZATION_? + * + * @return + * - \ref NVML_SUCCESS if \a pVirtualMode is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a pVirtualMode is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVirtualizationMode(nvmlDevice_t device, nvmlGpuVirtualizationMode_t *pVirtualMode); + +/** + * 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. + * + * @param device The identifier of the target device + * @param pHostVgpuMode Reference in which to return the current vGPU mode + * + * @return + * - \ref NVML_SUCCESS if device's vGPU mode has been successfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device handle is 0 or \a pVgpuMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if \a device doesn't support this feature. + * - \ref NVML_ERROR_UNKNOWN if any unexpected error occurred + */ +nvmlReturn_t DECLDIR nvmlDeviceGetHostVgpuMode(nvmlDevice_t device, nvmlHostVgpuMode_t *pHostVgpuMode); + +/** + * This method is used to set the virtualization mode corresponding to the GPU. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device Identifier of the target device + * @param virtualMode virtualization mode. One of NVML_GPU_VIRTUALIZATION_? + * + * @return + * - \ref NVML_SUCCESS if \a virtualMode is set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a virtualMode is NULL + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_SUPPORTED if setting of virtualization mode is not supported. + * - \ref NVML_ERROR_NO_PERMISSION if setting of virtualization mode is not allowed for this client. + */ +nvmlReturn_t DECLDIR nvmlDeviceSetVirtualizationMode(nvmlDevice_t device, nvmlGpuVirtualizationMode_t virtualMode); + +/** + * Get the vGPU heterogeneous mode for the device. + * + * When in heterogeneous mode, a vGPU can concurrently host timesliced vGPUs with differing framebuffer sizes. + * + * On successful return, the function returns \a pHeterogeneousMode->mode with the current vGPU heterogeneous mode. + * \a pHeterogeneousMode->version is the version number of the structure nvmlVgpuHeterogeneousMode_t, the caller should + * set the correct version number to retrieve the vGPU heterogeneous mode. + * \a pHeterogeneousMode->mode can either be \ref NVML_FEATURE_ENABLED or \ref NVML_FEATURE_DISABLED. + * + * @param device The identifier of the target device + * @param pHeterogeneousMode Pointer to the caller-provided structure of nvmlVgpuHeterogeneousMode_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid or \a pHeterogeneousMode is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device doesn't support this feature + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pHeterogeneousMode is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuHeterogeneousMode(nvmlDevice_t device, nvmlVgpuHeterogeneousMode_t *pHeterogeneousMode); + +/** + * Enable or disable vGPU heterogeneous mode for the device. + * + * When in heterogeneous mode, a vGPU can concurrently host timesliced vGPUs with differing framebuffer sizes. + * + * API would return an appropriate error code upon unsuccessful activation. For example, the heterogeneous mode + * set will fail with error \ref NVML_ERROR_IN_USE if any vGPU instance is active on the device. The caller of this API + * is expected to shutdown the vGPU VMs and retry setting the \a mode. + * On KVM platform, setting heterogeneous mode is allowed, if no MDEV device is created on the device, else will fail + * with same error \ref NVML_ERROR_IN_USE. + * On successful return, the function updates the vGPU heterogeneous mode with the user provided \a pHeterogeneousMode->mode. + * \a pHeterogeneousMode->version is the version number of the structure nvmlVgpuHeterogeneousMode_t, the caller should + * set the correct version number to set the vGPU heterogeneous mode. + * + * @param device Identifier of the target device + * @param pHeterogeneousMode Pointer to the caller-provided structure of nvmlVgpuHeterogeneousMode_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device or \a pHeterogeneousMode is NULL or \a pHeterogeneousMode->mode is invalid + * - \ref NVML_ERROR_IN_USE If the \a device is in use + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device doesn't support this feature + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pHeterogeneousMode is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetVgpuHeterogeneousMode(nvmlDevice_t device, const nvmlVgpuHeterogeneousMode_t *pHeterogeneousMode); + +/** + * Query the placement ID of active vGPU instance. + * + * When in vGPU heterogeneous mode, this function returns a valid placement ID as \a pPlacement->placementId + * else NVML_INVALID_VGPU_PLACEMENT_ID is returned. + * \a pPlacement->version is the version number of the structure nvmlVgpuPlacementId_t, the caller should + * set the correct version number to get placement id of the vGPU instance \a vgpuInstance. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param pPlacement Pointer to vGPU placement ID structure \a nvmlVgpuPlacementId_t + * + * @return + * - \ref NVML_SUCCESS If information is successfully retrieved + * - \ref NVML_ERROR_NOT_FOUND If \a vgpuInstance does not match a valid active vGPU instance + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a vgpuInstance is invalid or \a pPlacement is NULL + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pPlacement is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetPlacementId(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuPlacementId_t *pPlacement); + +/** + * Query the supported vGPU placement ID of the vGPU type. + * + * The function returns an array of supported vGPU placement IDs for the specified vGPU type ID in the buffer provided + * by the caller at \a pPlacementList->placementIds. The required memory for the placementIds array must be allocated + * based on the maximum number of vGPU type instances, which is retrievable through \ref nvmlVgpuTypeGetMaxInstances(). + * If the provided count by the caller is insufficient, the function will return NVML_ERROR_INSUFFICIENT_SIZE along with + * the number of required entries in \a pPlacementList->count. The caller should then reallocate a buffer with the size + * of pPlacementList->count * sizeof(pPlacementList->placementIds) and invoke the function again. + * + * To obtain a list of homogeneous placement IDs, the caller needs to set \a pPlacementList->mode to NVML_VGPU_PGPU_HOMOGENEOUS_MODE. + * For heterogeneous placement IDs, \a pPlacementList->mode should be set to NVML_VGPU_PGPU_HETEROGENEOUS_MODE. + * By default, a list of heterogeneous placement IDs is returned. + * + * @param device Identifier of the target device + * @param vgpuTypeId Handle to vGPU type. The vGPU type ID + * @param pPlacementList Pointer to the vGPU placement structure \a nvmlVgpuPlacementList_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device or \a vgpuTypeId is invalid or \a pPlacementList is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device or \a vgpuTypeId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pPlacementList is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If the buffer is small, element count is returned in \a pPlacementList->count + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuTypeSupportedPlacements(nvmlDevice_t device, nvmlVgpuTypeId_t vgpuTypeId, nvmlVgpuPlacementList_t *pPlacementList); + +/** + * Query the creatable vGPU placement ID of the vGPU type. + * + * An array of creatable vGPU placement IDs for the vGPU type ID indicated by \a vgpuTypeId is returned in the + * caller-supplied buffer of \a pPlacementList->placementIds. Memory needed for the placementIds array should be + * allocated based on maximum instances of a vGPU type which can be queried via \ref nvmlVgpuTypeGetMaxInstances(). + * If the provided count by the caller is insufficient, the function will return NVML_ERROR_INSUFFICIENT_SIZE along with + * the number of required entries in \a pPlacementList->count. The caller should then reallocate a buffer with the size + * of pPlacementList->count * sizeof(pPlacementList->placementIds) and invoke the function again. + * + * The creatable vGPU placement IDs may differ over time, as there may be restrictions on what type of vGPU the + * vGPU instance is running. + * + * @param device The identifier of the target device + * @param vgpuTypeId Handle to vGPU type. The vGPU type ID + * @param pPlacementList Pointer to the list of vGPU placement structure \a nvmlVgpuPlacementList_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device or \a vgpuTypeId is invalid or \a pPlacementList is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device or \a vgpuTypeId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pPlacementList is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuTypeCreatablePlacements(nvmlDevice_t device, nvmlVgpuTypeId_t vgpuTypeId, nvmlVgpuPlacementList_t *pPlacementList); + +/** + * Retrieve the static GSP heap size of the vGPU type in bytes + * + * @param vgpuTypeId Handle to vGPU type + * @param gspHeapSize Reference to return the GSP heap size value + * @return + * - \ref NVML_SUCCESS Successful completion + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a vgpuTypeId is invalid, or \a gspHeapSize is NULL + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetGspHeapSize(nvmlVgpuTypeId_t vgpuTypeId, unsigned long long *gspHeapSize); + +/** + * Retrieve the static framebuffer reservation of the vGPU type in bytes + * + * @param vgpuTypeId Handle to vGPU type + * @param fbReservation Reference to return the framebuffer reservation + * @return + * - \ref NVML_SUCCESS Successful completion + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a vgpuTypeId is invalid, or \a fbReservation is NULL + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetFbReservation(nvmlVgpuTypeId_t vgpuTypeId, unsigned long long *fbReservation); + +/** + * 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. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param pState Pointer to the vGPU runtime state's structure \a nvmlVgpuRuntimeState_t + * + * @return + * - \ref NVML_SUCCESS If information is successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a vgpuInstance is invalid, or \a pState is NULL + * - \ref NVML_ERROR_NOT_FOUND If \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pState is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetRuntimeStateSize(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuRuntimeState_t *pState); + +/** + * Set the desirable vGPU capability of a device + * + * Refer to the \a nvmlDeviceVgpuCapability_t structure for the specific capabilities that can be set. + * See \ref nvmlEnableState_t for available state. + * + * @param device The identifier of the target device + * @param capability Specifies the \a nvmlDeviceVgpuCapability_t to be set + * @param state The target capability mode + * + * @return + * - \ref NVML_SUCCESS Successful completion + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, or \a capability is invalid, or \a state is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED The API is not supported in current state, or \a device not in vGPU mode + * - \ref NVML_ERROR_UNKNOWN On any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlDeviceSetVgpuCapabilities(nvmlDevice_t device, nvmlDeviceVgpuCapability_t capability, nvmlEnableState_t state); + +/** + * Retrieve the vGPU Software licensable features. + * + * Identifies whether the system supports vGPU Software Licensing. If it does, return the list of licensable feature(s) + * and their current license status. + * + * @param device Identifier of the target device + * @param pGridLicensableFeatures Pointer to structure in which vGPU software licensable features are returned + * + * @return + * - \ref NVML_SUCCESS if licensable features are successfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a pGridLicensableFeatures is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGridLicensableFeatures_v4(nvmlDevice_t device, nvmlGridLicensableFeatures_t *pGridLicensableFeatures); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlVgpu vGPU Management + * @{ + * + * This chapter describes APIs supporting NVIDIA vGPU. + */ +/***************************************************************************************************/ + +/** + * Retrieve the requested vGPU driver capability. + * + * Refer to the \a nvmlVgpuDriverCapability_t structure for the specific capabilities that can be queried. + * The return value in \a capResult should be treated as a boolean, with a non-zero value indicating that the capability + * is supported. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param capability Specifies the \a nvmlVgpuDriverCapability_t to be queried + * @param capResult A boolean for the queried capability indicating that feature is supported + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a capability is invalid, or \a capResult is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED the API is not supported in current state or \a devices not in vGPU mode + * - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlGetVgpuDriverCapabilities(nvmlVgpuDriverCapability_t capability, unsigned int *capResult); + +/** + * Retrieve the requested vGPU capability for GPU. + * + * Refer to the \a nvmlDeviceVgpuCapability_t structure for the specific capabilities that can be queried. + * The return value in \a capResult reports a non-zero value indicating that the capability + * is supported, and also reports the capability's data based on the queried capability. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param capability Specifies the \a nvmlDeviceVgpuCapability_t to be queried + * @param capResult Specifies that the queried capability is supported, and also returns capability's data + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a capability is invalid, or \a capResult is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED the API is not supported in current state or \a device not in vGPU mode + * - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuCapabilities(nvmlDevice_t device, nvmlDeviceVgpuCapability_t capability, unsigned int *capResult); + +/** + * Retrieve the supported vGPU types on a physical GPU (device). + * + * An array of supported vGPU types for the physical GPU indicated by \a device is returned in the caller-supplied buffer + * pointed at by \a vgpuTypeIds. The element count of nvmlVgpuTypeId_t array is passed in \a vgpuCount, and \a vgpuCount + * is used to return the number of vGPU types written to the buffer. + * + * If the supplied buffer is not large enough to accommodate the vGPU type array, the function returns + * NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlVgpuTypeId_t array required in \a vgpuCount. + * To query the number of vGPU types supported for the GPU, call this function with *vgpuCount = 0. + * The code will return NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if no vGPU types are supported. + * + * @param device The identifier of the target device + * @param vgpuCount Pointer to caller-supplied array size, and returns number of vGPU types + * @param vgpuTypeIds Pointer to caller-supplied array in which to return list of vGPU types + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_INSUFFICIENT_SIZE \a vgpuTypeIds buffer is too small, array element count is returned in \a vgpuCount + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuCount is NULL or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if vGPU is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSupportedVgpus(nvmlDevice_t device, unsigned int *vgpuCount, nvmlVgpuTypeId_t *vgpuTypeIds); + +/** + * Retrieve the currently creatable vGPU types on a physical GPU (device). + * + * An array of creatable vGPU types for the physical GPU indicated by \a device is returned in the caller-supplied buffer + * pointed at by \a vgpuTypeIds. The element count of nvmlVgpuTypeId_t array is passed in \a vgpuCount, and \a vgpuCount + * is used to return the number of vGPU types written to the buffer. + * + * The creatable vGPU types for a device may differ over time, as there may be restrictions on what type of vGPU types + * can concurrently run on a device. For example, if only one vGPU type is allowed at a time on a device, then the creatable + * list will be restricted to whatever vGPU type is already running on the device. + * + * If the supplied buffer is not large enough to accommodate the vGPU type array, the function returns + * NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlVgpuTypeId_t array required in \a vgpuCount. + * To query the number of vGPU types that can be created for the GPU, call this function with *vgpuCount = 0. + * The code will return NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if no vGPU types are creatable. + * + * @param device The identifier of the target device + * @param vgpuCount Pointer to caller-supplied array size, and returns number of vGPU types + * @param vgpuTypeIds Pointer to caller-supplied array in which to return list of vGPU types + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_INSUFFICIENT_SIZE \a vgpuTypeIds buffer is too small, array element count is returned in \a vgpuCount + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuCount is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if vGPU is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCreatableVgpus(nvmlDevice_t device, unsigned int *vgpuCount, nvmlVgpuTypeId_t *vgpuTypeIds); + +/** + * Retrieve the class of a vGPU type. It will not exceed 64 characters in length (including the NUL terminator). + * See \ref nvmlConstants::NVML_DEVICE_NAME_BUFFER_SIZE. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param vgpuTypeClass Pointer to string array to return class in + * @param size Size of string + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a vgpuTypeClass is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetClass(nvmlVgpuTypeId_t vgpuTypeId, char *vgpuTypeClass, unsigned int *size); + +/** + * Retrieve the vGPU type name. + * + * The name is an alphanumeric string that denotes a particular vGPU, e.g. GRID M60-2Q. It will not + * exceed 64 characters in length (including the NUL terminator). See \ref + * nvmlConstants::NVML_DEVICE_NAME_BUFFER_SIZE. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param vgpuTypeName Pointer to buffer to return name + * @param size Size of buffer + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a name is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetName(nvmlVgpuTypeId_t vgpuTypeId, char *vgpuTypeName, unsigned int *size); + +/** + * Retrieve the GPU Instance Profile ID for the given vGPU type ID. + * The API will return a valid GPU Instance Profile ID for the MIG capable vGPU types, else INVALID_GPU_INSTANCE_PROFILE_ID is + * returned. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param gpuInstanceProfileId GPU Instance Profile ID + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_NOT_SUPPORTED if \a device is not in vGPU Host virtualization mode + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a gpuInstanceProfileId is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetGpuInstanceProfileId(nvmlVgpuTypeId_t vgpuTypeId, unsigned int *gpuInstanceProfileId); + +/** + * Retrieve the device ID of a vGPU type. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param deviceID Device ID and vendor ID of the device contained in single 32 bit value + * @param subsystemID Subsystem ID and subsystem vendor ID of the device contained in single 32 bit value + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a deviceId or \a subsystemID are NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetDeviceID(nvmlVgpuTypeId_t vgpuTypeId, unsigned long long *deviceID, unsigned long long *subsystemID); + +/** + * Retrieve the vGPU framebuffer size in bytes. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param fbSize Pointer to framebuffer size in bytes + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a fbSize is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetFramebufferSize(nvmlVgpuTypeId_t vgpuTypeId, unsigned long long *fbSize); + +/** + * Retrieve count of vGPU's supported display heads. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param numDisplayHeads Pointer to number of display heads + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a numDisplayHeads is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetNumDisplayHeads(nvmlVgpuTypeId_t vgpuTypeId, unsigned int *numDisplayHeads); + +/** + * Retrieve vGPU display head's maximum supported resolution. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param displayIndex Zero-based index of display head + * @param xdim Pointer to maximum number of pixels in X dimension + * @param ydim Pointer to maximum number of pixels in Y dimension + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a xdim or \a ydim are NULL, or \a displayIndex + * is out of range. + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetResolution(nvmlVgpuTypeId_t vgpuTypeId, unsigned int displayIndex, unsigned int *xdim, unsigned int *ydim); + +/** + * 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 + * ",", 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". + * + * The total length of the returned string will not exceed 128 characters, including the NUL terminator. + * See \ref nvmlVgpuConstants::NVML_GRID_LICENSE_BUFFER_SIZE. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param vgpuTypeLicenseString Pointer to buffer to return license info + * @param size Size of \a vgpuTypeLicenseString buffer + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a vgpuTypeLicenseString is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetLicense(nvmlVgpuTypeId_t vgpuTypeId, char *vgpuTypeLicenseString, unsigned int size); + +/** + * Retrieve the static frame rate limit value of the vGPU type + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param frameRateLimit Reference to return the frame rate limit value + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_NOT_SUPPORTED if frame rate limiter is turned off for the vGPU type + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a frameRateLimit is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetFrameRateLimit(nvmlVgpuTypeId_t vgpuTypeId, unsigned int *frameRateLimit); + +/** + * Retrieve the maximum number of vGPU instances creatable on a device for given vGPU type + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param vgpuTypeId Handle to vGPU type + * @param vgpuInstanceCount Pointer to get the max number of vGPU instances + * that can be created on a deicve for given vgpuTypeId + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid or is not supported on target device, + * or \a vgpuInstanceCount is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetMaxInstances(nvmlDevice_t device, nvmlVgpuTypeId_t vgpuTypeId, unsigned int *vgpuInstanceCount); + +/** + * Retrieve the maximum number of vGPU instances supported per VM for given vGPU type + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param vgpuInstanceCountPerVm Pointer to get the max number of vGPU instances supported per VM for given \a vgpuTypeId + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a vgpuInstanceCountPerVm is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetMaxInstancesPerVm(nvmlVgpuTypeId_t vgpuTypeId, unsigned int *vgpuInstanceCountPerVm); + +/** + * Retrieve the BAR1 info for given vGPU type. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuTypeId Handle to vGPU type + * @param bar1Info Pointer to the vGPU type BAR1 information structure \a nvmlVgpuTypeBar1Info_t + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a bar1Info is NULL + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetBAR1Info(nvmlVgpuTypeId_t vgpuTypeId, nvmlVgpuTypeBar1Info_t *bar1Info); + +/** + * Retrieve the active vGPU instances on a device. + * + * An array of active vGPU instances is returned in the caller-supplied buffer pointed at by \a vgpuInstances. The + * array element count is passed in \a vgpuCount, and \a vgpuCount is used to return the number of vGPU instances + * written to the buffer. + * + * If the supplied buffer is not large enough to accommodate the vGPU instance array, the function returns + * NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlVgpuInstance_t array required in \a vgpuCount. + * To query the number of active vGPU instances, call this function with *vgpuCount = 0. The code will return + * NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if no vGPU Types are supported. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param device The identifier of the target device + * @param vgpuCount Pointer which passes in the array size as well as get + * back the number of types + * @param vgpuInstances Pointer to array in which to return list of vGPU instances + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, or \a vgpuCount is NULL + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_NOT_SUPPORTED if vGPU is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetActiveVgpus(nvmlDevice_t device, unsigned int *vgpuCount, nvmlVgpuInstance_t *vgpuInstances); + +/** + * 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 \ref nvmlConstants::NVML_DEVICE_UUID_BUFFER_SIZE. + * + * The format of the VM ID varies by platform, and is indicated by the type identifier returned in \a vmIdType. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param vmId Pointer to caller-supplied buffer to hold VM ID + * @param size Size of buffer in bytes + * @param vmIdType Pointer to hold VM ID type + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vmId or \a vmIdType is NULL, or \a vgpuInstance is 0 + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetVmID(nvmlVgpuInstance_t vgpuInstance, char *vmId, unsigned int size, nvmlVgpuVmIdType_t *vmIdType); + +/** + * 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, + * not exceeding 80 characters in length (including the NULL terminator). + * See \ref nvmlConstants::NVML_DEVICE_UUID_BUFFER_SIZE. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param uuid Pointer to caller-supplied buffer to hold vGPU UUID + * @param size Size of buffer in bytes + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a uuid is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetUUID(nvmlVgpuInstance_t vgpuInstance, char *uuid, unsigned int size); + +/** + * 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 \a version. The length of the version + * string will not exceed 80 characters in length (including the NUL terminator). + * See \ref nvmlConstants::NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE. + * + * nvmlVgpuInstanceGetVmDriverVersion() 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. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param version Caller-supplied buffer to return driver version string + * @param length Size of \a version buffer + * + * @return + * - \ref NVML_SUCCESS if \a version has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0 + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetVmDriverVersion(nvmlVgpuInstance_t vgpuInstance, char* version, unsigned int length); + +/** + * Retrieve the framebuffer usage in bytes. + * + * Framebuffer usage is the amont of vGPU framebuffer memory that is currently in use by the VM. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance The identifier of the target instance + * @param fbUsage Pointer to framebuffer usage in bytes + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a fbUsage is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetFbUsage(nvmlVgpuInstance_t vgpuInstance, unsigned long long *fbUsage); + +/** + * @deprecated Use \ref nvmlVgpuInstanceGetLicenseInfo_v2. + * + * Retrieve the current licensing state of the vGPU instance. + * + * If the vGPU is currently licensed, \a licensed is set to 1, otherwise it is set to 0. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param licensed Reference to return the licensing status + * + * @return + * - \ref NVML_SUCCESS if \a licensed has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a licensed is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +DEPRECATED(13.0) nvmlReturn_t DECLDIR nvmlVgpuInstanceGetLicenseStatus(nvmlVgpuInstance_t vgpuInstance, unsigned int *licensed); + +/** + * Retrieve the vGPU type of a vGPU instance. + * + * Returns the vGPU type ID of vgpu assigned to the vGPU instance. + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param vgpuTypeId Reference to return the vgpuTypeId + * + * @return + * - \ref NVML_SUCCESS if \a vgpuTypeId has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a vgpuTypeId is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetType(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuTypeId_t *vgpuTypeId); + +/** + * Retrieve the frame rate limit set for the vGPU instance. + * + * Returns the value of the frame rate limit set for the vGPU instance + * + * For Kepler &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param frameRateLimit Reference to return the frame rate limit + * + * @return + * - \ref NVML_SUCCESS if \a frameRateLimit has been set + * - \ref NVML_ERROR_NOT_SUPPORTED if frame rate limiter is turned off for the vGPU type + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a frameRateLimit is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetFrameRateLimit(nvmlVgpuInstance_t vgpuInstance, unsigned int *frameRateLimit); + +/** + * Retrieve the current ECC mode of vGPU instance. + * + * @param vgpuInstance The identifier of the target vGPU instance + * @param eccMode Reference in which to return the current ECC mode + * + * @return + * - \ref NVML_SUCCESS if the vgpuInstance's ECC mode has been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a mode is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_NOT_SUPPORTED if the vGPU doesn't support this feature + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetEccMode(nvmlVgpuInstance_t vgpuInstance, nvmlEnableState_t *eccMode); + +/** + * Retrieve the encoder capacity of a vGPU instance, as a percentage of maximum encoder capacity with valid values in the range 0-100. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param encoderCapacity Reference to an unsigned int for the encoder capacity + * + * @return + * - \ref NVML_SUCCESS if \a encoderCapacity has been retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a encoderQueryType is invalid + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetEncoderCapacity(nvmlVgpuInstance_t vgpuInstance, unsigned int *encoderCapacity); + +/** + * Set the encoder capacity of a vGPU instance, as a percentage of maximum encoder capacity with valid values in the range 0-100. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param encoderCapacity Unsigned int for the encoder capacity value + * + * @return + * - \ref NVML_SUCCESS if \a encoderCapacity has been set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a encoderCapacity is out of range of 0-100. + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceSetEncoderCapacity(nvmlVgpuInstance_t vgpuInstance, unsigned int encoderCapacity); + +/** + * Retrieves the current encoder statistics of a vGPU Instance + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param sessionCount Reference to an unsigned int for count of active encoder sessions + * @param averageFps Reference to an unsigned int for trailing average FPS of all active sessions + * @param averageLatency Reference to an unsigned int for encode latency in microseconds + * + * @return + * - \ref NVML_SUCCESS if \a sessionCount, \a averageFps and \a averageLatency is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a sessionCount , or \a averageFps or \a averageLatency is NULL + * or \a vgpuInstance is 0. + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetEncoderStats(nvmlVgpuInstance_t vgpuInstance, unsigned int *sessionCount, + unsigned int *averageFps, unsigned int *averageLatency); + +/** + * Retrieves information about all active encoder sessions on a vGPU Instance. + * + * An array of active encoder sessions is returned in the caller-supplied buffer pointed at by \a sessionInfo. The + * array element count is passed in \a sessionCount, and \a sessionCount is used to return the number of sessions + * written to the buffer. + * + * If the supplied buffer is not large enough to accommodate the active session array, the function returns + * NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlEncoderSessionInfo_t array required in \a sessionCount. + * To query the number of active encoder sessions, call this function with *sessionCount = 0. The code will return + * NVML_SUCCESS with number of active encoder sessions updated in *sessionCount. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param sessionCount Reference to caller supplied array size, and returns + * the number of sessions. + * @param sessionInfo Reference to caller supplied array in which the list + * of session information us returned. + * + * @return + * - \ref NVML_SUCCESS if \a sessionInfo is fetched + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a sessionCount is too small, array element count is + returned in \a sessionCount + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a sessionCount is NULL, or \a vgpuInstance is 0. + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetEncoderSessions(nvmlVgpuInstance_t vgpuInstance, unsigned int *sessionCount, nvmlEncoderSessionInfo_t *sessionInfo); + +/** +* Retrieves the active frame buffer capture sessions statistics of a vGPU Instance +* +* For Maxwell &tm; or newer fully supported devices. +* +* @param vgpuInstance Identifier of the target vGPU instance +* @param fbcStats Reference to nvmlFBCStats_t structure containing NvFBC stats +* +* @return +* - \ref NVML_SUCCESS if \a fbcStats is fetched +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a fbcStats is NULL +* - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetFBCStats(nvmlVgpuInstance_t vgpuInstance, nvmlFBCStats_t *fbcStats); + +/** +* Retrieves information about active frame buffer capture sessions on a vGPU Instance. +* +* An array of active FBC sessions is returned in the caller-supplied buffer pointed at by \a sessionInfo. The +* array element count is passed in \a sessionCount, and \a sessionCount is used to return the number of sessions +* written to the buffer. +* +* If the supplied buffer is not large enough to accommodate the active session array, the function returns +* NVML_ERROR_INSUFFICIENT_SIZE, with the element count of nvmlFBCSessionInfo_t array required in \a sessionCount. +* To query the number of active FBC sessions, call this function with *sessionCount = 0. The code will return +* NVML_SUCCESS with number of active FBC sessions updated in *sessionCount. +* +* For Maxwell &tm; or newer fully supported devices. +* +* @note hResolution, vResolution, averageFPS and averageLatency data for a FBC session returned in \a sessionInfo may +* be zero if there are no new frames captured since the session started. +* +* @param vgpuInstance Identifier of the target vGPU instance +* @param sessionCount Reference to caller supplied array size, and returns the number of sessions. +* @param sessionInfo Reference in which to return the session information +* +* @return +* - \ref NVML_SUCCESS if \a sessionInfo is fetched +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a sessionCount is NULL. +* - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system +* - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a sessionCount is too small, array element count is returned in \a sessionCount +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetFBCSessions(nvmlVgpuInstance_t vgpuInstance, unsigned int *sessionCount, nvmlFBCSessionInfo_t *sessionInfo); + +/** +* 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. +* +* For Kepler &tm; or newer fully supported devices. +* +* @param vgpuInstance Identifier of the target vGPU instance +* @param gpuInstanceId GPU Instance ID +* +* @return +* - \ref NVML_SUCCESS successful completion +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a gpuInstanceId is NULL. +* - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetGpuInstanceId(nvmlVgpuInstance_t vgpuInstance, unsigned int *gpuInstanceId); + +/** +* 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. +* +* @param vgpuInstance Identifier of the target vGPU instance +* @param vgpuPciId Caller-supplied buffer to return vGPU PCI Id string +* @param length Size of the vgpuPciId buffer +* +* @return +* - \ref NVML_SUCCESS if vGPU PCI Id is sucessfully retrieved +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a vgpuPciId is NULL +* - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system +* - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running on the vGPU instance +* - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a length is too small, \a length is set to required length +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetGpuPciId(nvmlVgpuInstance_t vgpuInstance, char *vgpuPciId, unsigned int *length); + +/** +* Retrieve the requested capability for a given vGPU type. Refer to the \a nvmlVgpuCapability_t structure +* for the specific capabilities that can be queried. The return value in \a capResult should be treated as +* a boolean, with a non-zero value indicating that the capability is supported. +* +* For Maxwell &tm; or newer fully supported devices. +* +* @param vgpuTypeId Handle to vGPU type +* @param capability Specifies the \a nvmlVgpuCapability_t to be queried +* @param capResult A boolean for the queried capability indicating that feature is supported +* +* @return +* - \ref NVML_SUCCESS successful completion +* - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized +* - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuTypeId is invalid, or \a capability is invalid, or \a capResult is NULL +* - \ref NVML_ERROR_UNKNOWN on any unexpected error +*/ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetCapabilities(nvmlVgpuTypeId_t vgpuTypeId, nvmlVgpuCapability_t capability, unsigned int *capResult); + +/** + * 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 \ref nvmlConstants::NVML_DEVICE_UUID_BUFFER_SIZE. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param mdevUuid Pointer to caller-supplied buffer to hold MDEV UUID + * @param size Size of buffer in bytes + * + * @return + * - \ref NVML_SUCCESS successful completion + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_NOT_SUPPORTED on any hypervisor other than KVM + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a mdevUuid is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a size is too small + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetMdevUUID(nvmlVgpuInstance_t vgpuInstance, char *mdevUuid, unsigned int size); + +/** + * Query the currently creatable vGPU types on a specific GPU Instance. + * + * The function returns an array of vGPU types that can be created for a specified GPU instance. This array is stored + * in a caller-supplied buffer, with the buffer's element count passed through \a pVgpus->vgpuCount. The number of + * vGPU types written to the buffer is indicated by \a pVgpus->vgpuCount. If the buffer is too small to hold the vGPU + * type array, the function returns NVML_ERROR_INSUFFICIENT_SIZE and updates \a pVgpus->vgpuCount with the required + * element count. + * + * To determine the creatable vGPUs for a GPU Instance, invoke this function with \a pVgpus->vgpuCount set to 0 and + * \a pVgpus->vgpuTypeIds as NULL. This will result in NVML_ERROR_INSUFFICIENT_SIZE being returned, along with the + * count value in \a pVgpus->vgpuCount. + * + * The creatable vGPU types may differ over time, as there may be restrictions on what type of vGPUs can concurrently + * run on the device. + * + * @param gpuInstance The GPU instance handle + * @param pVgpus Pointer to the caller-provided structure of nvmlVgpuTypeIdInfo_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pVgpus is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If \a pVgpus->vgpuTypeIds buffer is small + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pVgpus is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetCreatableVgpus(nvmlGpuInstance_t gpuInstance, nvmlVgpuTypeIdInfo_t *pVgpus); + +/** + * Retrieve the maximum number of vGPU instances per GPU instance for given vGPU type + * + * @param pMaxInstance Pointer to the caller-provided structure of nvmlVgpuTypeMaxInstance_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a pMaxInstance is NULL or \a pMaxInstance->vgpuTypeId is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU or non-MIG vGPU type + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pMaxInstance is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuTypeGetMaxInstancesPerGpuInstance(nvmlVgpuTypeMaxInstance_t *pMaxInstance); + +/** + * Retrieve the active vGPU instances within a GPU instance. + * + * An array of active vGPU instances is returned in the caller-supplied buffer pointed + * at by \a pVgpuInstanceInfo->vgpuInstances. The array element count is passed in + * \a pVgpuInstanceInfo->vgpuCount, and \a pVgpuInstanceInfo->vgpuCount is used to return + * the number of vGPU instances written to the buffer. + * + * If the supplied buffer is not large enough to accommodate the vGPU instance array, + * the function returns NVML_ERROR_INSUFFICIENT_SIZE, with the element count of + * nvmlVgpuInstance_t array required in \a pVgpuInstanceInfo->vgpuCount. To query the + * number of active vGPU instances, call this function with pVgpuInstanceInfo->vgpuCount = 0 + * and pVgpuInstanceInfo->vgpuTypeIds = NULL. The code will return NVML_ERROR_INSUFFICIENT_SIZE, + * or NVML_SUCCESS if no vGPU Types are active. + * + * @param gpuInstance The GPU instance handle + * @param pVgpuInstanceInfo Pointer to the vGPU instance information structure \a nvmlActiveVgpuInstanceInfo_t + * + * @return + * - \ref NVML_SUCCESS Successful completion + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pVgpuInstanceInfo is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE \a pVgpuInstanceInfo->vgpuTypeIds buffer is too small, + * array element count is returned in \a pVgpuInstanceInfo->vgpuCount + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pVgpuInstanceInfo is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetActiveVgpus(nvmlGpuInstance_t gpuInstance, nvmlActiveVgpuInstanceInfo_t *pVgpuInstanceInfo); + +/** + * Set vGPU scheduler state for the given GPU instance + * + * %GB20X_OR_NEWER% + * + * Scheduler state and params will be allowed to set only when no VM is running within the GPU instance. + * In \a nvmlVgpuSchedulerState_t, IFF enableARRMode is enabled then provide the avgFactor and frequency + * as input. If enableARRMode is disabled then provide timeslice as input. + * + * The scheduler state change won't persist across module load/unload and GPU Instance creation/deletion. + * + * @param gpuInstance The GPU instance handle + * @param pScheduler Pointer to the caller-provided structure of nvmlVgpuSchedulerState_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pScheduler is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_RESET_REQUIRED If setting the state failed with fatal error, reboot is required + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU or if any vGPU instance exists + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pScheduler is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceSetVgpuSchedulerState(nvmlGpuInstance_t gpuInstance, nvmlVgpuSchedulerState_t *pScheduler); + +/** + * Returns the vGPU scheduler state for the given GPU instance. + * The information returned in \a nvmlVgpuSchedulerStateInfo_t is not relevant if the BEST EFFORT policy is set. + * + * %GB20X_OR_NEWER% + * + * @param gpuInstance The GPU instance handle + * @param pSchedulerStateInfo Reference in which \a pSchedulerStateInfo is returned + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler state is successfully obtained + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pSchedulerStateInfo is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pSchedulerStateInfo is invalid + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetVgpuSchedulerState(nvmlGpuInstance_t gpuInstance, nvmlVgpuSchedulerStateInfo_t *pSchedulerStateInfo); + +/** + * Returns the vGPU scheduler logs for the given GPU instance. + * \a pSchedulerLogInfo points to a caller-allocated structure to contain the logs. The number of elements returned will + * never exceed \a NVML_SCHEDULER_SW_MAX_LOG_ENTRIES. + * + * To get the entire logs, call the function atleast 5 times a second. + * + * %GB20X_OR_NEWER% + * + * @param gpuInstance The GPU instance handle + * @param pSchedulerLogInfo Reference in which \a pSchedulerLogInfo is written + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler logs are successfully obtained + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pSchedulerLogInfo is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pSchedulerLogInfo is invalid + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetVgpuSchedulerLog(nvmlGpuInstance_t gpuInstance, nvmlVgpuSchedulerLogInfo_t *pSchedulerLogInfo); + +/** + * Query the creatable vGPU placement ID of the vGPU type within a GPU instance. + * + * %GB20X_OR_NEWER% + * + * An array of creatable vGPU placement IDs for the vGPU type ID indicated by \a pCreatablePlacementInfo->vgpuTypeId + * is returned in the caller-supplied buffer of \a pCreatablePlacementInfo->placementIds. Memory needed for the + * placementIds array should be allocated based on maximum instances of a vGPU type per GPU instance which can be + * queried via \ref nvmlVgpuTypeGetMaxInstancesPerGpuInstance(). + * If the provided count by the caller is insufficient, the function will return NVML_ERROR_INSUFFICIENT_SIZE along with + * the number of required entries in \a pCreatablePlacementInfo->count. The caller should then reallocate a buffer with the size + * of pCreatablePlacementInfo->count * sizeof(pCreatablePlacementInfo->placementIds) and invoke the function again. + * The creatable vGPU placement IDs may differ over time, as there may be restrictions on what type of vGPU the + * vGPU instance is running. + * + * @param gpuInstance The GPU instance handle + * @param pCreatablePlacementInfo Pointer to the list of vGPU creatable placement structure \a nvmlVgpuCreatablePlacementInfo_t + * + * @return + * - \ref NVML_SUCCESS Successful completion + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pCreatablePlacementInfo is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If the buffer is small, element count is returned in \a pCreatablePlacementInfo->count + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pCreatablePlacementInfo is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU or vGPU heterogeneous mode is not enabled + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetVgpuTypeCreatablePlacements(nvmlGpuInstance_t gpuInstance, nvmlVgpuCreatablePlacementInfo_t *pCreatablePlacementInfo); + +/** + * Get the vGPU heterogeneous mode for the GPU instance. + * + * When in heterogeneous mode, a vGPU can concurrently host timesliced vGPUs with differing framebuffer sizes. + * + * On successful return, the function returns \a pHeterogeneousMode->mode with the current vGPU heterogeneous mode. + * \a pHeterogeneousMode->version is the version number of the structure nvmlVgpuHeterogeneousMode_t, the caller should + * set the correct version number to retrieve the vGPU heterogeneous mode. + * \a pHeterogeneousMode->mode can either be \ref NVML_FEATURE_ENABLED or \ref NVML_FEATURE_DISABLED. + * + * %GB20X_OR_NEWER% + * + * @param gpuInstance The GPU instance handle + * @param pHeterogeneousMode Pointer to the caller-provided structure of nvmlVgpuHeterogeneousMode_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, or \a pHeterogeneousMode is NULL + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU or not in MIG mode + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pHeterogeneousMode is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetVgpuHeterogeneousMode(nvmlGpuInstance_t gpuInstance, nvmlVgpuHeterogeneousMode_t *pHeterogeneousMode); + +/** + * Enable or disable vGPU heterogeneous mode for the GPU instance. + * + * When in heterogeneous mode, a vGPU can concurrently host timesliced vGPUs with differing framebuffer sizes. + * + * API would return an appropriate error code upon unsuccessful activation. For example, the heterogeneous mode + * set will fail with error \ref NVML_ERROR_IN_USE if any vGPU instance is active within the GPU instance. + * The caller of this API is expected to shutdown the vGPU VMs and retry setting the \a mode. + * On successful return, the function updates the vGPU heterogeneous mode with the user provided \a pHeterogeneousMode->mode. + * \a pHeterogeneousMode->version is the version number of the structure nvmlVgpuHeterogeneousMode_t, the caller should + * set the correct version number to set the vGPU heterogeneous mode. + * + * @param gpuInstance The GPU instance handle + * @param pHeterogeneousMode Pointer to the caller-provided structure of nvmlVgpuHeterogeneousMode_t + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is NULL or invalid, + * or \a pHeterogeneousMode is NULL or \a pHeterogeneousMode->mode is invalid + * or GPU Instance Id is invalid + * - \ref NVML_ERROR_IN_USE If the \a gpuInstance is in use + * - \ref NVML_ERROR_NOT_SUPPORTED If not on a vGPU host or an unsupported GPU + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a pHeterogeneousMode is invalid + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceSetVgpuHeterogeneousMode(nvmlGpuInstance_t gpuInstance, const nvmlVgpuHeterogeneousMode_t *pHeterogeneousMode); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlVgpuMigration vGPU Migration + * This chapter describes operations that are associated with vGPU Migration. + * @{ + */ +/***************************************************************************************************/ + +/** + * Structure representing range of vGPU versions. + */ +typedef struct nvmlVgpuVersion_st +{ + unsigned int minVersion; //!< Minimum vGPU version. + unsigned int maxVersion; //!< Maximum vGPU version. +} nvmlVgpuVersion_t; + +/** + * vGPU metadata structure. + */ +typedef struct nvmlVgpuMetadata_st +{ + unsigned int version; //!< Current version of the structure + unsigned int revision; //!< Current revision of the structure + nvmlVgpuGuestInfoState_t guestInfoState; //!< Current state of Guest-dependent fields + char guestDriverVersion[NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE]; //!< Version of driver installed in guest + char hostDriverVersion[NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE]; //!< Version of driver installed in host + unsigned int reserved[6]; //!< Reserved for internal use + unsigned int vgpuVirtualizationCaps; //!< vGPU virtualization capabilities bitfield + unsigned int guestVgpuVersion; //!< vGPU version of guest driver + unsigned int opaqueDataSize; //!< Size of opaque data field in bytes + char opaqueData[4]; //!< Opaque data +} nvmlVgpuMetadata_t; + +/** + * Physical GPU metadata structure + */ +typedef struct nvmlVgpuPgpuMetadata_st +{ + unsigned int version; //!< Current version of the structure + unsigned int revision; //!< Current revision of the structure + char hostDriverVersion[NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE]; //!< Host driver version + unsigned int pgpuVirtualizationCaps; //!< Pgpu virtualization capabilities bitfield + unsigned int reserved[5]; //!< Reserved for internal use + nvmlVgpuVersion_t hostSupportedVgpuRange; //!< vGPU version range supported by host driver + unsigned int opaqueDataSize; //!< Size of opaque data field in bytes + char opaqueData[4]; //!< Opaque data +} nvmlVgpuPgpuMetadata_t; + +/** + * vGPU VM compatibility codes + */ +typedef enum nvmlVgpuVmCompatibility_enum +{ + NVML_VGPU_VM_COMPATIBILITY_NONE = 0x0, //!< vGPU is not runnable + NVML_VGPU_VM_COMPATIBILITY_COLD = 0x1, //!< vGPU is runnable from a cold / powered-off state (ACPI S5) + NVML_VGPU_VM_COMPATIBILITY_HIBERNATE = 0x2, //!< vGPU is runnable from a hibernated state (ACPI S4) + NVML_VGPU_VM_COMPATIBILITY_SLEEP = 0x4, //!< vGPU is runnable from a sleeped state (ACPI S3) + NVML_VGPU_VM_COMPATIBILITY_LIVE = 0x8 //!< vGPU is runnable from a live/paused (ACPI S0) +} nvmlVgpuVmCompatibility_t; + +/** + * vGPU-pGPU compatibility limit codes + */ +typedef enum nvmlVgpuPgpuCompatibilityLimitCode_enum +{ + NVML_VGPU_COMPATIBILITY_LIMIT_NONE = 0x0, //!< Compatibility is not limited. + NVML_VGPU_COMPATIBILITY_LIMIT_HOST_DRIVER = 0x1, //!< ompatibility is limited by host driver version. + NVML_VGPU_COMPATIBILITY_LIMIT_GUEST_DRIVER = 0x2, //!< Compatibility is limited by guest driver version. + NVML_VGPU_COMPATIBILITY_LIMIT_GPU = 0x4, //!< Compatibility is limited by GPU hardware. + NVML_VGPU_COMPATIBILITY_LIMIT_OTHER = 0x80000000 //!< Compatibility is limited by an undefined factor. +} nvmlVgpuPgpuCompatibilityLimitCode_t; + +/** + * vGPU-pGPU compatibility structure + */ +typedef struct nvmlVgpuPgpuCompatibility_st +{ + nvmlVgpuVmCompatibility_t vgpuVmCompatibility; //!< Compatibility of vGPU VM. See \ref nvmlVgpuVmCompatibility_t + nvmlVgpuPgpuCompatibilityLimitCode_t compatibilityLimitCode; //!< Limiting factor for vGPU-pGPU compatibility. See \ref nvmlVgpuPgpuCompatibilityLimitCode_t +} nvmlVgpuPgpuCompatibility_t; + +/** + * 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. + * + * nvmlVgpuInstanceGetMetadata() 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. The current state of these dependent fields is reflected in the info structure's \ref nvmlVgpuGuestInfoState_t field. + * + * The VMM may choose to read and save the vGPU's VM info as persistent metadata associated with the VM, and provide + * it to Virtual GPU Manager when creating a vGPU for subsequent instances of the VM. + * + * The caller passes in a buffer via \a vgpuMetadata, with the size of the buffer in \a bufferSize. If the vGPU Metadata structure + * is too large to fit in the supplied buffer, the function returns NVML_ERROR_INSUFFICIENT_SIZE with the size needed + * in \a bufferSize. + * + * @param vgpuInstance vGPU instance handle + * @param vgpuMetadata Pointer to caller-supplied buffer into which vGPU metadata is written + * @param bufferSize Size of vgpuMetadata buffer + * + * @return + * - \ref NVML_SUCCESS vGPU metadata structure was successfully returned + * - \ref NVML_ERROR_INSUFFICIENT_SIZE vgpuMetadata buffer is too small, required size is returned in \a bufferSize + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a bufferSize is NULL or \a vgpuInstance is 0; if \a vgpuMetadata is NULL and the value of \a bufferSize is not 0. + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetMetadata(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuMetadata_t *vgpuMetadata, unsigned int *bufferSize); + +/** + * Returns a vGPU metadata structure for the physical GPU indicated by \a device. 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. + * + * The caller passes in a buffer via \a pgpuMetadata, with the size of the buffer in \a bufferSize. If the \a pgpuMetadata + * structure is too large to fit in the supplied buffer, the function returns NVML_ERROR_INSUFFICIENT_SIZE with the size needed + * in \a bufferSize. + * + * @param device The identifier of the target device + * @param pgpuMetadata Pointer to caller-supplied buffer into which \a pgpuMetadata is written + * @param bufferSize Pointer to size of \a pgpuMetadata buffer + * + * @return + * - \ref NVML_SUCCESS GPU metadata structure was successfully returned + * - \ref NVML_ERROR_INSUFFICIENT_SIZE pgpuMetadata buffer is too small, required size is returned in \a bufferSize + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a bufferSize is NULL or \a device is invalid; if \a pgpuMetadata is NULL and the value of \a bufferSize is not 0. + * - \ref NVML_ERROR_NOT_SUPPORTED vGPU is not supported by the system + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuMetadata(nvmlDevice_t device, nvmlVgpuPgpuMetadata_t *pgpuMetadata, unsigned int *bufferSize); + +/** + * Takes a vGPU instance metadata structure read from \ref nvmlVgpuInstanceGetMetadata(), and a vGPU metadata structure for a + * physical GPU read from \ref nvmlDeviceGetVgpuMetadata(), and returns compatibility information of the vGPU instance and the + * physical GPU. + * + * The caller passes in a buffer via \a compatibilityInfo, into which a compatibility information structure is written. The + * structure defines the states in which the vGPU / VM may be booted on the physical GPU. If the vGPU / VM compatibility + * with the physical GPU is limited, a limit code indicates the factor limiting compatability. + * (see \ref nvmlVgpuPgpuCompatibilityLimitCode_t for details). + * + * Note: vGPU compatibility does not take into account dynamic capacity conditions that may limit a system's ability to + * boot a given vGPU or associated VM. + * + * @param vgpuMetadata Pointer to caller-supplied vGPU metadata structure + * @param pgpuMetadata Pointer to caller-supplied GPU metadata structure + * @param compatibilityInfo Pointer to caller-supplied buffer to hold compatibility info + * + * @return + * - \ref NVML_SUCCESS vGPU metadata structure was successfully returned + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a vgpuMetadata or \a pgpuMetadata or \a bufferSize are NULL + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlGetVgpuCompatibility(nvmlVgpuMetadata_t *vgpuMetadata, nvmlVgpuPgpuMetadata_t *pgpuMetadata, nvmlVgpuPgpuCompatibility_t *compatibilityInfo); + +/** + * Returns the properties of the physical GPU indicated by the device in an ascii-encoded string format. + * + * The caller passes in a buffer via \a pgpuMetadata, with the size of the buffer in \a bufferSize. If the + * string is too large to fit in the supplied buffer, the function returns NVML_ERROR_INSUFFICIENT_SIZE with the size needed + * in \a bufferSize. + * + * @param device The identifier of the target device + * @param pgpuMetadata Pointer to caller-supplied buffer into which \a pgpuMetadata is written + * @param bufferSize Pointer to size of \a pgpuMetadata buffer + * + * @return + * - \ref NVML_SUCCESS GPU metadata structure was successfully returned + * - \ref NVML_ERROR_INSUFFICIENT_SIZE \a pgpuMetadata buffer is too small, required size is returned in \a bufferSize + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a bufferSize is NULL or \a device is invalid; if \a pgpuMetadata is NULL and the value of \a bufferSize is not 0. + * - \ref NVML_ERROR_NOT_SUPPORTED If vGPU is not supported by the system + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetPgpuMetadataString(nvmlDevice_t device, char *pgpuMetadata, unsigned int *bufferSize); + +/** + * Returns the vGPU Software scheduler logs. + * \a pSchedulerLog points to a caller-allocated structure to contain the logs. The number of elements returned will + * never exceed \a NVML_SCHEDULER_SW_MAX_LOG_ENTRIES. + * + * To get the entire logs, call the function atleast 5 times a second. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target \a device + * @param pSchedulerLog Reference in which \a pSchedulerLog is written + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler logs were successfully obtained + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a pSchedulerLog is NULL or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device not in vGPU host mode + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuSchedulerLog(nvmlDevice_t device, nvmlVgpuSchedulerLog_t *pSchedulerLog); + +/** + * Returns the vGPU scheduler state. + * The information returned in \a nvmlVgpuSchedulerGetState_t is not relevant if the BEST EFFORT policy is set. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target \a device + * @param pSchedulerState Reference in which \a pSchedulerState is returned + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler state is successfully obtained + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a pSchedulerState is NULL or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device not in vGPU host mode + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuSchedulerState(nvmlDevice_t device, nvmlVgpuSchedulerGetState_t *pSchedulerState); + +/** + * Returns the vGPU scheduler capabilities. + * The list of supported vGPU schedulers returned in \a nvmlVgpuSchedulerCapabilities_t is from + * the NVML_VGPU_SCHEDULER_POLICY_*. This list enumerates the supported scheduler policies + * if the engine is Graphics type. + * The other values in \a nvmlVgpuSchedulerCapabilities_t are also applicable if the engine is + * Graphics type. For other engine types, it is BEST EFFORT policy. + * If ARR is supported and enabled, scheduling frequency and averaging factor are applicable + * else timeSlice is applicable. + * + * For Pascal &tm; or newer fully supported devices. + * + * @param device The identifier of the target \a device + * @param pCapabilities Reference in which \a pCapabilities is written + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler capabilities were successfully obtained + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a pCapabilities is NULL or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED The API is not supported in current state or \a device not in vGPU host mode + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuSchedulerCapabilities(nvmlDevice_t device, nvmlVgpuSchedulerCapabilities_t *pCapabilities); + +/** + * Sets the vGPU scheduler state. + * + * For Pascal &tm; or newer fully supported devices. + * + * The scheduler state change won't persist across module load/unload. + * Scheduler state and params will be allowed to set only when no VM is running. + * In \a nvmlVgpuSchedulerSetState_t, IFF enableARRMode is enabled then + * provide avgFactorForARR and frequency as input. If enableARRMode is disabled + * then provide timeslice as input. + * + * @param device The identifier of the target \a device + * @param pSchedulerState vGPU \a pSchedulerState to set + * + * @return + * - \ref NVML_SUCCESS vGPU scheduler state has been successfully set + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a pSchedulerState is NULL or \a device is invalid + * - \ref NVML_ERROR_RESET_REQUIRED If setting \a pSchedulerState failed with fatal error, + * reboot is required to overcome from this error. + * - \ref NVML_ERROR_NOT_SUPPORTED If MIG is enabled or \a device not in vGPU host mode + * or if any vGPU instance currently exists on the \a device + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceSetVgpuSchedulerState(nvmlDevice_t device, nvmlVgpuSchedulerSetState_t *pSchedulerState); + +/* + * Virtual GPU (vGPU) version + * + * The NVIDIA vGPU Manager and the guest drivers are tagged with a range of supported vGPU versions. This determines the range of NVIDIA guest driver versions that + * are compatible for vGPU feature support with a given NVIDIA vGPU Manager. For vGPU feature support, the range of supported versions for the NVIDIA vGPU Manager + * and the guest driver must overlap. Otherwise, the guest driver fails to load in the VM. + * + * When the NVIDIA guest driver loads, either when the VM is booted or when the driver is installed or upgraded, a negotiation occurs between the guest driver + * and the NVIDIA vGPU Manager to select the highest mutually compatible vGPU version. The negotiated vGPU version stays the same across VM migration. + */ + +/** + * Query the ranges of supported vGPU versions. + * + * This function gets the linear range of supported vGPU versions that is preset for the NVIDIA vGPU Manager and the range set by an administrator. + * If the preset range has not been overridden by \ref nvmlSetVgpuVersion, both ranges are the same. + * + * The caller passes pointers to the following \ref nvmlVgpuVersion_t structures, into which the NVIDIA vGPU Manager writes the ranges: + * 1. \a supported structure that represents the preset range of vGPU versions supported by the NVIDIA vGPU Manager. + * 2. \a current structure that represents the range of supported vGPU versions set by an administrator. By default, this range is the same as the preset range. + * + * @param supported Pointer to the structure in which the preset range of vGPU versions supported by the NVIDIA vGPU Manager is written + * @param current Pointer to the structure in which the range of supported vGPU versions set by an administrator is written + * + * @return + * - \ref NVML_SUCCESS The vGPU version range structures were successfully obtained. + * - \ref NVML_ERROR_NOT_SUPPORTED The API is not supported. + * - \ref NVML_ERROR_INVALID_ARGUMENT The \a supported parameter or the \a current parameter is NULL. + * - \ref NVML_ERROR_UNKNOWN An error occurred while the data was being fetched. + */ +nvmlReturn_t DECLDIR nvmlGetVgpuVersion(nvmlVgpuVersion_t *supported, nvmlVgpuVersion_t *current); + +/** + * Override the preset range of vGPU versions supported by the NVIDIA vGPU Manager with a range set by an administrator. + * + * This function configures the NVIDIA vGPU Manager with a range of supported vGPU versions set by an administrator. This range must be a subset of the + * preset range that the NVIDIA vGPU Manager supports. The custom range set by an administrator takes precedence over the preset range and is advertised to + * the guest VM for negotiating the vGPU version. See \ref nvmlGetVgpuVersion for details of how to query the preset range of versions supported. + * + * This function takes a pointer to vGPU version range structure \ref nvmlVgpuVersion_t as input to override the preset vGPU version range that the NVIDIA vGPU Manager supports. + * + * After host system reboot or driver reload, the range of supported versions reverts to the range that is preset for the NVIDIA vGPU Manager. + * + * @note 1. The range set by the administrator must be a subset of the preset range that the NVIDIA vGPU Manager supports. Otherwise, an error is returned. + * 2. If the range of supported guest driver versions does not overlap the range set by the administrator, the guest driver fails to load. + * 3. If the range of supported guest driver versions overlaps the range set by the administrator, the guest driver will load with a negotiated + * vGPU version that is the maximum value in the overlapping range. + * 4. No VMs must be running on the host when this function is called. If a VM is running on the host, the call to this function fails. + * + * @param vgpuVersion Pointer to a caller-supplied range of supported vGPU versions. + * + * @return + * - \ref NVML_SUCCESS The preset range of supported vGPU versions was successfully overridden. + * - \ref NVML_ERROR_NOT_SUPPORTED The API is not supported. + * - \ref NVML_ERROR_IN_USE The range was not overridden because a VM is running on the host. + * - \ref NVML_ERROR_INVALID_ARGUMENT The \a vgpuVersion parameter specifies a range that is outside the range supported by the NVIDIA vGPU Manager or if \a vgpuVersion is NULL. + */ +nvmlReturn_t DECLDIR nvmlSetVgpuVersion(nvmlVgpuVersion_t *vgpuVersion); + +/** @} */ // @defgroup nvmlVgpuMigration vGPU Migration + +/***************************************************************************************************/ +/** @defgroup nvmlUtil vGPU Utilization and Accounting + * This chapter describes operations that are associated with vGPU Utilization and Accounting. + * @{ + */ +/***************************************************************************************************/ + +/** + * Retrieves current utilization for vGPUs on a physical GPU (device). + * + * For Kepler &tm; or newer fully supported devices. + * + * Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, and video decoder for vGPU instances running + * on a device. Utilization values are returned as an array of utilization sample structures in the caller-supplied buffer + * pointed at by \a utilizationSamples. One utilization sample structure is returned per vGPU instance, and includes the + * CPU timestamp at which the samples were recorded. Individual utilization values are returned as "unsigned int" values + * in nvmlValue_t unions. The function sets the caller-supplied \a sampleValType to NVML_VALUE_TYPE_UNSIGNED_INT to + * indicate the returned value type. + * + * To read utilization values, first determine the size of buffer required to hold the samples by invoking the function with + * \a utilizationSamples set to NULL. The function will return NVML_ERROR_INSUFFICIENT_SIZE, with the current vGPU instance + * count in \a vgpuInstanceSamplesCount, or NVML_SUCCESS if the current vGPU instance count is zero. The caller should allocate + * a buffer of size vgpuInstanceSamplesCount * sizeof(nvmlVgpuInstanceUtilizationSample_t). Invoke the function again with + * the allocated buffer passed in \a utilizationSamples, and \a vgpuInstanceSamplesCount set to the number of entries the + * buffer is sized for. + * + * On successful return, the function updates \a vgpuInstanceSampleCount with the number of vGPU utilization sample + * structures that were actually written. This may differ from a previously read value as vGPU instances are created or + * destroyed. + * + * lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * @param device The identifier for the target device + * @param lastSeenTimeStamp Return only samples with timestamp greater than lastSeenTimeStamp. + * @param sampleValType Pointer to caller-supplied buffer to hold the type of returned sample values + * @param vgpuInstanceSamplesCount Pointer to caller-supplied array size, and returns number of vGPU instances + * @param utilizationSamples Pointer to caller-supplied buffer in which vGPU utilization samples are returned + + * @return + * - \ref NVML_SUCCESS if utilization samples are successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a vgpuInstanceSamplesCount or \a sampleValType is + * NULL, or a sample count of 0 is passed with a non-NULL \a utilizationSamples + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if supplied \a vgpuInstanceSamplesCount is too small to return samples for all + * vGPU instances currently executing on the device + * - \ref NVML_ERROR_NOT_SUPPORTED if vGPU is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_FOUND if sample entries are not found + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuUtilization(nvmlDevice_t device, unsigned long long lastSeenTimeStamp, + nvmlValueType_t *sampleValType, unsigned int *vgpuInstanceSamplesCount, + nvmlVgpuInstanceUtilizationSample_t *utilizationSamples); + +/** + * Retrieves recent utilization for vGPU instances running on a physical GPU (device). + * + * For Kepler &tm; or newer fully supported devices. + * + * Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, video decoder, jpeg decoder, and OFA for vGPU + * instances running on a device. Utilization values are returned as an array of utilization sample structures in the caller-supplied + * buffer pointed at by \a vgpuUtilInfo->vgpuUtilArray. One utilization sample structure is returned per vGPU instance, and includes the + * CPU timestamp at which the samples were recorded. Individual utilization values are returned as "unsigned int" values + * in nvmlValue_t unions. The function sets the caller-supplied \a vgpuUtilInfo->sampleValType to NVML_VALUE_TYPE_UNSIGNED_INT to + * indicate the returned value type. + * + * To read utilization values, first determine the size of buffer required to hold the samples by invoking the function with + * \a vgpuUtilInfo->vgpuUtilArray set to NULL. The function will return NVML_ERROR_INSUFFICIENT_SIZE, with the current vGPU instance + * count in \a vgpuUtilInfo->vgpuInstanceCount, or NVML_SUCCESS if the current vGPU instance count is zero. The caller should allocate + * a buffer of size vgpuUtilInfo->vgpuInstanceCount * sizeof(nvmlVgpuInstanceUtilizationInfo_t). Invoke the function again with + * the allocated buffer passed in \a vgpuUtilInfo->vgpuUtilArray, and \a vgpuUtilInfo->vgpuInstanceCount set to the number of entries the + * buffer is sized for. + * + * On successful return, the function updates \a vgpuUtilInfo->vgpuInstanceCount with the number of vGPU utilization sample + * structures that were actually written. This may differ from a previously read value as vGPU instances are created or + * destroyed. + * + * \a vgpuUtilInfo->lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set \a vgpuUtilInfo->lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * @param device The identifier for the target device + * @param vgpuUtilInfo Pointer to the caller-provided structure of nvmlVgpuInstancesUtilizationInfo_t + + * @return + * - \ref NVML_SUCCESS If utilization samples are successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, \a vgpuUtilInfo is NULL, or \a vgpuUtilInfo->vgpuInstanceCount is 0 + * - \ref NVML_ERROR_NOT_SUPPORTED If vGPU is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a vgpuUtilInfo is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If \a vgpuUtilInfo->vgpuUtilArray is NULL, or the buffer size of vgpuUtilInfo->vgpuInstanceCount is too small. + * The caller should check the current vGPU instance count from the returned vgpuUtilInfo->vgpuInstanceCount, and call + * the function again with a buffer of size vgpuUtilInfo->vgpuInstanceCount * sizeof(nvmlVgpuInstanceUtilizationInfo_t) + * - \ref NVML_ERROR_NOT_FOUND If sample entries are not found + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuInstancesUtilizationInfo(nvmlDevice_t device, + nvmlVgpuInstancesUtilizationInfo_t *vgpuUtilInfo); + +/** + * Retrieves current utilization for processes running on vGPUs on a physical GPU (device). + * + * For Maxwell &tm; or newer fully supported devices. + * + * Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, and video decoder for processes running on + * vGPU instances active on a device. Utilization values are returned as an array of utilization sample structures in the + * caller-supplied buffer pointed at by \a utilizationSamples. One utilization sample structure is returned per process running + * on vGPU instances, that had some 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 int" values. + * + * To read utilization values, first determine the size of buffer required to hold the samples by invoking the function with + * \a utilizationSamples set to NULL. The function will return NVML_ERROR_INSUFFICIENT_SIZE, with the current vGPU instance + * count in \a vgpuProcessSamplesCount. The caller should allocate a buffer of size + * vgpuProcessSamplesCount * sizeof(nvmlVgpuProcessUtilizationSample_t). Invoke the function again with + * the allocated buffer passed in \a utilizationSamples, and \a vgpuProcessSamplesCount set to the number of entries the + * buffer is sized for. + * + * On successful return, the function updates \a vgpuSubProcessSampleCount with the number of vGPU sub process utilization sample + * structures that were actually written. This may differ from a previously read value depending on the number of processes that are active + * in any given sample period. + * + * lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * @param device The identifier for the target device + * @param lastSeenTimeStamp Return only samples with timestamp greater than lastSeenTimeStamp. + * @param vgpuProcessSamplesCount Pointer to caller-supplied array size, and returns number of processes running on vGPU instances + * @param utilizationSamples Pointer to caller-supplied buffer in which vGPU sub process utilization samples are returned + + * @return + * - \ref NVML_SUCCESS if utilization samples are successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a vgpuProcessSamplesCount or a sample count of 0 is + * passed with a non-NULL \a utilizationSamples + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if supplied \a vgpuProcessSamplesCount is too small to return samples for all + * vGPU instances currently executing on the device + * - \ref NVML_ERROR_NOT_SUPPORTED if vGPU is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_FOUND if sample entries are not found + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuProcessUtilization(nvmlDevice_t device, unsigned long long lastSeenTimeStamp, + unsigned int *vgpuProcessSamplesCount, + nvmlVgpuProcessUtilizationSample_t *utilizationSamples); + +/** + * Retrieves recent utilization for processes running on vGPU instances on a physical GPU (device). + * + * For Maxwell &tm; or newer fully supported devices. + * + * Reads recent utilization of GPU SM (3D/Compute), framebuffer, video encoder, video decoder, jpeg decoder, and OFA for processes running + * on vGPU instances active on a device. Utilization values are returned as an array of utilization sample structures in the caller-supplied + * buffer pointed at by \a vgpuProcUtilInfo->vgpuProcUtilArray. One utilization sample structure is returned per process running + * on vGPU instances, that had some 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 int" values. + * + * To read utilization values, first determine the size of buffer required to hold the samples by invoking the function with + * \a vgpuProcUtilInfo->vgpuProcUtilArray set to NULL. The function will return NVML_ERROR_INSUFFICIENT_SIZE, with the current processes' count + * running on vGPU instances in \a vgpuProcUtilInfo->vgpuProcessCount. The caller should allocate a buffer of size + * vgpuProcUtilInfo->vgpuProcessCount * sizeof(nvmlVgpuProcessUtilizationSample_t). Invoke the function again with the allocated buffer passed + * in \a vgpuProcUtilInfo->vgpuProcUtilArray, and \a vgpuProcUtilInfo->vgpuProcessCount set to the number of entries the buffer is sized for. + * + * On successful return, the function updates \a vgpuProcUtilInfo->vgpuProcessCount with the number of vGPU sub process utilization sample + * structures that were actually written. This may differ from a previously read value depending on the number of processes that are active + * in any given sample period. + * + * vgpuProcUtilInfo->lastSeenTimeStamp represents the CPU timestamp in microseconds at which utilization samples were last read. Set it to 0 + * to read utilization based on all the samples maintained by the driver's internal sample buffer. Set vgpuProcUtilInfo->lastSeenTimeStamp + * to a timeStamp retrieved from a previous query to read utilization since the previous query. + * + * @param device The identifier for the target device + * @param vgpuProcUtilInfo Pointer to the caller-provided structure of nvmlVgpuProcessesUtilizationInfo_t + + * @return + * - \ref NVML_SUCCESS If utilization samples are successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid, or \a vgpuProcUtilInfo is null + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the version of \a vgpuProcUtilInfo is invalid + * - \ref NVML_ERROR_INSUFFICIENT_SIZE If \a vgpuProcUtilInfo->vgpuProcUtilArray is null, or supplied \a vgpuProcUtilInfo->vgpuProcessCount + * is too small to return samples for all processes on vGPU instances currently executing on the device. + * The caller should check the current processes count from the returned \a vgpuProcUtilInfo->vgpuProcessCount, + * and call the function again with a buffer of size + * vgpuProcUtilInfo->vgpuProcessCount * sizeof(nvmlVgpuProcessUtilizationSample_t) + * - \ref NVML_ERROR_NOT_SUPPORTED If vGPU is not supported by the device + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_NOT_FOUND If sample entries are not found + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetVgpuProcessesUtilizationInfo(nvmlDevice_t device, nvmlVgpuProcessesUtilizationInfo_t *vgpuProcUtilInfo); + +/** + * Queries the state of per process accounting mode on vGPU. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance The identifier of the target vGPU instance + * @param mode Reference in which to return the current accounting mode + * + * @return + * - \ref NVML_SUCCESS if the mode has been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a mode is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_NOT_SUPPORTED if the vGPU doesn't support this feature + * - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running on the vGPU instance + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetAccountingMode(nvmlVgpuInstance_t vgpuInstance, nvmlEnableState_t *mode); + +/** + * Queries list of processes running on vGPU that can be queried for accounting stats. The list of processes + * returned can be in running or terminated state. + * + * For Maxwell &tm; or newer fully supported devices. + * + * To just query the maximum number of processes that can be queried, call this function with *count = 0 and + * pids=NULL. The return code will be NVML_ERROR_INSUFFICIENT_SIZE, or NVML_SUCCESS if list is empty. + * + * For more details see \ref nvmlVgpuInstanceGetAccountingStats. + * + * @note In case of PID collision some processes might not be accessible before the circular buffer is full. + * + * @param vgpuInstance The identifier of the target vGPU instance + * @param count Reference in which to provide the \a pids array size, and + * to return the number of elements ready to be queried + * @param pids Reference in which to return list of process ids + * + * @return + * - \ref NVML_SUCCESS if pids were successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a count is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_NOT_SUPPORTED if the vGPU doesn't support this feature or accounting mode is disabled + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if \a count is too small (\a count is set to expected value) + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + * + * @see nvmlVgpuInstanceGetAccountingPids + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetAccountingPids(nvmlVgpuInstance_t vgpuInstance, unsigned int *count, unsigned int *pids); + +/** + * Queries process's accounting stats. + * + * For Maxwell &tm; or newer fully supported devices. + * + * Accounting stats capture GPU utilization and other statistics across the lifetime of a process, and + * can be queried during life time of the process or after its termination. + * The time field in \ref nvmlAccountingStats_t is reported as 0 during the lifetime of the process and + * updated to actual running time after its termination. + * Accounting stats are kept in a circular buffer, newly created processes overwrite information about old + * processes. + * + * See \ref nvmlAccountingStats_t for description of each returned metric. + * List of processes that can be queried can be retrieved from \ref nvmlVgpuInstanceGetAccountingPids. + * + * @note Accounting Mode needs to be on. See \ref nvmlVgpuInstanceGetAccountingMode. + * @note Only compute and graphics applications stats can be queried. Monitoring applications stats can't be + * queried since they don't contribute to GPU utilization. + * @note In case of pid collision stats of only the latest process (that terminated last) will be reported + * + * @param vgpuInstance The identifier of the target vGPU instance + * @param pid Process Id of the target process to query stats for + * @param stats Reference in which to return the process's accounting stats + * + * @return + * - \ref NVML_SUCCESS if stats have been successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a stats is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * or \a stats is not found + * - \ref NVML_ERROR_NOT_SUPPORTED if the vGPU doesn't support this feature or accounting mode is disabled + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetAccountingStats(nvmlVgpuInstance_t vgpuInstance, unsigned int pid, nvmlAccountingStats_t *stats); + +/** + * Clears accounting information of the vGPU instance that have already terminated. + * + * For Maxwell &tm; or newer fully supported devices. + * Requires root/admin permissions. + * + * @note Accounting Mode needs to be on. See \ref nvmlVgpuInstanceGetAccountingMode. + * @note Only compute and graphics applications stats are reported and can be cleared since monitoring applications + * stats don't contribute to GPU utilization. + * + * @param vgpuInstance The identifier of the target vGPU instance + * + * @return + * - \ref NVML_SUCCESS if accounting information has been cleared + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is invalid + * - \ref NVML_ERROR_NO_PERMISSION if the user doesn't have permission to perform this operation + * - \ref NVML_ERROR_NOT_SUPPORTED if the vGPU doesn't support this feature or accounting mode is disabled + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceClearAccountingPids(nvmlVgpuInstance_t vgpuInstance); + +/** + * Query the license information of the vGPU instance. + * + * For Maxwell &tm; or newer fully supported devices. + * + * @param vgpuInstance Identifier of the target vGPU instance + * @param licenseInfo Pointer to vGPU license information structure + * + * @return + * - \ref NVML_SUCCESS if information is successfully retrieved + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a vgpuInstance is 0, or \a licenseInfo is NULL + * - \ref NVML_ERROR_NOT_FOUND if \a vgpuInstance does not match a valid active vGPU instance on the system + * - \ref NVML_ERROR_DRIVER_NOT_LOADED if NVIDIA driver is not running on the vGPU instance + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetLicenseInfo_v2(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuLicenseInfo_t *licenseInfo); +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlExcludedGpuQueries Excluded GPU Queries + * This chapter describes NVML operations that are associated with excluded GPUs. + * @{ + */ +/***************************************************************************************************/ + +/** + * Excluded GPU device information + **/ +typedef struct nvmlExcludedDeviceInfo_st +{ + nvmlPciInfo_t pciInfo; //!< The PCI information for the excluded GPU + char uuid[NVML_DEVICE_UUID_BUFFER_SIZE]; //!< The ASCII string UUID for the excluded GPU +} nvmlExcludedDeviceInfo_t; + + /** + * Retrieves the number of excluded GPU devices in the system. + * + * For all products. + * + * @param deviceCount Reference in which to return the number of excluded devices + * + * @return + * - \ref NVML_SUCCESS if \a deviceCount has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a deviceCount is NULL + */ +nvmlReturn_t DECLDIR nvmlGetExcludedDeviceCount(unsigned int *deviceCount); + +/** + * Acquire the device information for an excluded GPU device, based on its index. + * + * For all products. + * + * Valid indices are derived from the \a deviceCount returned by + * \ref nvmlGetExcludedDeviceCount(). For example, if \a deviceCount is 2 the valid indices + * are 0 and 1, corresponding to GPU 0 and GPU 1. + * + * @param index The index of the target GPU, >= 0 and < \a deviceCount + * @param info Reference in which to return the device information + * + * @return + * - \ref NVML_SUCCESS if \a device has been set + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a index is invalid or \a info is NULL + * + * @see nvmlGetExcludedDeviceCount + */ +nvmlReturn_t DECLDIR nvmlGetExcludedDeviceInfoByIndex(unsigned int index, nvmlExcludedDeviceInfo_t *info); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlGPUPRMAccess PRM Access + * This chapter describes NVML operations that are associated with PRM register reads + * @{ + */ +/***************************************************************************************************/ + +#define NVML_PRM_DATA_MAX_SIZE 496 +/** + * Main PRM input structure + */ +typedef struct +{ + /* I/O parameters */ + unsigned dataSize; //!< Size of the input TLV data. + unsigned status; //!< OUT: status of the PRM command + union { + /* Input data in TLV format */ + unsigned char inData[NVML_PRM_DATA_MAX_SIZE]; //!< IN: Input data in TLV format + /* Output data in TLV format */ + unsigned char outData[NVML_PRM_DATA_MAX_SIZE]; //!< OUT: Output PRM data in TLV format + }; +} nvmlPRMTLV_v1_t; + +/** + * Read or write a GPU PRM register. The input is assumed to be in TLV format in + * network byte order. + * + * %BLACKWELL_OR_NEWER% + * + * Supported on Linux only. + * + * @param device Identifer of target GPU device + * @param buffer Structure holding the input data in TLV format as well as + * the PRM register contents in TLV format (in the case of a successful + * read operation). + * Note: the input data and any returned data shall be in network byte order. + * + * @return + * - \ref NVML_SUCCESS on success + * - \ref NVML_ERROR_INVALID_ARGUMENT if \p device or \p buffer are invalid + * - \ref NVML_ERROR_NO_PERMISSION if user does not have permission to perform this operation + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the version specified in \p buffer is not supported + */ +nvmlReturn_t DECLDIR nvmlDeviceReadWritePRM_v1(nvmlDevice_t device, nvmlPRMTLV_v1_t *buffer); + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup nvmlMultiInstanceGPU Multi Instance GPU Management + * This chapter describes NVML operations that are associated with Multi Instance GPU management. + * @{ + */ +/***************************************************************************************************/ + +/** + * Disable Multi Instance GPU mode. + */ +#define NVML_DEVICE_MIG_DISABLE 0x0 + +/** + * Enable Multi Instance GPU mode. + */ +#define NVML_DEVICE_MIG_ENABLE 0x1 + +/** + * GPU instance profiles. + * + * These macros should be passed to \ref nvmlDeviceGetGpuInstanceProfileInfo to retrieve the + * detailed information about a GPU instance such as profile ID, engine counts. + */ +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE 0x0 +#define NVML_GPU_INSTANCE_PROFILE_2_SLICE 0x1 +#define NVML_GPU_INSTANCE_PROFILE_3_SLICE 0x2 +#define NVML_GPU_INSTANCE_PROFILE_4_SLICE 0x3 +#define NVML_GPU_INSTANCE_PROFILE_7_SLICE 0x4 +#define NVML_GPU_INSTANCE_PROFILE_8_SLICE 0x5 +#define NVML_GPU_INSTANCE_PROFILE_6_SLICE 0x6 +// 1_SLICE profile with at least one (if supported at all) of Decoder, Encoder, JPEG, OFA engines. +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV1 0x7 +// 2_SLICE profile with at least one (if supported at all) of Decoder, Encoder, JPEG, OFA engines. +#define NVML_GPU_INSTANCE_PROFILE_2_SLICE_REV1 0x8 +// 1_SLICE profile with twice the amount of memory resources. +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE_REV2 0x9 +// 1_SLICE gfx capable profile +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE_GFX 0x0A +// 2_SLICE gfx capable profile +#define NVML_GPU_INSTANCE_PROFILE_2_SLICE_GFX 0x0B +// 4_SLICE gfx capable profile +#define NVML_GPU_INSTANCE_PROFILE_4_SLICE_GFX 0x0C +// 1_SLICE profile with none of Decode, Encoder, JPEG, OFA engines. +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE_NO_ME 0x0D +// 2_SLICE profile with none of Decode, Encoder, JPEG, OFA engines. +#define NVML_GPU_INSTANCE_PROFILE_2_SLICE_NO_ME 0x0E +// 1_SLICE profile with all of GPU Decode, Encoder, JPEG, OFA engines. +// Allocation of instance of this profile prevents allocation of +// all but _NO_ME profiles. +#define NVML_GPU_INSTANCE_PROFILE_1_SLICE_ALL_ME 0x0F +// 2_SLICE profile with all of GPU Decode, Encoder, JPEG, OFA engines. +// Allocation of instance of this profile prevents allocation of +// all but _NO_ME profiles. +#define NVML_GPU_INSTANCE_PROFILE_2_SLICE_ALL_ME 0x10 +#define NVML_GPU_INSTANCE_PROFILE_COUNT 0x11 + +/** + * MIG GPU instance profile capability. + * + * Bit field values representing MIG profile capabilities + * \ref nvmlGpuInstanceProfileInfo_v3_t.capabilities + */ +#define NVML_GPU_INSTANCE_PROFILE_CAPS_P2P 0x1 +#define NVML_GPU_INTSTANCE_PROFILE_CAPS_P2P 0x1 //!< Deprecated, do not use +#define NVML_GPU_INSTANCE_PROFILE_CAPS_GFX 0x2 + +/** + * MIG compute instance profile capability. + * + * Bit field values representing MIG profile capabilities + * \ref nvmlComputeInstanceProfileInfo_v3_t.capabilities + */ +#define NVML_COMPUTE_INSTANCE_PROFILE_CAPS_GFX 0x1 + +typedef struct nvmlGpuInstancePlacement_st +{ + unsigned int start; //!< Index of first occupied memory slice + unsigned int size; //!< Number of memory slices occupied +} nvmlGpuInstancePlacement_t; + +/** + * GPU instance profile information. + */ +typedef struct nvmlGpuInstanceProfileInfo_st +{ + unsigned int id; //!< Unique profile ID within the device + unsigned int isP2pSupported; //!< Peer-to-Peer support + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< GPU instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int copyEngineCount; //!< Copy Engine count + unsigned int decoderCount; //!< Decoder Engine count + unsigned int encoderCount; //!< Encoder Engine count + unsigned int jpegCount; //!< JPEG Engine count + unsigned int ofaCount; //!< OFA Engine count + unsigned long long memorySizeMB; //!< Memory size in MBytes +} nvmlGpuInstanceProfileInfo_t; + +/** + * GPU instance profile information (v2). + * + * Version 2 adds the \ref nvmlGpuInstanceProfileInfo_v2_t.version field + * to the start of the structure, and the \ref nvmlGpuInstanceProfileInfo_v2_t.name + * field to the end. This structure is not backwards-compatible with + * \ref nvmlGpuInstanceProfileInfo_t. + */ +typedef struct nvmlGpuInstanceProfileInfo_v2_st +{ + unsigned int version; //!< Structure version identifier (set to \ref nvmlGpuInstanceProfileInfo_v2) + unsigned int id; //!< Unique profile ID within the device + unsigned int isP2pSupported; //!< Peer-to-Peer support + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< GPU instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int copyEngineCount; //!< Copy Engine count + unsigned int decoderCount; //!< Decoder Engine count + unsigned int encoderCount; //!< Encoder Engine count + unsigned int jpegCount; //!< JPEG Engine count + unsigned int ofaCount; //!< OFA Engine count + unsigned long long memorySizeMB; //!< Memory size in MBytes + char name[NVML_DEVICE_NAME_V2_BUFFER_SIZE]; //!< Profile name +} nvmlGpuInstanceProfileInfo_v2_t; + +/** + * Version identifier value for \ref nvmlGpuInstanceProfileInfo_v2_t.version. + */ +#define nvmlGpuInstanceProfileInfo_v2 NVML_STRUCT_VERSION(GpuInstanceProfileInfo, 2) + +/** + * GPU instance profile information (v3). + * + * Version 3 removes isP2pSupported field and adds the \ref nvmlGpuInstanceProfileInfo_v3_t.capabilities + * field \ref nvmlGpuInstanceProfileInfo_t. + */ +typedef struct nvmlGpuInstanceProfileInfo_v3_st +{ + unsigned int version; //!< Structure version identifier (set to \ref nvmlGpuInstanceProfileInfo_v3) + unsigned int id; //!< Unique profile ID within the device + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< GPU instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int copyEngineCount; //!< Copy Engine count + unsigned int decoderCount; //!< Decoder Engine count + unsigned int encoderCount; //!< Encoder Engine count + unsigned int jpegCount; //!< JPEG Engine count + unsigned int ofaCount; //!< OFA Engine count + unsigned long long memorySizeMB; //!< Memory size in MBytes + char name[NVML_DEVICE_NAME_V2_BUFFER_SIZE]; //!< Profile name + unsigned int capabilities; //!< Additional capabilities +} nvmlGpuInstanceProfileInfo_v3_t; + +/** + * Version identifier value for \ref nvmlGpuInstanceProfileInfo_v3_t.version. + */ +#define nvmlGpuInstanceProfileInfo_v3 NVML_STRUCT_VERSION(GpuInstanceProfileInfo, 3) + +typedef struct nvmlGpuInstanceInfo_st +{ + nvmlDevice_t device; //!< Parent device + unsigned int id; //!< Unique instance ID within the device + unsigned int profileId; //!< Unique profile ID within the device + nvmlGpuInstancePlacement_t placement; //!< Placement for this instance +} nvmlGpuInstanceInfo_t; + +/** + * Compute instance profiles. + * + * These macros should be passed to \ref nvmlGpuInstanceGetComputeInstanceProfileInfo to retrieve the + * detailed information about a compute instance such as profile ID, engine counts + */ +#define NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE 0x0 +#define NVML_COMPUTE_INSTANCE_PROFILE_2_SLICE 0x1 +#define NVML_COMPUTE_INSTANCE_PROFILE_3_SLICE 0x2 +#define NVML_COMPUTE_INSTANCE_PROFILE_4_SLICE 0x3 +#define NVML_COMPUTE_INSTANCE_PROFILE_7_SLICE 0x4 +#define NVML_COMPUTE_INSTANCE_PROFILE_8_SLICE 0x5 +#define NVML_COMPUTE_INSTANCE_PROFILE_6_SLICE 0x6 +#define NVML_COMPUTE_INSTANCE_PROFILE_1_SLICE_REV1 0x7 +#define NVML_COMPUTE_INSTANCE_PROFILE_COUNT 0x8 + +#define NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_SHARED 0x0 //!< All the engines except multiprocessors would be shared +#define NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_COUNT 0x1 + +typedef struct nvmlComputeInstancePlacement_st +{ + unsigned int start; //!< Index of first occupied compute slice + unsigned int size; //!< Number of compute slices occupied +} nvmlComputeInstancePlacement_t; + +/** + * Compute instance profile information. + */ +typedef struct nvmlComputeInstanceProfileInfo_st +{ + unsigned int id; //!< Unique profile ID within the GPU instance + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< Compute instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int sharedCopyEngineCount; //!< Shared Copy Engine count + unsigned int sharedDecoderCount; //!< Shared Decoder Engine count + unsigned int sharedEncoderCount; //!< Shared Encoder Engine count + unsigned int sharedJpegCount; //!< Shared JPEG Engine count + unsigned int sharedOfaCount; //!< Shared OFA Engine count +} nvmlComputeInstanceProfileInfo_t; + +/** + * Compute instance profile information (v2). + * + * Version 2 adds the \ref nvmlComputeInstanceProfileInfo_v2_t.version field + * to the start of the structure, and the \ref nvmlComputeInstanceProfileInfo_v2_t.name + * field to the end. This structure is not backwards-compatible with + * \ref nvmlComputeInstanceProfileInfo_t. + */ +typedef struct nvmlComputeInstanceProfileInfo_v2_st +{ + unsigned int version; //!< Structure version identifier (set to \ref nvmlComputeInstanceProfileInfo_v2) + unsigned int id; //!< Unique profile ID within the GPU instance + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< Compute instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int sharedCopyEngineCount; //!< Shared Copy Engine count + unsigned int sharedDecoderCount; //!< Shared Decoder Engine count + unsigned int sharedEncoderCount; //!< Shared Encoder Engine count + unsigned int sharedJpegCount; //!< Shared JPEG Engine count + unsigned int sharedOfaCount; //!< Shared OFA Engine count + char name[NVML_DEVICE_NAME_V2_BUFFER_SIZE]; //!< Profile name +} nvmlComputeInstanceProfileInfo_v2_t; + +/** + * Version identifier value for \ref nvmlComputeInstanceProfileInfo_v2_t.version. + */ +#define nvmlComputeInstanceProfileInfo_v2 NVML_STRUCT_VERSION(ComputeInstanceProfileInfo, 2) + +/** + * Compute instance profile information (v3). + * + * Version 3 adds the \ref nvmlComputeInstanceProfileInfo_v3_t.capabilities field + * \ref nvmlComputeInstanceProfileInfo_t. + */ +typedef struct nvmlComputeInstanceProfileInfo_v3_st +{ + unsigned int version; //!< Structure version identifier (set to \ref nvmlComputeInstanceProfileInfo_v3) + unsigned int id; //!< Unique profile ID within the GPU instance + unsigned int sliceCount; //!< GPU Slice count + unsigned int instanceCount; //!< Compute instance count + unsigned int multiprocessorCount; //!< Streaming Multiprocessor count + unsigned int sharedCopyEngineCount; //!< Shared Copy Engine count + unsigned int sharedDecoderCount; //!< Shared Decoder Engine count + unsigned int sharedEncoderCount; //!< Shared Encoder Engine count + unsigned int sharedJpegCount; //!< Shared JPEG Engine count + unsigned int sharedOfaCount; //!< Shared OFA Engine count + char name[NVML_DEVICE_NAME_V2_BUFFER_SIZE]; //!< Profile name + unsigned int capabilities; //!< Additional capabilities +} nvmlComputeInstanceProfileInfo_v3_t; + +/** + * Version identifier value for \ref nvmlComputeInstanceProfileInfo_v3_t.version. + */ +#define nvmlComputeInstanceProfileInfo_v3 NVML_STRUCT_VERSION(ComputeInstanceProfileInfo, 3) + +typedef struct nvmlComputeInstanceInfo_st +{ + nvmlDevice_t device; //!< Parent device + nvmlGpuInstance_t gpuInstance; //!< Parent GPU instance + unsigned int id; //!< Unique instance ID within the GPU instance + unsigned int profileId; //!< Unique profile ID within the GPU instance + nvmlComputeInstancePlacement_t placement; //!< Placement for this instance within the GPU instance's compute slice range {0, sliceCount} +} nvmlComputeInstanceInfo_t; + +typedef struct +{ + struct nvmlComputeInstance_st* handle; +} nvmlComputeInstance_t; + +/** + * Set MIG mode for the device. + * + * For Ampere &tm; or newer fully supported devices. + * Requires root user. + * + * This mode determines whether a GPU instance can be created. + * + * This API may unbind or reset the device to activate the requested mode. Thus, the attributes associated with the + * device, such as minor number, might change. The caller of this API is expected to query such attributes again. + * + * On certain platforms like pass-through virtualization, where reset functionality may not be exposed directly, VM + * reboot is required. \a activationStatus would return \ref NVML_ERROR_RESET_REQUIRED for such cases. + * + * \a activationStatus would return the appropriate error code upon unsuccessful activation. For example, if device + * unbind fails because the device isn't idle, \ref NVML_ERROR_IN_USE would be returned. The caller of this API + * is expected to idle the device and retry setting the \a mode. + * + * @note On Windows, only disabling MIG mode is supported. \a activationStatus would return \ref + * NVML_ERROR_NOT_SUPPORTED as GPU reset is not supported on Windows through this API. + * + * @param device The identifier of the target device + * @param mode The mode to be set, \ref NVML_DEVICE_MIG_DISABLE or + * \ref NVML_DEVICE_MIG_ENABLE + * @param activationStatus The activationStatus status + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device,\a mode or \a activationStatus are invalid + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support MIG mode + */ +nvmlReturn_t DECLDIR nvmlDeviceSetMigMode(nvmlDevice_t device, unsigned int mode, nvmlReturn_t *activationStatus); + +/** + * Get MIG mode for the device. + * + * For Ampere &tm; 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. + * + * @param device The identifier of the target device + * @param currentMode Returns the current mode, \ref NVML_DEVICE_MIG_DISABLE or + * \ref NVML_DEVICE_MIG_ENABLE + * @param pendingMode Returns the pending mode, \ref NVML_DEVICE_MIG_DISABLE or + * \ref NVML_DEVICE_MIG_ENABLE + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a currentMode or \a pendingMode are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support MIG mode + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMigMode(nvmlDevice_t device, unsigned int *currentMode, unsigned int *pendingMode); + +/** + * Get GPU instance profile information + * + * Information provided by this API is immutable throughout the lifetime of a MIG mode. + * + * @note This API can be used to enumerate all MIG profiles supported by NVML in a forward compatible + * way by invoking it on \a profile values starting from 0, until the API returns \ref NVML_ERROR_INVALID_ARGUMENT. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param profile One of the NVML_GPU_INSTANCE_PROFILE_* + * @param info Returns detailed profile information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profile or \a info are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support MIG or \a profile isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceProfileInfo(nvmlDevice_t device, unsigned int profile, + nvmlGpuInstanceProfileInfo_t *info); + +/** + * Versioned wrapper around \ref nvmlDeviceGetGpuInstanceProfileInfo that accepts a versioned + * \ref nvmlGpuInstanceProfileInfo_v2_t or later output structure. + * + * @note The caller must set the \ref nvmlGpuInstanceProfileInfo_v2_t.version field to the + * appropriate version prior to calling this function. For example: + * \code + * nvmlGpuInstanceProfileInfo_v2_t profileInfo = + * { .version = nvmlGpuInstanceProfileInfo_v2 }; + * nvmlReturn_t result = nvmlDeviceGetGpuInstanceProfileInfoV(device, + * profile, + * &profileInfo); + * \endcode + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param profile One of the NVML_GPU_INSTANCE_PROFILE_* + * @param info Returns detailed profile information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profile, \a info, or \a info->version are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or \a profile isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceProfileInfoV(nvmlDevice_t device, unsigned int profile, + nvmlGpuInstanceProfileInfo_v2_t *info); + +/** + * GPU instance profile query function that accepts profile ID, instead of profile name. + * It accepts a versioned \ref nvmlGpuInstanceProfileInfo_v2_t or later output structure. + * + * @note The caller must set the \ref nvmlGpuInstanceProfileInfo_v2_t.version field to the + * appropriate version prior to calling this function. For example: + * \code + * nvmlGpuInstanceProfileInfo_v2_t profileInfo = + * { .version = nvmlGpuInstanceProfileInfo_v2 }; + * nvmlReturn_t result = nvmlDeviceGetGpuInstanceProfileInfoV(device, + * profile, + * &profileInfo); + * \endcode + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device The identifier of the target device + * @param profileId One of the profile IDs. + * @param info Returns detailed profile information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profileId, \a info, or \a info->version are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or \a profile isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceProfileInfoByIdV(nvmlDevice_t device, unsigned int profileId, + nvmlGpuInstanceProfileInfo_v2_t *info); + +/** + * Get GPU instance placements. + * + * A placement represents the location of a GPU instance within a device. This API only returns all the possible + * placements for the given profile regardless of whether MIG is enabled or not. + * A created GPU instance occupies memory slices described by its placement. Creation of new GPU instance will + * fail if there is overlap with the already occupied memory slices. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param device The identifier of the target device + * @param profileId The GPU instance profile ID. See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param placements Returns placements allowed for the profile. Can be NULL to discover number + * of allowed placements for this profile. If non-NULL must be large enough + * to accommodate the placements supported by the profile. + * @param count Returns number of allowed placemenets for the profile. + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profileId or \a count are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't support MIG or \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstancePossiblePlacements_v2(nvmlDevice_t device, unsigned int profileId, + nvmlGpuInstancePlacement_t *placements, + unsigned int *count); + +/** + * Get GPU instance profile capacity. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param device The identifier of the target device + * @param profileId The GPU instance profile ID. See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param count Returns remaining instance count for the profile ID + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profileId or \a count are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceRemainingCapacity(nvmlDevice_t device, unsigned int profileId, + unsigned int *count); + +/** + * Create GPU instance. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * If the parent device is unbound, reset or the GPU instance is destroyed explicitly, the GPU instance handle would + * become invalid. The GPU instance must be recreated to acquire a valid handle. + * + * @param device The identifier of the target device + * @param profileId The GPU instance profile ID. See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param gpuInstance Returns the GPU instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profile, \a profileId or \a gpuInstance are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or in vGPU guest + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_INSUFFICIENT_RESOURCES If the requested GPU instance could not be created + */ +nvmlReturn_t DECLDIR nvmlDeviceCreateGpuInstance(nvmlDevice_t device, unsigned int profileId, + nvmlGpuInstance_t *gpuInstance); + +/** + * Create GPU instance with the specified placement. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * If the parent device is unbound, reset or the GPU instance is destroyed explicitly, the GPU instance handle would + * become invalid. The GPU instance must be recreated to acquire a valid handle. + * + * @param device The identifier of the target device + * @param profileId The GPU instance profile ID. See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param placement The requested placement. See \ref nvmlDeviceGetGpuInstancePossiblePlacements_v2 + * @param gpuInstance Returns the GPU instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profile, \a profileId, \a placement or \a gpuInstance + * are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or in vGPU guest + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_INSUFFICIENT_RESOURCES If the requested GPU instance could not be created + */ +nvmlReturn_t DECLDIR nvmlDeviceCreateGpuInstanceWithPlacement(nvmlDevice_t device, unsigned int profileId, + const nvmlGpuInstancePlacement_t *placement, + nvmlGpuInstance_t *gpuInstance); +/** + * Destroy GPU instance. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param gpuInstance The GPU instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or in vGPU guest + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_IN_USE If the GPU instance is in use. This error would be returned if processes + * (e.g. CUDA application) or compute instances are active on the + * GPU instance. + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceDestroy(nvmlGpuInstance_t gpuInstance); + +/** + * Get GPU instances for given profile ID. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param device The identifier of the target device + * @param profileId The GPU instance profile ID. See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param gpuInstances Returns pre-exiting GPU instances, the buffer must be large enough to + * accommodate the instances supported by the profile. + * See \ref nvmlDeviceGetGpuInstanceProfileInfo + * @param count The count of returned GPU instances + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a profileId, \a gpuInstances or \a count are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstances(nvmlDevice_t device, unsigned int profileId, + nvmlGpuInstance_t *gpuInstances, unsigned int *count); + +/** + * Get GPU instances for given instance ID. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param device The identifier of the target device + * @param id The GPU instance ID + * @param gpuInstance Returns GPU instance + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a id or \a gpuInstance are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_NOT_FOUND If the GPU instance is not found. + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceById(nvmlDevice_t device, unsigned int id, nvmlGpuInstance_t *gpuInstance); + +/** + * Get GPU instance information. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param gpuInstance The GPU instance handle + * @param info Return GPU instance information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance or \a info are invalid + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetInfo(nvmlGpuInstance_t gpuInstance, nvmlGpuInstanceInfo_t *info); + +/** + * Get compute instance profile information. + * + * Information provided by this API is immutable throughout the lifetime of a MIG mode. + * + * @note This API can be used to enumerate all MIG profiles supported by NVML in a forward compatible + * way by invoking it on \a profile values starting from 0, until the API returns \ref NVML_ERROR_INVALID_ARGUMENT. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profile One of the NVML_COMPUTE_INSTANCE_PROFILE_* + * @param engProfile One of the NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_* + * @param info Returns detailed profile information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profile, \a engProfile or \a info are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profile isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstanceProfileInfo(nvmlGpuInstance_t gpuInstance, unsigned int profile, + unsigned int engProfile, + nvmlComputeInstanceProfileInfo_t *info); + +/** + * Versioned wrapper around \ref nvmlGpuInstanceGetComputeInstanceProfileInfo that accepts a versioned + * \ref nvmlComputeInstanceProfileInfo_v2_t or later output structure. + * + * @note The caller must set the \ref nvmlGpuInstanceProfileInfo_v2_t.version field to the + * appropriate version prior to calling this function. For example: + * \code + * nvmlComputeInstanceProfileInfo_v2_t profileInfo = + * { .version = nvmlComputeInstanceProfileInfo_v2 }; + * nvmlReturn_t result = nvmlGpuInstanceGetComputeInstanceProfileInfoV(gpuInstance, + * profile, + * engProfile, + * &profileInfo); + * \endcode + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profile One of the NVML_COMPUTE_INSTANCE_PROFILE_* + * @param engProfile One of the NVML_COMPUTE_INSTANCE_ENGINE_PROFILE_* + * @param info Returns detailed profile information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profile, \a engProfile, \a info, or \a info->version are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profile isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstanceProfileInfoV(nvmlGpuInstance_t gpuInstance, unsigned int profile, + unsigned int engProfile, + nvmlComputeInstanceProfileInfo_v2_t *info); + +/** + * Get compute instance profile capacity. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profileId The compute instance profile ID. + * See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param count Returns remaining instance count for the profile ID + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profileId or \a availableCount are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstanceRemainingCapacity(nvmlGpuInstance_t gpuInstance, + unsigned int profileId, unsigned int *count); + +/** + * Get compute instance placements. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * A placement represents the location of a compute instance within a GPU instance. This API only returns all the possible + * placements for the given profile. + * A created compute instance occupies compute slices described by its placement. Creation of new compute instance will + * fail if there is overlap with the already occupied compute slices. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profileId The compute instance profile ID. See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param placements Returns placements allowed for the profile. Can be NULL to discover number + * of allowed placements for this profile. If non-NULL must be large enough + * to accommodate the placements supported by the profile. + * @param count Returns number of allowed placemenets for the profile. + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profileId or \a count are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled or \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstancePossiblePlacements(nvmlGpuInstance_t gpuInstance, + unsigned int profileId, + nvmlComputeInstancePlacement_t *placements, + unsigned int *count); + +/** + * Create compute instance. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * If the parent device is unbound, reset or the parent GPU instance is destroyed or the compute instance is destroyed + * explicitly, the compute instance handle would become invalid. The compute instance must be recreated to acquire + * a valid handle. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profileId The compute instance profile ID. + * See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param computeInstance Returns the compute instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profile, \a profileId or \a computeInstance + * are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_INSUFFICIENT_RESOURCES If the requested compute instance could not be created + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceCreateComputeInstance(nvmlGpuInstance_t gpuInstance, unsigned int profileId, + nvmlComputeInstance_t *computeInstance); + +/** + * Create compute instance with the specified placement. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * If the parent device is unbound, reset or the parent GPU instance is destroyed or the compute instance is destroyed + * explicitly, the compute instance handle would become invalid. The compute instance must be recreated to acquire + * a valid handle. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profileId The compute instance profile ID. + * See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param placement The requested placement. See \ref nvmlGpuInstanceGetComputeInstancePossiblePlacements + * @param computeInstance Returns the compute instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profile, \a profileId or \a computeInstance + * are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_INSUFFICIENT_RESOURCES If the requested compute instance could not be created + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceCreateComputeInstanceWithPlacement(nvmlGpuInstance_t gpuInstance, unsigned int profileId, + const nvmlComputeInstancePlacement_t *placement, + nvmlComputeInstance_t *computeInstance); + +/** + * Destroy compute instance. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param computeInstance The compute instance handle + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a computeInstance is invalid + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_IN_USE If the compute instance is in use. This error would be returned if + * processes (e.g. CUDA application) are active on the compute instance. + */ +nvmlReturn_t DECLDIR nvmlComputeInstanceDestroy(nvmlComputeInstance_t computeInstance); + +/** + * Get compute instances for given profile ID. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param gpuInstance The identifier of the target GPU instance + * @param profileId The compute instance profile ID. + * See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param computeInstances Returns pre-exiting compute instances, the buffer must be large enough to + * accommodate the instances supported by the profile. + * See \ref nvmlGpuInstanceGetComputeInstanceProfileInfo + * @param count The count of returned compute instances + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a gpuInstance, \a profileId, \a computeInstances or \a count + * are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a profileId isn't supported + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstances(nvmlGpuInstance_t gpuInstance, unsigned int profileId, + nvmlComputeInstance_t *computeInstances, unsigned int *count); + +/** + * Get compute instance for given instance ID. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * Requires privileged user. + * + * @param gpuInstance The identifier of the target GPU instance + * @param id The compute instance ID + * @param computeInstance Returns compute instance + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device, \a ID or \a computeInstance are invalid + * - \ref NVML_ERROR_NOT_SUPPORTED If \a device doesn't have MIG mode enabled + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + * - \ref NVML_ERROR_NOT_FOUND If the compute instance is not found. + */ +nvmlReturn_t DECLDIR nvmlGpuInstanceGetComputeInstanceById(nvmlGpuInstance_t gpuInstance, unsigned int id, + nvmlComputeInstance_t *computeInstance); + +/** + * Get compute instance information. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param computeInstance The compute instance handle + * @param info Return compute instance information + * + * @return + * - \ref NVML_SUCCESS Upon success + * - \ref NVML_ERROR_UNINITIALIZED If library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a computeInstance or \a info are invalid + * - \ref NVML_ERROR_NO_PERMISSION If user doesn't have permission to perform the operation + */ +nvmlReturn_t DECLDIR nvmlComputeInstanceGetInfo_v2(nvmlComputeInstance_t computeInstance, nvmlComputeInstanceInfo_t *info); + +/** + * Test if the given 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 &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device NVML handle to test + * @param isMigDevice True when handle refers to a MIG device + * + * @return + * - \ref NVML_SUCCESS if \a device status was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device handle or \a isMigDevice reference is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this check is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceIsMigDeviceHandle(nvmlDevice_t device, unsigned int *isMigDevice); + +/** + * Get GPU instance ID for the given MIG device handle. + * + * GPU instance IDs are unique per device and remain valid until the GPU instance is destroyed. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device Target MIG device handle + * @param id GPU instance ID + * + * @return + * - \ref NVML_SUCCESS if instance ID was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a id reference is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstanceId(nvmlDevice_t device, unsigned int *id); + +/** + * Get compute instance ID for the given MIG device handle. + * + * Compute instance IDs are unique per GPU instance and remain valid until the compute instance + * is destroyed. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device Target MIG device handle + * @param id Compute instance ID + * + * @return + * - \ref NVML_SUCCESS if instance ID was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a id reference is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetComputeInstanceId(nvmlDevice_t device, unsigned int *id); + +/** + * Get the maximum number of MIG devices that can exist under a given parent NVML device. + * + * Returns zero if MIG is not supported or enabled. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device Target device handle + * @param count Count of MIG devices + * + * @return + * - \ref NVML_SUCCESS if \a count was successfully retrieved + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device or \a count reference is invalid + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMaxMigDeviceCount(nvmlDevice_t device, unsigned int *count); + +/** + * Get 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 the GPU device itself + * the MIG device handle would remain invalid and must be requested again + * using this API. Handles may be reused and their properties can change in + * the process. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param device Reference to the parent GPU device handle + * @param index Index of the MIG device + * @param migDevice Reference to the MIG device handle + * + * @return + * - \ref NVML_SUCCESS if \a migDevice handle was successfully created + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device, \a index or \a migDevice reference is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_NOT_FOUND if no valid MIG device was found at \a index + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetMigDeviceHandleByIndex(nvmlDevice_t device, unsigned int index, + nvmlDevice_t *migDevice); + +/** + * Get parent device handle from a MIG device handle. + * + * For Ampere &tm; or newer fully supported devices. + * Supported on Linux only. + * + * @param migDevice MIG device handle + * @param device Device handle + * + * @return + * - \ref NVML_SUCCESS if \a device handle was successfully created + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a migDevice or \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetDeviceHandleFromMigDeviceHandle(nvmlDevice_t migDevice, nvmlDevice_t *device); + +/** @} */ // @defgroup nvmlMultiInstanceGPU + + +/***************************************************************************************************/ +/** @defgroup GPM NVML GPM + * @{ + */ +/***************************************************************************************************/ +/** @defgroup nvmlGpmEnums GPM Enums + * @{ + */ +/***************************************************************************************************/ + +/** + * GPM Metric Identifiers + */ +typedef enum +{ + NVML_GPM_METRIC_GRAPHICS_UTIL = 1, //!< Percentage of time any compute/graphics app was active on the GPU. 0.0 - 100.0 + NVML_GPM_METRIC_SM_UTIL = 2, //!< Percentage of SMs that were busy. 0.0 - 100.0 + NVML_GPM_METRIC_SM_OCCUPANCY = 3, //!< Percentage of warps that were active vs theoretical maximum. 0.0 - 100.0 + NVML_GPM_METRIC_INTEGER_UTIL = 4, //!< Percentage of time the GPU's SMs were doing integer operations. 0.0 - 100.0 + NVML_GPM_METRIC_ANY_TENSOR_UTIL = 5, //!< Percentage of time the GPU's SMs were doing ANY tensor operations. 0.0 - 100.0 + NVML_GPM_METRIC_DFMA_TENSOR_UTIL = 6, //!< Percentage of time the GPU's SMs were doing DFMA tensor operations. 0.0 - 100.0 + NVML_GPM_METRIC_HMMA_TENSOR_UTIL = 7, //!< Percentage of time the GPU's SMs were doing HMMA tensor operations. 0.0 - 100.0 + NVML_GPM_METRIC_IMMA_TENSOR_UTIL = 9, //!< Percentage of time the GPU's SMs were doing IMMA tensor operations. 0.0 - 100.0 + NVML_GPM_METRIC_DRAM_BW_UTIL = 10, //!< Percentage of DRAM bw used vs theoretical maximum. 0.0 - 100.0 */ + NVML_GPM_METRIC_FP64_UTIL = 11, //!< Percentage of time the GPU's SMs were doing non-tensor FP64 math. 0.0 - 100.0 + NVML_GPM_METRIC_FP32_UTIL = 12, //!< Percentage of time the GPU's SMs were doing non-tensor FP32 math. 0.0 - 100.0 + NVML_GPM_METRIC_FP16_UTIL = 13, //!< Percentage of time the GPU's SMs were doing non-tensor FP16 math. 0.0 - 100.0 + NVML_GPM_METRIC_PCIE_TX_PER_SEC = 20, //!< PCIe traffic from this GPU in MiB/sec + NVML_GPM_METRIC_PCIE_RX_PER_SEC = 21, //!< PCIe traffic to this GPU in MiB/sec + NVML_GPM_METRIC_NVDEC_0_UTIL = 30, //!< Percent utilization of NVDEC 0. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_1_UTIL = 31, //!< Percent utilization of NVDEC 1. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_2_UTIL = 32, //!< Percent utilization of NVDEC 2. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_3_UTIL = 33, //!< Percent utilization of NVDEC 3. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_4_UTIL = 34, //!< Percent utilization of NVDEC 4. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_5_UTIL = 35, //!< Percent utilization of NVDEC 5. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_6_UTIL = 36, //!< Percent utilization of NVDEC 6. 0.0 - 100.0 + NVML_GPM_METRIC_NVDEC_7_UTIL = 37, //!< Percent utilization of NVDEC 7. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_0_UTIL = 40, //!< Percent utilization of NVJPG 0. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_1_UTIL = 41, //!< Percent utilization of NVJPG 1. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_2_UTIL = 42, //!< Percent utilization of NVJPG 2. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_3_UTIL = 43, //!< Percent utilization of NVJPG 3. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_4_UTIL = 44, //!< Percent utilization of NVJPG 4. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_5_UTIL = 45, //!< Percent utilization of NVJPG 5. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_6_UTIL = 46, //!< Percent utilization of NVJPG 6. 0.0 - 100.0 + NVML_GPM_METRIC_NVJPG_7_UTIL = 47, //!< Percent utilization of NVJPG 7. 0.0 - 100.0 + NVML_GPM_METRIC_NVOFA_0_UTIL = 50, //!< Percent utilization of NVOFA 0. 0.0 - 100.0 + NVML_GPM_METRIC_NVOFA_1_UTIL = 51, //!< Percent utilization of NVOFA 1. 0.0 - 100.0 + NVML_GPM_METRIC_NVLINK_TOTAL_RX_PER_SEC = 60, //!< NvLink read bandwidth for all links in MiB/sec + NVML_GPM_METRIC_NVLINK_TOTAL_TX_PER_SEC = 61, //!< NvLink write bandwidth for all links in MiB/sec + NVML_GPM_METRIC_NVLINK_L0_RX_PER_SEC = 62, //!< NvLink read bandwidth for link 0 in MiB/sec + NVML_GPM_METRIC_NVLINK_L0_TX_PER_SEC = 63, //!< NvLink write bandwidth for link 0 in MiB/sec + NVML_GPM_METRIC_NVLINK_L1_RX_PER_SEC = 64, //!< NvLink read bandwidth for link 1 in MiB/sec + NVML_GPM_METRIC_NVLINK_L1_TX_PER_SEC = 65, //!< NvLink write bandwidth for link 1 in MiB/sec + NVML_GPM_METRIC_NVLINK_L2_RX_PER_SEC = 66, //!< NvLink read bandwidth for link 2 in MiB/sec + NVML_GPM_METRIC_NVLINK_L2_TX_PER_SEC = 67, //!< NvLink write bandwidth for link 2 in MiB/sec + NVML_GPM_METRIC_NVLINK_L3_RX_PER_SEC = 68, //!< NvLink read bandwidth for link 3 in MiB/sec + NVML_GPM_METRIC_NVLINK_L3_TX_PER_SEC = 69, //!< NvLink write bandwidth for link 3 in MiB/sec + NVML_GPM_METRIC_NVLINK_L4_RX_PER_SEC = 70, //!< NvLink read bandwidth for link 4 in MiB/sec + NVML_GPM_METRIC_NVLINK_L4_TX_PER_SEC = 71, //!< NvLink write bandwidth for link 4 in MiB/sec + NVML_GPM_METRIC_NVLINK_L5_RX_PER_SEC = 72, //!< NvLink read bandwidth for link 5 in MiB/sec + NVML_GPM_METRIC_NVLINK_L5_TX_PER_SEC = 73, //!< NvLink write bandwidth for link 5 in MiB/sec + NVML_GPM_METRIC_NVLINK_L6_RX_PER_SEC = 74, //!< NvLink read bandwidth for link 6 in MiB/sec + NVML_GPM_METRIC_NVLINK_L6_TX_PER_SEC = 75, //!< NvLink write bandwidth for link 6 in MiB/sec + NVML_GPM_METRIC_NVLINK_L7_RX_PER_SEC = 76, //!< NvLink read bandwidth for link 7 in MiB/sec + NVML_GPM_METRIC_NVLINK_L7_TX_PER_SEC = 77, //!< NvLink write bandwidth for link 7 in MiB/sec + NVML_GPM_METRIC_NVLINK_L8_RX_PER_SEC = 78, //!< NvLink read bandwidth for link 8 in MiB/sec + NVML_GPM_METRIC_NVLINK_L8_TX_PER_SEC = 79, //!< NvLink write bandwidth for link 8 in MiB/sec + NVML_GPM_METRIC_NVLINK_L9_RX_PER_SEC = 80, //!< NvLink read bandwidth for link 9 in MiB/sec + NVML_GPM_METRIC_NVLINK_L9_TX_PER_SEC = 81, //!< NvLink write bandwidth for link 9 in MiB/sec + NVML_GPM_METRIC_NVLINK_L10_RX_PER_SEC = 82, //!< NvLink read bandwidth for link 10 in MiB/sec + NVML_GPM_METRIC_NVLINK_L10_TX_PER_SEC = 83, //!< NvLink write bandwidth for link 10 in MiB/sec + NVML_GPM_METRIC_NVLINK_L11_RX_PER_SEC = 84, //!< NvLink read bandwidth for link 11 in MiB/sec + NVML_GPM_METRIC_NVLINK_L11_TX_PER_SEC = 85, //!< NvLink write bandwidth for link 11 in MiB/sec + NVML_GPM_METRIC_NVLINK_L12_RX_PER_SEC = 86, //!< NvLink read bandwidth for link 12 in MiB/sec + NVML_GPM_METRIC_NVLINK_L12_TX_PER_SEC = 87, //!< NvLink write bandwidth for link 12 in MiB/sec + NVML_GPM_METRIC_NVLINK_L13_RX_PER_SEC = 88, //!< NvLink read bandwidth for link 13 in MiB/sec + NVML_GPM_METRIC_NVLINK_L13_TX_PER_SEC = 89, //!< NvLink write bandwidth for link 13 in MiB/sec + NVML_GPM_METRIC_NVLINK_L14_RX_PER_SEC = 90, //!< NvLink read bandwidth for link 14 in MiB/sec + NVML_GPM_METRIC_NVLINK_L14_TX_PER_SEC = 91, //!< NvLink write bandwidth for link 14 in MiB/sec + NVML_GPM_METRIC_NVLINK_L15_RX_PER_SEC = 92, //!< NvLink read bandwidth for link 15 in MiB/sec + NVML_GPM_METRIC_NVLINK_L15_TX_PER_SEC = 93, //!< NvLink write bandwidth for link 15 in MiB/sec + NVML_GPM_METRIC_NVLINK_L16_RX_PER_SEC = 94, //!< NvLink read bandwidth for link 16 in MiB/sec + NVML_GPM_METRIC_NVLINK_L16_TX_PER_SEC = 95, //!< NvLink write bandwidth for link 16 in MiB/sec + NVML_GPM_METRIC_NVLINK_L17_RX_PER_SEC = 96, //!< NvLink read bandwidth for link 17 in MiB/sec + NVML_GPM_METRIC_NVLINK_L17_TX_PER_SEC = 97, //!< NvLink write bandwidth for link 17 in MiB/sec + //Put new metrics for BLACKWELL here... + NVML_GPM_METRIC_C2C_TOTAL_TX_PER_SEC = 100, + NVML_GPM_METRIC_C2C_TOTAL_RX_PER_SEC = 101, + NVML_GPM_METRIC_C2C_DATA_TX_PER_SEC = 102, + NVML_GPM_METRIC_C2C_DATA_RX_PER_SEC = 103, + NVML_GPM_METRIC_C2C_LINK0_TOTAL_TX_PER_SEC = 104, + NVML_GPM_METRIC_C2C_LINK0_TOTAL_RX_PER_SEC = 105, + NVML_GPM_METRIC_C2C_LINK0_DATA_TX_PER_SEC = 106, + NVML_GPM_METRIC_C2C_LINK0_DATA_RX_PER_SEC = 107, + NVML_GPM_METRIC_C2C_LINK1_TOTAL_TX_PER_SEC = 108, + NVML_GPM_METRIC_C2C_LINK1_TOTAL_RX_PER_SEC = 109, + NVML_GPM_METRIC_C2C_LINK1_DATA_TX_PER_SEC = 110, + NVML_GPM_METRIC_C2C_LINK1_DATA_RX_PER_SEC = 111, + NVML_GPM_METRIC_C2C_LINK2_TOTAL_TX_PER_SEC = 112, + NVML_GPM_METRIC_C2C_LINK2_TOTAL_RX_PER_SEC = 113, + NVML_GPM_METRIC_C2C_LINK2_DATA_TX_PER_SEC = 114, + NVML_GPM_METRIC_C2C_LINK2_DATA_RX_PER_SEC = 115, + NVML_GPM_METRIC_C2C_LINK3_TOTAL_TX_PER_SEC = 116, + NVML_GPM_METRIC_C2C_LINK3_TOTAL_RX_PER_SEC = 117, + NVML_GPM_METRIC_C2C_LINK3_DATA_TX_PER_SEC = 118, + NVML_GPM_METRIC_C2C_LINK3_DATA_RX_PER_SEC = 119, + NVML_GPM_METRIC_C2C_LINK4_TOTAL_TX_PER_SEC = 120, + NVML_GPM_METRIC_C2C_LINK4_TOTAL_RX_PER_SEC = 121, + NVML_GPM_METRIC_C2C_LINK4_DATA_TX_PER_SEC = 122, + NVML_GPM_METRIC_C2C_LINK4_DATA_RX_PER_SEC = 123, + NVML_GPM_METRIC_C2C_LINK5_TOTAL_TX_PER_SEC = 124, + NVML_GPM_METRIC_C2C_LINK5_TOTAL_RX_PER_SEC = 125, + NVML_GPM_METRIC_C2C_LINK5_DATA_TX_PER_SEC = 126, + NVML_GPM_METRIC_C2C_LINK5_DATA_RX_PER_SEC = 127, + NVML_GPM_METRIC_C2C_LINK6_TOTAL_TX_PER_SEC = 128, + NVML_GPM_METRIC_C2C_LINK6_TOTAL_RX_PER_SEC = 129, + NVML_GPM_METRIC_C2C_LINK6_DATA_TX_PER_SEC = 130, + NVML_GPM_METRIC_C2C_LINK6_DATA_RX_PER_SEC = 131, + NVML_GPM_METRIC_C2C_LINK7_TOTAL_TX_PER_SEC = 132, + NVML_GPM_METRIC_C2C_LINK7_TOTAL_RX_PER_SEC = 133, + NVML_GPM_METRIC_C2C_LINK7_DATA_TX_PER_SEC = 134, + NVML_GPM_METRIC_C2C_LINK7_DATA_RX_PER_SEC = 135, + NVML_GPM_METRIC_C2C_LINK8_TOTAL_TX_PER_SEC = 136, + NVML_GPM_METRIC_C2C_LINK8_TOTAL_RX_PER_SEC = 137, + NVML_GPM_METRIC_C2C_LINK8_DATA_TX_PER_SEC = 138, + NVML_GPM_METRIC_C2C_LINK8_DATA_RX_PER_SEC = 139, + NVML_GPM_METRIC_C2C_LINK9_TOTAL_TX_PER_SEC = 140, + NVML_GPM_METRIC_C2C_LINK9_TOTAL_RX_PER_SEC = 141, + NVML_GPM_METRIC_C2C_LINK9_DATA_TX_PER_SEC = 142, + NVML_GPM_METRIC_C2C_LINK9_DATA_RX_PER_SEC = 143, + NVML_GPM_METRIC_C2C_LINK10_TOTAL_TX_PER_SEC = 144, + NVML_GPM_METRIC_C2C_LINK10_TOTAL_RX_PER_SEC = 145, + NVML_GPM_METRIC_C2C_LINK10_DATA_TX_PER_SEC = 146, + NVML_GPM_METRIC_C2C_LINK10_DATA_RX_PER_SEC = 147, + NVML_GPM_METRIC_C2C_LINK11_TOTAL_TX_PER_SEC = 148, + NVML_GPM_METRIC_C2C_LINK11_TOTAL_RX_PER_SEC = 149, + NVML_GPM_METRIC_C2C_LINK11_DATA_TX_PER_SEC = 150, + NVML_GPM_METRIC_C2C_LINK11_DATA_RX_PER_SEC = 151, + NVML_GPM_METRIC_C2C_LINK12_TOTAL_TX_PER_SEC = 152, + NVML_GPM_METRIC_C2C_LINK12_TOTAL_RX_PER_SEC = 153, + NVML_GPM_METRIC_C2C_LINK12_DATA_TX_PER_SEC = 154, + NVML_GPM_METRIC_C2C_LINK12_DATA_RX_PER_SEC = 155, + NVML_GPM_METRIC_C2C_LINK13_TOTAL_TX_PER_SEC = 156, + NVML_GPM_METRIC_C2C_LINK13_TOTAL_RX_PER_SEC = 157, + NVML_GPM_METRIC_C2C_LINK13_DATA_TX_PER_SEC = 158, + NVML_GPM_METRIC_C2C_LINK13_DATA_RX_PER_SEC = 159, + NVML_GPM_METRIC_HOSTMEM_CACHE_HIT = 160, + NVML_GPM_METRIC_HOSTMEM_CACHE_MISS = 161, + NVML_GPM_METRIC_PEERMEM_CACHE_HIT = 162, + NVML_GPM_METRIC_PEERMEM_CACHE_MISS = 163, + NVML_GPM_METRIC_DRAM_CACHE_HIT = 164, + NVML_GPM_METRIC_DRAM_CACHE_MISS = 165, + NVML_GPM_METRIC_NVENC_0_UTIL = 166, + NVML_GPM_METRIC_NVENC_1_UTIL = 167, + NVML_GPM_METRIC_NVENC_2_UTIL = 168, + NVML_GPM_METRIC_NVENC_3_UTIL = 169, + NVML_GPM_METRIC_GR0_CTXSW_CYCLES_ELAPSED = 170, + NVML_GPM_METRIC_GR0_CTXSW_CYCLES_ACTIVE = 171, + NVML_GPM_METRIC_GR0_CTXSW_REQUESTS = 172, + NVML_GPM_METRIC_GR0_CTXSW_CYCLES_PER_REQ = 173, + NVML_GPM_METRIC_GR0_CTXSW_ACTIVE_PCT = 174, + NVML_GPM_METRIC_GR1_CTXSW_CYCLES_ELAPSED = 175, + NVML_GPM_METRIC_GR1_CTXSW_CYCLES_ACTIVE = 176, + NVML_GPM_METRIC_GR1_CTXSW_REQUESTS = 177, + NVML_GPM_METRIC_GR1_CTXSW_CYCLES_PER_REQ = 178, + NVML_GPM_METRIC_GR1_CTXSW_ACTIVE_PCT = 179, + NVML_GPM_METRIC_GR2_CTXSW_CYCLES_ELAPSED = 180, + NVML_GPM_METRIC_GR2_CTXSW_CYCLES_ACTIVE = 181, + NVML_GPM_METRIC_GR2_CTXSW_REQUESTS = 182, + NVML_GPM_METRIC_GR2_CTXSW_CYCLES_PER_REQ = 183, + NVML_GPM_METRIC_GR2_CTXSW_ACTIVE_PCT = 184, + NVML_GPM_METRIC_GR3_CTXSW_CYCLES_ELAPSED = 185, + NVML_GPM_METRIC_GR3_CTXSW_CYCLES_ACTIVE = 186, + NVML_GPM_METRIC_GR3_CTXSW_REQUESTS = 187, + NVML_GPM_METRIC_GR3_CTXSW_CYCLES_PER_REQ = 188, + NVML_GPM_METRIC_GR3_CTXSW_ACTIVE_PCT = 189, + NVML_GPM_METRIC_GR4_CTXSW_CYCLES_ELAPSED = 190, + NVML_GPM_METRIC_GR4_CTXSW_CYCLES_ACTIVE = 191, + NVML_GPM_METRIC_GR4_CTXSW_REQUESTS = 192, + NVML_GPM_METRIC_GR4_CTXSW_CYCLES_PER_REQ = 193, + NVML_GPM_METRIC_GR4_CTXSW_ACTIVE_PCT = 194, + NVML_GPM_METRIC_GR5_CTXSW_CYCLES_ELAPSED = 195, + NVML_GPM_METRIC_GR5_CTXSW_CYCLES_ACTIVE = 196, + NVML_GPM_METRIC_GR5_CTXSW_REQUESTS = 197, + NVML_GPM_METRIC_GR5_CTXSW_CYCLES_PER_REQ = 198, + NVML_GPM_METRIC_GR5_CTXSW_ACTIVE_PCT = 199, + NVML_GPM_METRIC_GR6_CTXSW_CYCLES_ELAPSED = 200, + NVML_GPM_METRIC_GR6_CTXSW_CYCLES_ACTIVE = 201, + NVML_GPM_METRIC_GR6_CTXSW_REQUESTS = 202, + NVML_GPM_METRIC_GR6_CTXSW_CYCLES_PER_REQ = 203, + NVML_GPM_METRIC_GR6_CTXSW_ACTIVE_PCT = 204, + NVML_GPM_METRIC_GR7_CTXSW_CYCLES_ELAPSED = 205, + NVML_GPM_METRIC_GR7_CTXSW_CYCLES_ACTIVE = 206, + NVML_GPM_METRIC_GR7_CTXSW_REQUESTS = 207, + NVML_GPM_METRIC_GR7_CTXSW_CYCLES_PER_REQ = 208, + NVML_GPM_METRIC_GR7_CTXSW_ACTIVE_PCT = 209, + NVML_GPM_METRIC_MAX = 210, //!< Maximum value above +1. Note that changing this should also change NVML_GPM_METRICS_GET_VERSION due to struct size change +} nvmlGpmMetricId_t; + +/** @} */ // @defgroup nvmlGpmEnums + + +/***************************************************************************************************/ +/** @defgroup nvmlGpmStructs GPM Structs + * @{ + */ +/***************************************************************************************************/ + +/** + * Handle to an allocated GPM sample allocated with nvmlGpmSampleAlloc(). Free this with nvmlGpmSampleFree(). + */ +typedef struct +{ + struct nvmlGpmSample_st* handle; +} nvmlGpmSample_t; + +/** + * GPM metric information. + */ +typedef struct +{ + unsigned int metricId; //!< IN: NVML_GPM_METRIC_? define of which metric to retrieve + nvmlReturn_t nvmlReturn; //!< OUT: Status of this metric. If this is nonzero, then value is not valid + double value; //!< OUT: Value of this metric. Is only valid if nvmlReturn is 0 (NVML_SUCCESS) + struct + { + char *shortName; + char *longName; + char *unit; + } metricInfo; //!< OUT: Metric name and unit. Those can be NULL if not defined +} nvmlGpmMetric_t; + +/** + * GPM buffer information. + */ +typedef struct +{ + unsigned int version; //!< IN: Set to NVML_GPM_METRICS_GET_VERSION + unsigned int numMetrics; //!< IN: How many metrics to retrieve in metrics[] + nvmlGpmSample_t sample1; //!< IN: Sample buffer + nvmlGpmSample_t sample2; //!< IN: Sample buffer + nvmlGpmMetric_t metrics[NVML_GPM_METRIC_MAX]; //!< IN/OUT: Array of metrics. Set metricId on call. See nvmlReturn and value on return +} nvmlGpmMetricsGet_t; + +#define NVML_GPM_METRICS_GET_VERSION 1 + +/** + * GPM device information. + */ +typedef struct +{ + unsigned int version; //!< IN: Set to NVML_GPM_SUPPORT_VERSION + unsigned int isSupportedDevice; //!< OUT: Indicates device support +} nvmlGpmSupport_t; + +#define NVML_GPM_SUPPORT_VERSION 1 + +/** @} */ // @defgroup nvmlGPMStructs + +/***************************************************************************************************/ +/** @defgroup nvmlGpmFunctions GPM Functions + * @{ + */ +/***************************************************************************************************/ + +/** + * Calculate GPM metrics from two samples. + * + * For Hopper &tm; or newer fully supported devices. + * + * To retrieve metrics, the user must first allocate the two sample buffers at \a metricsGet->sample1 + * and \a metricsGet->sample2 by calling \a nvmlGpmSampleAlloc(). Next, the user should fill in the ID of each metric + * in \a metricsGet->metrics[i].metricId and specify the total number of metrics to retrieve in \a metricsGet->numMetrics, + * The version should be set to NVML_GPM_METRICS_GET_VERSION in \a metricsGet->version. The user then calls the + * \a nvmlGpmSampleGet() API twice to obtain 2 samples of counters. \note that the interval between these + * two \a nvmlGpmSampleGet() calls should be greater than 100ms due to the internal sample refresh rate. + * Finally, the user calls \a nvmlGpmMetricsGet to retrieve the metrics, which will be stored at \a metricsGet->metrics + * + * @param metricsGet IN/OUT: populated \a nvmlGpmMetricsGet_t struct + * + * @return + * - \ref NVML_SUCCESS on success + * - Nonzero NVML_ERROR_? enum on error + */ +nvmlReturn_t DECLDIR nvmlGpmMetricsGet(nvmlGpmMetricsGet_t *metricsGet); + + +/** + * Free an allocated sample buffer that was allocated with \ref nvmlGpmSampleAlloc() + * + * For Hopper &tm; or newer fully supported devices. + * + * @param gpmSample Sample to free + * + * @return + * - \ref NVML_SUCCESS on success + * - \ref NVML_ERROR_INVALID_ARGUMENT if an invalid pointer is provided + */ +nvmlReturn_t DECLDIR nvmlGpmSampleFree(nvmlGpmSample_t gpmSample); + + +/** + * Allocate a sample buffer to be used with NVML GPM . You will need to allocate + * at least two of these buffers to use with the NVML GPM feature + * + * For Hopper &tm; or newer fully supported devices. + * + * @param gpmSample Where the allocated sample will be stored + * + * @return + * - \ref NVML_SUCCESS on success + * - \ref NVML_ERROR_INVALID_ARGUMENT if an invalid pointer is provided + * - \ref NVML_ERROR_MEMORY if system memory is insufficient + */ +nvmlReturn_t DECLDIR nvmlGpmSampleAlloc(nvmlGpmSample_t *gpmSample); + +/** + * Read a sample of GPM metrics into the provided \a gpmSample buffer. After + * two samples are gathered, you can call nvmlGpmMetricGet on those samples to + * retrive metrics + * + * For Hopper &tm; or newer fully supported devices. + * + * @note The interval between two \a nvmlGpmSampleGet() calls should be greater than 100ms due to + * the internal sample refresh rate. + * + * @param device Device to get samples for + * @param gpmSample Buffer to read samples into + * + * @return + * - \ref NVML_SUCCESS on success + * - Nonzero NVML_ERROR_? enum on error + */ +nvmlReturn_t DECLDIR nvmlGpmSampleGet(nvmlDevice_t device, nvmlGpmSample_t gpmSample); + +/** + * Read a sample of GPM metrics into the provided \a gpmSample buffer for a MIG GPU Instance. + * + * After two samples are gathered, you can call nvmlGpmMetricGet on those + * samples to retrive metrics + * + * For Hopper &tm; or newer fully supported devices. + * + * @note The interval between two \a nvmlGpmMigSampleGet() calls should be greater than 100ms due to + * the internal sample refresh rate. + * + * @param device Device to get samples for + * @param gpuInstanceId MIG GPU Instance ID + * @param gpmSample Buffer to read samples into + * + * @return + * - \ref NVML_SUCCESS on success + * - Nonzero NVML_ERROR_? enum on error + */ +nvmlReturn_t DECLDIR nvmlGpmMigSampleGet(nvmlDevice_t device, unsigned int gpuInstanceId, nvmlGpmSample_t gpmSample); + +/** + * Indicate whether the supplied device supports GPM + * + * For Hopper &tm; or newer fully supported devices. + * + * @param device NVML device to query for + * @param gpmSupport Structure to indicate GPM support \a nvmlGpmSupport_t. Indicates + * GPM support per system for the supplied device + * + * @return + * - NVML_SUCCESS on success + * - Nonzero NVML_ERROR_? enum if there is an error in processing the query + */ +nvmlReturn_t DECLDIR nvmlGpmQueryDeviceSupport(nvmlDevice_t device, nvmlGpmSupport_t *gpmSupport); + +/* GPM Stream State */ +/** + * Get GPM stream state. + * + * For Hopper &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device The identifier of the target device + * @param state Returns GPM stream state + * NVML_FEATURE_DISABLED or NVML_FEATURE_ENABLED + * + * @return + * - \ref NVML_SUCCESS if \a current GPM stream state were successfully queried + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid or \a state is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlGpmQueryIfStreamingEnabled(nvmlDevice_t device, unsigned int *state); + +/** + * Set GPM stream state. + * + * For Hopper &tm; or newer fully supported devices. + * Supported on Linux, Windows TCC. + * + * @param device The identifier of the target device + * @param state GPM stream state, + * NVML_FEATURE_DISABLED or NVML_FEATURE_ENABLED + * + * @return + * - \ref NVML_SUCCESS if \a current GPM stream state is successfully set + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid + * - \ref NVML_ERROR_NOT_SUPPORTED if this query is not supported by the device + */ +nvmlReturn_t DECLDIR nvmlGpmSetStreamingEnabled(nvmlDevice_t device, unsigned int state); + +/** @} */ // @defgroup nvmlGpmFunctions +/** @} */ // @defgroup GPM + +#define NVML_DEV_CAP_EGM (1 << 0) // Extended GPU memory +/** + * Device capabilities + */ +typedef struct +{ + unsigned int version; //!< the API version number + unsigned int capMask; //!< OUT: Bit mask of capabilities. +} nvmlDeviceCapabilities_v1_t; +typedef nvmlDeviceCapabilities_v1_t nvmlDeviceCapabilities_t; +#define nvmlDeviceCapabilities_v1 NVML_STRUCT_VERSION(DeviceCapabilities, 1) + +/** + * Get device capabilities + * + * See \ref nvmlDeviceCapabilities_v1_t for more information on the struct. + * + * @param device The identifier of the target device + * @param caps Returns GPU's capabilities + * + * @return + * - \ref NVML_SUCCESS If the query is success + * - \ref NVML_ERROR_UNINITIALIZED If the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT If \a device is invalid or \a counters is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED If the device does not support this feature + * - \ref NVML_ERROR_GPU_IS_LOST If the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH If the provided version is invalid/unsupported + * - \ref NVML_ERROR_UNKNOWN On any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetCapabilities(nvmlDevice_t device, + nvmlDeviceCapabilities_t *caps); + + +/* + * Generic bitmask to hold 255 bits, represented by 8 elements of 32 bits + */ +#define NVML_255_MASK_BITS_PER_ELEM 32 +#define NVML_255_MASK_NUM_ELEMS 8 +#define NVML_255_MASK_BIT_SET(index, nvmlMask) \ + nvmlMask.mask[index / NVML_255_MASK_BITS_PER_ELEM] |= (1 << (index % NVML_255_MASK_BITS_PER_ELEM)) + +#define NVML_255_MASK_BIT_GET(index, nvmlMask) \ + nvmlMask.mask[index / NVML_255_MASK_BITS_PER_ELEM] & (1 << (index % NVML_255_MASK_BITS_PER_ELEM)) + +#define NVML_255_MASK_BIT_SET_PTR(index, nvmlMask) \ + nvmlMask->mask[index / NVML_255_MASK_BITS_PER_ELEM] |= (1 << (index % NVML_255_MASK_BITS_PER_ELEM)) + +#define NVML_255_MASK_BIT_GET_PTR(index, nvmlMask) \ + nvmlMask->mask[index / NVML_255_MASK_BITS_PER_ELEM] & (1 << (index % NVML_255_MASK_BITS_PER_ELEM)) + +typedef struct +{ + unsigned int mask[NVML_255_MASK_NUM_ELEMS]; //profileId is used and + * the rest of the structure is ignored. + * + * @return + * - \ref NVML_SUCCESS if the Desired Profile was successfully set + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or structure was NULL + * - \ref NVML_ERROR_NO_PERMISSION if user does not have permission to change the profile number + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * + **/ +nvmlReturn_t DECLDIR nvmlDevicePowerSmoothingActivatePresetProfile(nvmlDevice_t device, + nvmlPowerSmoothingProfile_t *profile); + +/** + * Update the value of a specific profile parameter contained within \ref nvmlPowerSmoothingProfile_v1_t. + * Requires root/admin permissions. + * + * %BLACKWELL_OR_NEWER% + * + * NVML_POWER_SMOOTHING_PROFILE_PARAM_PERCENT_TMP_FLOOR expects a value as a percentage from 00.00-100.00% + * NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_UP_RATE expects a value in W/s + * NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_RATE expects a value in W/s + * NVML_POWER_SMOOTHING_PROFILE_PARAM_RAMP_DOWN_HYSTERESIS expects a value in ms + * + * @param device The identifier of the target device + * @param profile Reference to \ref nvmlPowerSmoothingProfile_v1_t struct + * + * @return + * - \ref NVML_SUCCESS if the Active Profile was successfully set + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or profile parameter/value was invalid + * - \ref NVML_ERROR_NO_PERMISSION if user does not have permission to change any profile parameters + * - \ref NVML_ERROR_ARGUMENT_VERSION_MISMATCH if the structure version is not supported + * + **/ +nvmlReturn_t DECLDIR nvmlDevicePowerSmoothingUpdatePresetProfileParam(nvmlDevice_t device, + nvmlPowerSmoothingProfile_t *profile); +/** + * Enable or disable the Power Smoothing Feature. + * Requires root/admin permissions. + * + * %BLACKWELL_OR_NEWER% + * + * See \ref nvmlEnableState_t for details on allowed states + * + * @param device The identifier of the target device + * @param state Reference to \ref nvmlPowerSmoothingState_v1_t + * + * @return + * - \ref NVML_SUCCESS if the feature state was successfully set + * - \ref NVML_ERROR_INVALID_ARGUMENT if device is invalid or state is NULL + * - \ref NVML_ERROR_NO_PERMISSION if user does not have permission to change feature state + * - \ref NVML_ERROR_NOT_SUPPORTED if this feature is not supported by the device + * + **/ +nvmlReturn_t DECLDIR nvmlDevicePowerSmoothingSetState(nvmlDevice_t device, + nvmlPowerSmoothingState_t *state); +/** @} */ // @defgroup + +/** + * Retrieves the counts of SRAM unique uncorrected ECC errors + * + * %BLACKWELL_OR_NEWER% + * + * Reads SRAM unique uncorrected ECC error counts. The total number of unique errors is returned by + * \a errorCounts->entryCount. Error counts are returned as an array of in the caller-supplied buffer pointed at by + * \a errorCounts->entries. Each error count entry holds the location/address of the unique error, the error count and + * whether the error is parity or not. + * + * To read SRAM unique uncorrected ECC error counts, first determine the size of buffer required to hold the error + * counts by invoking the function with \a errorCounts->entries set to NULL. The required array size is returned in + * \a errorCounts->entryCount. The caller should allocate a buffer of size "errorCounts->entryCount * + * sizeof(nvmlEccSramUniqueUncorrectedErrorCounts_t)". Invoke the function again with the allocated buffer passed in + * \a errorCounts->entries. This time \a errorCounts->entryCount will be taken as the entry array size that caller + * allocates for \a errorCounts->entries. + * + * On successful return of the second query, the function updates \a errorCounts->entries with all unique errors. This + * may fail if \a errorCounts->entryCount is smaller than the actual number of unique errors. This can happen in cases + * like new errors occur since the previous query of \a errorCounts->entryCount. No matter the query succeeds or not, + * the latest number of unique errors will be returned in \a errorCounts->entryCount. + * + * @note The query is only supported when ECC mode is enabled. + * + * @param device The identifier of the target device + * @param errorCounts Pointer to caller-supplied array which returns the unique error count entries + * + * @return + * - \ref NVML_SUCCESS if \a utilization has been populated + * - \ref NVML_ERROR_UNINITIALIZED if the library has not been successfully initialized + * - \ref NVML_ERROR_INVALID_ARGUMENT if \a device is invalid, \a errorCounts->entryCount is NULL + * - \ref NVML_ERROR_NOT_SUPPORTED if the device does not support this feature or ECC mods is not enabled + * - \ref NVML_ERROR_INSUFFICIENT_SIZE if the allocated error entry array is not big enough + * - \ref NVML_ERROR_GPU_IS_LOST if the target GPU has fallen off the bus or is otherwise inaccessible + * - \ref NVML_ERROR_UNKNOWN on any unexpected error + */ +nvmlReturn_t DECLDIR nvmlDeviceGetSramUniqueUncorrectedEccErrorCounts(nvmlDevice_t device, + nvmlEccSramUniqueUncorrectedErrorCounts_t *errorCounts); + +/** + * NVML API versioning support + */ + +#ifdef NVML_NO_UNVERSIONED_FUNC_DEFS +nvmlReturn_t DECLDIR nvmlInit(void); +nvmlReturn_t DECLDIR nvmlDeviceGetCount(unsigned int *deviceCount); +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByIndex(unsigned int index, nvmlDevice_t *device); +nvmlReturn_t DECLDIR nvmlDeviceGetHandleByPciBusId(const char *pciBusId, nvmlDevice_t *device); +nvmlReturn_t DECLDIR nvmlDeviceGetPciInfo(nvmlDevice_t device, nvmlPciInfo_t *pci); +nvmlReturn_t DECLDIR nvmlDeviceGetPciInfo_v2(nvmlDevice_t device, nvmlPciInfo_t *pci); +nvmlReturn_t DECLDIR nvmlDeviceGetNvLinkRemotePciInfo(nvmlDevice_t device, unsigned int link, nvmlPciInfo_t *pci); +nvmlReturn_t DECLDIR nvmlDeviceGetGridLicensableFeatures(nvmlDevice_t device, nvmlGridLicensableFeatures_t *pGridLicensableFeatures); +nvmlReturn_t DECLDIR nvmlDeviceGetGridLicensableFeatures_v2(nvmlDevice_t device, nvmlGridLicensableFeatures_t *pGridLicensableFeatures); +nvmlReturn_t DECLDIR nvmlDeviceGetGridLicensableFeatures_v3(nvmlDevice_t device, nvmlGridLicensableFeatures_t *pGridLicensableFeatures); +nvmlReturn_t DECLDIR nvmlDeviceRemoveGpu(nvmlPciInfo_t *pciInfo); +nvmlReturn_t DECLDIR nvmlEventSetWait(nvmlEventSet_t set, nvmlEventData_t * data, unsigned int timeoutms); +nvmlReturn_t DECLDIR nvmlDeviceGetAttributes(nvmlDevice_t device, nvmlDeviceAttributes_t *attributes); +nvmlReturn_t DECLDIR nvmlComputeInstanceGetInfo(nvmlComputeInstance_t computeInstance, nvmlComputeInstanceInfo_t *info); +nvmlReturn_t DECLDIR nvmlDeviceGetComputeRunningProcesses(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v1_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetComputeRunningProcesses_v2(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v2_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetGraphicsRunningProcesses(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v1_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetGraphicsRunningProcesses_v2(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v2_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetMPSComputeRunningProcesses(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v1_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetMPSComputeRunningProcesses_v2(nvmlDevice_t device, unsigned int *infoCount, nvmlProcessInfo_v2_t *infos); +nvmlReturn_t DECLDIR nvmlDeviceGetGpuInstancePossiblePlacements(nvmlDevice_t device, unsigned int profileId, nvmlGpuInstancePlacement_t *placements, unsigned int *count); +nvmlReturn_t DECLDIR nvmlVgpuInstanceGetLicenseInfo(nvmlVgpuInstance_t vgpuInstance, nvmlVgpuLicenseInfo_t *licenseInfo); +nvmlReturn_t DECLDIR nvmlDeviceGetDriverModel(nvmlDevice_t device, nvmlDriverModel_t *current, nvmlDriverModel_t *pending); +#endif // #ifdef NVML_NO_UNVERSIONED_FUNC_DEFS + +#if defined(NVML_NO_UNVERSIONED_FUNC_DEFS) +// We don't define APIs to run new versions if this guard is present so there is +// no need to undef +#elif defined(__NVML_API_VERSION_INTERNAL) +#undef nvmlDeviceGetGraphicsRunningProcesses +#undef nvmlDeviceGetComputeRunningProcesses +#undef nvmlDeviceGetMPSComputeRunningProcesses +#undef nvmlDeviceGetAttributes +#undef nvmlComputeInstanceGetInfo +#undef nvmlEventSetWait +#undef nvmlDeviceGetGridLicensableFeatures +#undef nvmlDeviceRemoveGpu +#undef nvmlDeviceGetNvLinkRemotePciInfo +#undef nvmlDeviceGetPciInfo +#undef nvmlDeviceGetCount +#undef nvmlDeviceGetHandleByIndex +#undef nvmlDeviceGetHandleByPciBusId +#undef nvmlInit +#undef nvmlBlacklistDeviceInfo_t +#undef nvmlGetBlacklistDeviceCount +#undef nvmlGetBlacklistDeviceInfoByIndex +#undef nvmlDeviceGetGpuInstancePossiblePlacements +#undef nvmlVgpuInstanceGetLicenseInfo +#undef nvmlDeviceGetDriverModel +#undef nvmlDeviceSetPowerManagementLimit + +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/refcount.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/refcount.go new file mode 100644 index 00000000..4d1e212e --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/refcount.go @@ -0,0 +1,31 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvml + +type refcount int + +func (r *refcount) IncOnNoError(err error) { + if err == nil { + (*r)++ + } +} + +func (r *refcount) DecOnNoError(err error) { + if err == nil && (*r) > 0 { + (*r)-- + } +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/return.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/return.go new file mode 100644 index 00000000..1aec3ecc --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/return.go @@ -0,0 +1,103 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import ( + "fmt" +) + +// nvml.ErrorString() +func (l *library) ErrorString(r Return) string { + return r.Error() +} + +// String returns the string representation of a Return. +func (r Return) String() string { + return r.Error() +} + +// Error returns the string representation of a Return. +func (r Return) Error() string { + return errorStringFunc(r) +} + +// Assigned to nvml.ErrorString if the system nvml library is in use. +var errorStringFunc = defaultErrorStringFunc + +// defaultErrorStringFunc provides a basic nvmlErrorString implementation. +// This allows the nvml.ErrorString function to be used even if the NVML library +// is not loaded. +var defaultErrorStringFunc = func(r Return) string { + switch r { + case SUCCESS: + return "SUCCESS" + case ERROR_UNINITIALIZED: + return "ERROR_UNINITIALIZED" + case ERROR_INVALID_ARGUMENT: + return "ERROR_INVALID_ARGUMENT" + case ERROR_NOT_SUPPORTED: + return "ERROR_NOT_SUPPORTED" + case ERROR_NO_PERMISSION: + return "ERROR_NO_PERMISSION" + case ERROR_ALREADY_INITIALIZED: + return "ERROR_ALREADY_INITIALIZED" + case ERROR_NOT_FOUND: + return "ERROR_NOT_FOUND" + case ERROR_INSUFFICIENT_SIZE: + return "ERROR_INSUFFICIENT_SIZE" + case ERROR_INSUFFICIENT_POWER: + return "ERROR_INSUFFICIENT_POWER" + case ERROR_DRIVER_NOT_LOADED: + return "ERROR_DRIVER_NOT_LOADED" + case ERROR_TIMEOUT: + return "ERROR_TIMEOUT" + case ERROR_IRQ_ISSUE: + return "ERROR_IRQ_ISSUE" + case ERROR_LIBRARY_NOT_FOUND: + return "ERROR_LIBRARY_NOT_FOUND" + case ERROR_FUNCTION_NOT_FOUND: + return "ERROR_FUNCTION_NOT_FOUND" + case ERROR_CORRUPTED_INFOROM: + return "ERROR_CORRUPTED_INFOROM" + case ERROR_GPU_IS_LOST: + return "ERROR_GPU_IS_LOST" + case ERROR_RESET_REQUIRED: + return "ERROR_RESET_REQUIRED" + case ERROR_OPERATING_SYSTEM: + return "ERROR_OPERATING_SYSTEM" + case ERROR_LIB_RM_VERSION_MISMATCH: + return "ERROR_LIB_RM_VERSION_MISMATCH" + case ERROR_IN_USE: + return "ERROR_IN_USE" + case ERROR_MEMORY: + return "ERROR_MEMORY" + case ERROR_NO_DATA: + return "ERROR_NO_DATA" + case ERROR_VGPU_ECC_NOT_SUPPORTED: + return "ERROR_VGPU_ECC_NOT_SUPPORTED" + case ERROR_INSUFFICIENT_RESOURCES: + return "ERROR_INSUFFICIENT_RESOURCES" + case ERROR_FREQ_NOT_SUPPORTED: + return "ERROR_FREQ_NOT_SUPPORTED" + case ERROR_ARGUMENT_VERSION_MISMATCH: + return "ERROR_ARGUMENT_VERSION_MISMATCH" + case ERROR_DEPRECATED: + return "ERROR_DEPRECATED" + case ERROR_UNKNOWN: + return "ERROR_UNKNOWN" + default: + return fmt.Sprintf("unknown return value: %d", r) + } +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/system.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/system.go new file mode 100644 index 00000000..f8247102 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/system.go @@ -0,0 +1,148 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +// nvml.SystemGetDriverVersion() +func (l *library) SystemGetDriverVersion() (string, Return) { + Version := make([]byte, SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + ret := nvmlSystemGetDriverVersion(&Version[0], SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + return string(Version[:clen(Version)]), ret +} + +// nvml.SystemGetNVMLVersion() +func (l *library) SystemGetNVMLVersion() (string, Return) { + Version := make([]byte, SYSTEM_NVML_VERSION_BUFFER_SIZE) + ret := nvmlSystemGetNVMLVersion(&Version[0], SYSTEM_NVML_VERSION_BUFFER_SIZE) + return string(Version[:clen(Version)]), ret +} + +// nvml.SystemGetCudaDriverVersion() +func (l *library) SystemGetCudaDriverVersion() (int, Return) { + var CudaDriverVersion int32 + ret := nvmlSystemGetCudaDriverVersion(&CudaDriverVersion) + return int(CudaDriverVersion), ret +} + +// nvml.SystemGetCudaDriverVersion_v2() +func (l *library) SystemGetCudaDriverVersion_v2() (int, Return) { + var CudaDriverVersion int32 + ret := nvmlSystemGetCudaDriverVersion_v2(&CudaDriverVersion) + return int(CudaDriverVersion), ret +} + +// nvml.SystemGetProcessName() +func (l *library) SystemGetProcessName(pid int) (string, Return) { + name := make([]byte, SYSTEM_PROCESS_NAME_BUFFER_SIZE) + ret := nvmlSystemGetProcessName(uint32(pid), &name[0], SYSTEM_PROCESS_NAME_BUFFER_SIZE) + return string(name[:clen(name)]), ret +} + +// nvml.SystemGetHicVersion() +func (l *library) SystemGetHicVersion() ([]HwbcEntry, Return) { + var hwbcCount uint32 = 1 // Will be reduced upon returning + for { + hwbcEntries := make([]HwbcEntry, hwbcCount) + ret := nvmlSystemGetHicVersion(&hwbcCount, &hwbcEntries[0]) + if ret == SUCCESS { + return hwbcEntries[:hwbcCount], ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + hwbcCount *= 2 + } +} + +// nvml.SystemGetTopologyGpuSet() +func (l *library) SystemGetTopologyGpuSet(cpuNumber int) ([]Device, Return) { + var count uint32 + ret := nvmlSystemGetTopologyGpuSet(uint32(cpuNumber), &count, nil) + if ret != SUCCESS { + return nil, ret + } + if count == 0 { + return []Device{}, ret + } + deviceArray := make([]nvmlDevice, count) + ret = nvmlSystemGetTopologyGpuSet(uint32(cpuNumber), &count, &deviceArray[0]) + return convertSlice[nvmlDevice, Device](deviceArray), ret +} + +// nvml.SystemGetConfComputeCapabilities() +func (l *library) SystemGetConfComputeCapabilities() (ConfComputeSystemCaps, Return) { + var capabilities ConfComputeSystemCaps + ret := nvmlSystemGetConfComputeCapabilities(&capabilities) + return capabilities, ret +} + +// nvml.SystemGetConfComputeState() +func (l *library) SystemGetConfComputeState() (ConfComputeSystemState, Return) { + var state ConfComputeSystemState + ret := nvmlSystemGetConfComputeState(&state) + return state, ret +} + +// nvml.SystemGetConfComputeGpusReadyState() +func (l *library) SystemGetConfComputeGpusReadyState() (uint32, Return) { + var isAcceptingWork uint32 + ret := nvmlSystemGetConfComputeGpusReadyState(&isAcceptingWork) + return isAcceptingWork, ret +} + +// nvml.SystemSetConfComputeGpusReadyState() +func (l *library) SystemSetConfComputeGpusReadyState(isAcceptingWork uint32) Return { + return nvmlSystemSetConfComputeGpusReadyState(isAcceptingWork) +} + +// nvml.SystemSetNvlinkBwMode() +func (l *library) SystemSetNvlinkBwMode(nvlinkBwMode uint32) Return { + return nvmlSystemSetNvlinkBwMode(nvlinkBwMode) +} + +// nvml.SystemGetNvlinkBwMode() +func (l *library) SystemGetNvlinkBwMode() (uint32, Return) { + var nvlinkBwMode uint32 + ret := nvmlSystemGetNvlinkBwMode(&nvlinkBwMode) + return nvlinkBwMode, ret +} + +// nvml.SystemGetConfComputeKeyRotationThresholdInfo() +func (l *library) SystemGetConfComputeKeyRotationThresholdInfo() (ConfComputeGetKeyRotationThresholdInfo, Return) { + var keyRotationThresholdInfo ConfComputeGetKeyRotationThresholdInfo + keyRotationThresholdInfo.Version = STRUCT_VERSION(keyRotationThresholdInfo, 1) + ret := nvmlSystemGetConfComputeKeyRotationThresholdInfo(&keyRotationThresholdInfo) + return keyRotationThresholdInfo, ret +} + +// nvml.SystemGetConfComputeSettings() +func (l *library) SystemGetConfComputeSettings() (SystemConfComputeSettings, Return) { + var settings SystemConfComputeSettings + settings.Version = STRUCT_VERSION(settings, 1) + ret := nvmlSystemGetConfComputeSettings(&settings) + return settings, ret +} + +// nvml.SystemSetConfComputeKeyRotationThresholdInfo() +func (l *library) SystemSetConfComputeKeyRotationThresholdInfo(keyRotationThresholdInfo ConfComputeSetKeyRotationThresholdInfo) Return { + return nvmlSystemSetConfComputeKeyRotationThresholdInfo(&keyRotationThresholdInfo) +} + +// nvml.SystemGetDriverBranch() +func (l *library) SystemGetDriverBranch() (SystemDriverBranchInfo, Return) { + var branchInfo SystemDriverBranchInfo + branchInfo.Version = STRUCT_VERSION(branchInfo, 1) + ret := nvmlSystemGetDriverBranch(&branchInfo, SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + return branchInfo, ret +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/types_gen.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/types_gen.go new file mode 100644 index 00000000..efa58637 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/types_gen.go @@ -0,0 +1,1462 @@ +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs types.go + +package nvml + +import "unsafe" + +type nvmlDevice struct { + Handle *_Ctype_struct_nvmlDevice_st +} + +type nvmlGpuInstance struct { + Handle *_Ctype_struct_nvmlGpuInstance_st +} + +type PciInfoExt_v1 struct { + Version uint32 + Domain uint32 + Bus uint32 + Device uint32 + PciDeviceId uint32 + PciSubSystemId uint32 + BaseClass uint32 + SubClass uint32 + BusId [32]uint8 +} + +type PciInfoExt struct { + Version uint32 + Domain uint32 + Bus uint32 + Device uint32 + PciDeviceId uint32 + PciSubSystemId uint32 + BaseClass uint32 + SubClass uint32 + BusId [32]uint8 +} + +type PciInfo struct { + BusIdLegacy [16]uint8 + Domain uint32 + Bus uint32 + Device uint32 + PciDeviceId uint32 + PciSubSystemId uint32 + BusId [32]uint8 +} + +type EccErrorCounts struct { + L1Cache uint64 + L2Cache uint64 + DeviceMemory uint64 + RegisterFile uint64 +} + +type Utilization struct { + Gpu uint32 + Memory uint32 +} + +type Memory struct { + Total uint64 + Free uint64 + Used uint64 +} + +type Memory_v2 struct { + Version uint32 + Total uint64 + Reserved uint64 + Free uint64 + Used uint64 +} + +type BAR1Memory struct { + Bar1Total uint64 + Bar1Free uint64 + Bar1Used uint64 +} + +type ProcessInfo_v1 struct { + Pid uint32 + UsedGpuMemory uint64 +} + +type ProcessInfo_v2 struct { + Pid uint32 + UsedGpuMemory uint64 + GpuInstanceId uint32 + ComputeInstanceId uint32 +} + +type ProcessInfo struct { + Pid uint32 + UsedGpuMemory uint64 + GpuInstanceId uint32 + ComputeInstanceId uint32 +} + +type ProcessDetail_v1 struct { + Pid uint32 + UsedGpuMemory uint64 + GpuInstanceId uint32 + ComputeInstanceId uint32 + UsedGpuCcProtectedMemory uint64 +} + +type ProcessDetailList_v1 struct { + Version uint32 + Mode uint32 + NumProcArrayEntries uint32 + ProcArray *ProcessDetail_v1 +} + +type ProcessDetailList struct { + Version uint32 + Mode uint32 + NumProcArrayEntries uint32 + ProcArray *ProcessDetail_v1 +} + +type DeviceAttributes struct { + MultiprocessorCount uint32 + SharedCopyEngineCount uint32 + SharedDecoderCount uint32 + SharedEncoderCount uint32 + SharedJpegCount uint32 + SharedOfaCount uint32 + GpuInstanceSliceCount uint32 + ComputeInstanceSliceCount uint32 + MemorySizeMB uint64 +} + +type C2cModeInfo_v1 struct { + IsC2cEnabled uint32 +} + +type DeviceAddressingMode_v1 struct { + Version uint32 + Value uint32 +} + +type DeviceAddressingMode struct { + Version uint32 + Value uint32 +} + +type RepairStatus_v1 struct { + Version uint32 + BChannelRepairPending uint32 + BTpcRepairPending uint32 +} + +type RepairStatus struct { + Version uint32 + BChannelRepairPending uint32 + BTpcRepairPending uint32 +} + +type RowRemapperHistogramValues struct { + Max uint32 + High uint32 + Partial uint32 + Low uint32 + None uint32 +} + +type NvLinkUtilizationControl struct { + Units uint32 + Pktfilter uint32 +} + +type BridgeChipInfo struct { + Type uint32 + FwVersion uint32 +} + +type BridgeChipHierarchy struct { + BridgeCount uint8 + BridgeChipInfo [128]BridgeChipInfo +} + +const sizeofValue = unsafe.Sizeof([8]byte{}) + +type Value [sizeofValue]byte + +type Sample struct { + TimeStamp uint64 + SampleValue [8]byte +} + +type ViolationTime struct { + ReferenceTime uint64 + ViolationTime uint64 +} + +type GpuThermalSettings struct { + Count uint32 + Sensor [3]_Ctype_struct___28 +} + +type CoolerInfo_v1 struct { + Version uint32 + Index uint32 + SignalType uint32 + Target uint32 +} + +type CoolerInfo struct { + Version uint32 + Index uint32 + SignalType uint32 + Target uint32 +} + +const sizeofUUIDValue = unsafe.Sizeof([41]byte{}) + +type UUIDValue [sizeofUUIDValue]byte + +type UUID_v1 struct { + Version uint32 + Type uint32 + Value [41]byte + Pad_cgo_0 [3]byte +} + +type UUID struct { + Version uint32 + Type uint32 + Value [41]byte + Pad_cgo_0 [3]byte +} + +type Pdi_v1 struct { + Version uint32 + Value uint64 +} + +type Pdi struct { + Version uint32 + Value uint64 +} + +type DramEncryptionInfo_v1 struct { + Version uint32 + EncryptionState uint32 +} + +type DramEncryptionInfo struct { + Version uint32 + EncryptionState uint32 +} + +type MarginTemperature_v1 struct { + Version uint32 + MarginTemperature int32 +} + +type MarginTemperature struct { + Version uint32 + MarginTemperature int32 +} + +type ClkMonFaultInfo struct { + ClkApiDomain uint32 + ClkDomainFaultMask uint32 +} + +type ClkMonStatus struct { + BGlobalStatus uint32 + ClkMonListSize uint32 + ClkMonList [32]ClkMonFaultInfo +} + +type ClockOffset_v1 struct { + Version uint32 + Type uint32 + Pstate uint32 + ClockOffsetMHz int32 + MinClockOffsetMHz int32 + MaxClockOffsetMHz int32 +} + +type ClockOffset struct { + Version uint32 + Type uint32 + Pstate uint32 + ClockOffsetMHz int32 + MinClockOffsetMHz int32 + MaxClockOffsetMHz int32 +} + +type FanSpeedInfo_v1 struct { + Version uint32 + Fan uint32 + Speed uint32 +} + +type FanSpeedInfo struct { + Version uint32 + Fan uint32 + Speed uint32 +} + +type DevicePerfModes_v1 struct { + Version uint32 + Str [2048]uint8 +} + +type DevicePerfModes struct { + Version uint32 + Str [2048]uint8 +} + +type DeviceCurrentClockFreqs_v1 struct { + Version uint32 + Str [2048]uint8 +} + +type DeviceCurrentClockFreqs struct { + Version uint32 + Str [2048]uint8 +} + +type DevicePowerMizerModes_v1 struct { + CurrentMode uint32 + Mode uint32 + SupportedPowerMizerModes uint32 +} + +type ProcessUtilizationSample struct { + Pid uint32 + TimeStamp uint64 + SmUtil uint32 + MemUtil uint32 + EncUtil uint32 + DecUtil uint32 +} + +type ProcessUtilizationInfo_v1 struct { + TimeStamp uint64 + Pid uint32 + SmUtil uint32 + MemUtil uint32 + EncUtil uint32 + DecUtil uint32 + JpgUtil uint32 + OfaUtil uint32 + Pad_cgo_0 [4]byte +} + +type ProcessesUtilizationInfo_v1 struct { + Version uint32 + ProcessSamplesCount uint32 + LastSeenTimeStamp uint64 + ProcUtilArray *ProcessUtilizationInfo_v1 +} + +type ProcessesUtilizationInfo struct { + Version uint32 + ProcessSamplesCount uint32 + LastSeenTimeStamp uint64 + ProcUtilArray *ProcessUtilizationInfo_v1 +} + +type EccSramErrorStatus_v1 struct { + Version uint32 + AggregateUncParity uint64 + AggregateUncSecDed uint64 + AggregateCor uint64 + VolatileUncParity uint64 + VolatileUncSecDed uint64 + VolatileCor uint64 + AggregateUncBucketL2 uint64 + AggregateUncBucketSm uint64 + AggregateUncBucketPcie uint64 + AggregateUncBucketMcu uint64 + AggregateUncBucketOther uint64 + BThresholdExceeded uint32 + Pad_cgo_0 [4]byte +} + +type EccSramErrorStatus struct { + Version uint32 + AggregateUncParity uint64 + AggregateUncSecDed uint64 + AggregateCor uint64 + VolatileUncParity uint64 + VolatileUncSecDed uint64 + VolatileCor uint64 + AggregateUncBucketL2 uint64 + AggregateUncBucketSm uint64 + AggregateUncBucketPcie uint64 + AggregateUncBucketMcu uint64 + AggregateUncBucketOther uint64 + BThresholdExceeded uint32 + Pad_cgo_0 [4]byte +} + +type PlatformInfo_v1 struct { + Version uint32 + IbGuid [16]uint8 + RackGuid [16]uint8 + ChassisPhysicalSlotNumber uint8 + ComputeSlotIndex uint8 + NodeIndex uint8 + PeerType uint8 + ModuleId uint8 + Pad_cgo_0 [3]byte +} + +type PlatformInfo_v2 struct { + Version uint32 + IbGuid [16]uint8 + ChassisSerialNumber [16]uint8 + SlotNumber uint8 + TrayIndex uint8 + HostId uint8 + PeerType uint8 + ModuleId uint8 + Pad_cgo_0 [3]byte +} + +type PlatformInfo struct { + Version uint32 + IbGuid [16]uint8 + ChassisSerialNumber [16]uint8 + SlotNumber uint8 + TrayIndex uint8 + HostId uint8 + PeerType uint8 + ModuleId uint8 + Pad_cgo_0 [3]byte +} + +type EccSramUniqueUncorrectedErrorEntry_v1 struct { + Unit uint32 + Location uint32 + Sublocation uint32 + Extlocation uint32 + Address uint32 + IsParity uint32 + Count uint32 +} + +type EccSramUniqueUncorrectedErrorCounts_v1 struct { + Version uint32 + EntryCount uint32 + Entries *EccSramUniqueUncorrectedErrorEntry_v1 +} + +type EccSramUniqueUncorrectedErrorCounts struct { + Version uint32 + EntryCount uint32 + Entries *EccSramUniqueUncorrectedErrorEntry_v1 +} + +type DeviceArchitecture uint32 + +type BusType uint32 + +type FanControlPolicy uint32 + +type PowerSource uint32 + +type GpuDynamicPstatesInfo struct { + Flags uint32 + Utilization [8]_Ctype_struct___23 +} + +type PowerScopeType byte + +type PowerValue_v2 struct { + Version uint32 + PowerScope uint8 + PowerValueMw uint32 +} + +type nvmlVgpuTypeId uint32 + +type nvmlVgpuInstance uint32 + +type VgpuHeterogeneousMode_v1 struct { + Version uint32 + Mode uint32 +} + +type VgpuHeterogeneousMode struct { + Version uint32 + Mode uint32 +} + +type VgpuPlacementId_v1 struct { + Version uint32 + PlacementId uint32 +} + +type VgpuPlacementId struct { + Version uint32 + PlacementId uint32 +} + +type VgpuPlacementList_v1 struct { + Version uint32 + PlacementSize uint32 + Count uint32 + PlacementIds *uint32 +} + +type VgpuPlacementList_v2 struct { + Version uint32 + PlacementSize uint32 + Count uint32 + PlacementIds *uint32 + Mode uint32 + Pad_cgo_0 [4]byte +} + +type VgpuPlacementList struct { + Version uint32 + PlacementSize uint32 + Count uint32 + PlacementIds *uint32 + Mode uint32 + Pad_cgo_0 [4]byte +} + +type VgpuTypeBar1Info_v1 struct { + Version uint32 + Bar1Size uint64 +} + +type VgpuTypeBar1Info struct { + Version uint32 + Bar1Size uint64 +} + +type VgpuInstanceUtilizationSample struct { + VgpuInstance uint32 + TimeStamp uint64 + SmUtil [8]byte + MemUtil [8]byte + EncUtil [8]byte + DecUtil [8]byte +} + +type VgpuInstanceUtilizationInfo_v1 struct { + TimeStamp uint64 + VgpuInstance uint32 + Pad_cgo_0 [4]byte + SmUtil [8]byte + MemUtil [8]byte + EncUtil [8]byte + DecUtil [8]byte + JpgUtil [8]byte + OfaUtil [8]byte +} + +type VgpuInstancesUtilizationInfo_v1 struct { + Version uint32 + SampleValType uint32 + VgpuInstanceCount uint32 + LastSeenTimeStamp uint64 + VgpuUtilArray *VgpuInstanceUtilizationInfo_v1 +} + +type VgpuInstancesUtilizationInfo struct { + Version uint32 + SampleValType uint32 + VgpuInstanceCount uint32 + LastSeenTimeStamp uint64 + VgpuUtilArray *VgpuInstanceUtilizationInfo_v1 +} + +type VgpuProcessUtilizationSample struct { + VgpuInstance uint32 + Pid uint32 + ProcessName [64]uint8 + TimeStamp uint64 + SmUtil uint32 + MemUtil uint32 + EncUtil uint32 + DecUtil uint32 +} + +type VgpuProcessUtilizationInfo_v1 struct { + ProcessName [64]uint8 + TimeStamp uint64 + VgpuInstance uint32 + Pid uint32 + SmUtil uint32 + MemUtil uint32 + EncUtil uint32 + DecUtil uint32 + JpgUtil uint32 + OfaUtil uint32 +} + +type VgpuProcessesUtilizationInfo_v1 struct { + Version uint32 + VgpuProcessCount uint32 + LastSeenTimeStamp uint64 + VgpuProcUtilArray *VgpuProcessUtilizationInfo_v1 +} + +type VgpuProcessesUtilizationInfo struct { + Version uint32 + VgpuProcessCount uint32 + LastSeenTimeStamp uint64 + VgpuProcUtilArray *VgpuProcessUtilizationInfo_v1 +} + +type VgpuRuntimeState_v1 struct { + Version uint32 + Size uint64 +} + +type VgpuRuntimeState struct { + Version uint32 + Size uint64 +} + +const sizeofVgpuSchedulerParams = unsafe.Sizeof([8]byte{}) + +type VgpuSchedulerParams [sizeofVgpuSchedulerParams]byte + +type VgpuSchedulerLogEntry struct { + Timestamp uint64 + TimeRunTotal uint64 + TimeRun uint64 + SwRunlistId uint32 + TargetTimeSlice uint64 + CumulativePreemptionTime uint64 +} + +type VgpuSchedulerLog struct { + EngineId uint32 + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte + EntriesCount uint32 + LogEntries [200]VgpuSchedulerLogEntry +} + +type VgpuSchedulerGetState struct { + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte +} + +const sizeofVgpuSchedulerSetParams = unsafe.Sizeof([8]byte{}) + +type VgpuSchedulerSetParams [sizeofVgpuSchedulerSetParams]byte + +type VgpuSchedulerSetState struct { + SchedulerPolicy uint32 + EnableARRMode uint32 + SchedulerParams [8]byte +} + +type VgpuSchedulerCapabilities struct { + SupportedSchedulers [3]uint32 + MaxTimeslice uint32 + MinTimeslice uint32 + IsArrModeSupported uint32 + MaxFrequencyForARR uint32 + MinFrequencyForARR uint32 + MaxAvgFactorForARR uint32 + MinAvgFactorForARR uint32 +} + +type VgpuLicenseExpiry struct { + Year uint32 + Month uint16 + Day uint16 + Hour uint16 + Min uint16 + Sec uint16 + Status uint8 + Pad_cgo_0 [1]byte +} + +type VgpuLicenseInfo struct { + IsLicensed uint8 + LicenseExpiry VgpuLicenseExpiry + CurrentState uint32 +} + +type GridLicenseExpiry struct { + Year uint32 + Month uint16 + Day uint16 + Hour uint16 + Min uint16 + Sec uint16 + Status uint8 + Pad_cgo_0 [1]byte +} + +type GridLicensableFeature struct { + FeatureCode uint32 + FeatureState uint32 + LicenseInfo [128]uint8 + ProductName [128]uint8 + FeatureEnabled uint32 + LicenseExpiry GridLicenseExpiry +} + +type GridLicensableFeatures struct { + IsGridLicenseSupported int32 + LicensableFeaturesCount uint32 + GridLicensableFeatures [3]GridLicensableFeature +} + +type VgpuTypeIdInfo_v1 struct { + Version uint32 + VgpuCount uint32 + VgpuTypeIds *uint32 +} + +type VgpuTypeIdInfo struct { + Version uint32 + VgpuCount uint32 + VgpuTypeIds *uint32 +} + +type VgpuTypeMaxInstance_v1 struct { + Version uint32 + VgpuTypeId uint32 + MaxInstancePerGI uint32 +} + +type VgpuTypeMaxInstance struct { + Version uint32 + VgpuTypeId uint32 + MaxInstancePerGI uint32 +} + +type ActiveVgpuInstanceInfo_v1 struct { + Version uint32 + VgpuCount uint32 + VgpuInstances *uint32 +} + +type ActiveVgpuInstanceInfo struct { + Version uint32 + VgpuCount uint32 + VgpuInstances *uint32 +} + +type VgpuSchedulerState_v1 struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + EnableARRMode uint32 + SchedulerParams [8]byte +} + +type VgpuSchedulerState struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + EnableARRMode uint32 + SchedulerParams [8]byte +} + +type VgpuSchedulerStateInfo_v1 struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte +} + +type VgpuSchedulerStateInfo struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte +} + +type VgpuSchedulerLogInfo_v1 struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte + EntriesCount uint32 + LogEntries [200]VgpuSchedulerLogEntry +} + +type VgpuSchedulerLogInfo struct { + Version uint32 + EngineId uint32 + SchedulerPolicy uint32 + ArrMode uint32 + SchedulerParams [8]byte + EntriesCount uint32 + LogEntries [200]VgpuSchedulerLogEntry +} + +type VgpuCreatablePlacementInfo_v1 struct { + Version uint32 + VgpuTypeId uint32 + Count uint32 + PlacementIds *uint32 + PlacementSize uint32 + Pad_cgo_0 [4]byte +} + +type VgpuCreatablePlacementInfo struct { + Version uint32 + VgpuTypeId uint32 + Count uint32 + PlacementIds *uint32 + PlacementSize uint32 + Pad_cgo_0 [4]byte +} + +type NvLinkPowerThres struct { + LowPwrThreshold uint32 +} + +type FieldValue struct { + FieldId uint32 + ScopeId uint32 + Timestamp int64 + LatencyUsec int64 + ValueType uint32 + NvmlReturn uint32 + Value [8]byte +} + +type nvmlUnit struct { + Handle *_Ctype_struct_nvmlUnit_st +} + +type HwbcEntry struct { + HwbcId uint32 + FirmwareVersion [32]uint8 +} + +type LedState struct { + Cause [256]uint8 + Color uint32 +} + +type UnitInfo struct { + Name [96]uint8 + Id [96]uint8 + Serial [96]uint8 + FirmwareVersion [96]uint8 +} + +type PSUInfo struct { + State [256]uint8 + Current uint32 + Voltage uint32 + Power uint32 +} + +type UnitFanInfo struct { + Speed uint32 + State uint32 +} + +type UnitFanSpeeds struct { + Fans [24]UnitFanInfo + Count uint32 +} + +type nvmlEventSet struct { + Handle *_Ctype_struct_nvmlEventSet_st +} + +type nvmlEventData struct { + Device nvmlDevice + EventType uint64 + EventData uint64 + GpuInstanceId uint32 + ComputeInstanceId uint32 +} + +type SystemEventSet struct { + Handle *_Ctype_struct_nvmlSystemEventSet_st +} + +type SystemEventSetCreateRequest_v1 struct { + Version uint32 + Set SystemEventSet +} + +type SystemEventSetCreateRequest struct { + Version uint32 + Set SystemEventSet +} + +type SystemEventSetFreeRequest_v1 struct { + Version uint32 + Set SystemEventSet +} + +type SystemEventSetFreeRequest struct { + Version uint32 + Set SystemEventSet +} + +type SystemRegisterEventRequest_v1 struct { + Version uint32 + EventTypes uint64 + Set SystemEventSet +} + +type SystemRegisterEventRequest struct { + Version uint32 + EventTypes uint64 + Set SystemEventSet +} + +type SystemEventData_v1 struct { + EventType uint64 + GpuId uint32 + Pad_cgo_0 [4]byte +} + +type SystemEventSetWaitRequest_v1 struct { + Version uint32 + Timeoutms uint32 + Set SystemEventSet + Data *SystemEventData_v1 + DataSize uint32 + NumEvent uint32 +} + +type SystemEventSetWaitRequest struct { + Version uint32 + Timeoutms uint32 + Set SystemEventSet + Data *SystemEventData_v1 + DataSize uint32 + NumEvent uint32 +} + +type AccountingStats struct { + GpuUtilization uint32 + MemoryUtilization uint32 + MaxMemoryUsage uint64 + Time uint64 + StartTime uint64 + IsRunning uint32 + Reserved [5]uint32 +} + +type EncoderSessionInfo struct { + SessionId uint32 + Pid uint32 + VgpuInstance uint32 + CodecType uint32 + HResolution uint32 + VResolution uint32 + AverageFps uint32 + AverageLatency uint32 +} + +type FBCStats struct { + SessionsCount uint32 + AverageFPS uint32 + AverageLatency uint32 +} + +type FBCSessionInfo struct { + SessionId uint32 + Pid uint32 + VgpuInstance uint32 + DisplayOrdinal uint32 + SessionType uint32 + SessionFlags uint32 + HMaxResolution uint32 + VMaxResolution uint32 + HResolution uint32 + VResolution uint32 + AverageFPS uint32 + AverageLatency uint32 +} + +type ConfComputeSystemCaps struct { + CpuCaps uint32 + GpusCaps uint32 +} + +type ConfComputeSystemState struct { + Environment uint32 + CcFeature uint32 + DevToolsMode uint32 +} + +type SystemConfComputeSettings_v1 struct { + Version uint32 + Environment uint32 + CcFeature uint32 + DevToolsMode uint32 + MultiGpuMode uint32 +} + +type SystemConfComputeSettings struct { + Version uint32 + Environment uint32 + CcFeature uint32 + DevToolsMode uint32 + MultiGpuMode uint32 +} + +type ConfComputeMemSizeInfo struct { + ProtectedMemSizeKib uint64 + UnprotectedMemSizeKib uint64 +} + +type ConfComputeGpuCertificate struct { + CertChainSize uint32 + AttestationCertChainSize uint32 + CertChain [4096]uint8 + AttestationCertChain [5120]uint8 +} + +type ConfComputeGpuAttestationReport struct { + IsCecAttestationReportPresent uint32 + AttestationReportSize uint32 + CecAttestationReportSize uint32 + Nonce [32]uint8 + AttestationReport [8192]uint8 + CecAttestationReport [4096]uint8 +} + +type ConfComputeSetKeyRotationThresholdInfo_v1 struct { + Version uint32 + MaxAttackerAdvantage uint64 +} + +type ConfComputeSetKeyRotationThresholdInfo struct { + Version uint32 + MaxAttackerAdvantage uint64 +} + +type ConfComputeGetKeyRotationThresholdInfo_v1 struct { + Version uint32 + AttackerAdvantage uint64 +} + +type ConfComputeGetKeyRotationThresholdInfo struct { + Version uint32 + AttackerAdvantage uint64 +} + +type GpuFabricState byte + +type GpuFabricInfo struct { + ClusterUuid [16]uint8 + Status uint32 + CliqueId uint32 + State uint8 + Pad_cgo_0 [3]byte +} + +type GpuFabricInfo_v2 struct { + Version uint32 + ClusterUuid [16]uint8 + Status uint32 + CliqueId uint32 + State uint8 + HealthMask uint32 +} + +type GpuFabricInfo_v3 struct { + Version uint32 + ClusterUuid [16]uint8 + Status uint32 + CliqueId uint32 + State uint8 + HealthMask uint32 + HealthSummary uint8 + Pad_cgo_0 [3]byte +} + +type GpuFabricInfoV struct { + Version uint32 + ClusterUuid [16]uint8 + Status uint32 + CliqueId uint32 + State uint8 + HealthMask uint32 + HealthSummary uint8 + Pad_cgo_0 [3]byte +} + +type SystemDriverBranchInfo_v1 struct { + Version uint32 + Branch [80]uint8 +} + +type SystemDriverBranchInfo struct { + Version uint32 + Branch [80]uint8 +} + +type AffinityScope uint32 + +type Temperature_v1 struct { + Version uint32 + SensorType uint32 + Temperature int32 +} + +type Temperature struct { + Version uint32 + SensorType uint32 + Temperature int32 +} + +type NvlinkSupportedBwModes_v1 struct { + Version uint32 + BwModes [23]uint8 + TotalBwModes uint8 +} + +type NvlinkSupportedBwModes struct { + Version uint32 + BwModes [23]uint8 + TotalBwModes uint8 +} + +type NvlinkGetBwMode_v1 struct { + Version uint32 + BIsBest uint32 + BwMode uint8 + Pad_cgo_0 [3]byte +} + +type NvlinkGetBwMode struct { + Version uint32 + BIsBest uint32 + BwMode uint8 + Pad_cgo_0 [3]byte +} + +type NvlinkSetBwMode_v1 struct { + Version uint32 + BSetBest uint32 + BwMode uint8 + Pad_cgo_0 [3]byte +} + +type NvlinkSetBwMode struct { + Version uint32 + BSetBest uint32 + BwMode uint8 + Pad_cgo_0 [3]byte +} + +type NvLinkInfo_v1 struct { + Version uint32 + IsNvleEnabled uint32 +} + +type NvlinkFirmwareVersion struct { + UcodeType uint8 + Major uint32 + Minor uint32 + SubMinor uint32 +} + +type NvlinkFirmwareInfo struct { + FirmwareVersion [100]NvlinkFirmwareVersion + NumValidEntries uint32 +} + +type NvLinkInfo_v2 struct { + Version uint32 + IsNvleEnabled uint32 + FirmwareInfo NvlinkFirmwareInfo +} + +type NvLinkInfo struct { + Version uint32 + IsNvleEnabled uint32 + FirmwareInfo NvlinkFirmwareInfo +} + +type VgpuVersion struct { + MinVersion uint32 + MaxVersion uint32 +} + +type nvmlVgpuMetadata struct { + Version uint32 + Revision uint32 + GuestInfoState uint32 + GuestDriverVersion [80]uint8 + HostDriverVersion [80]uint8 + Reserved [6]uint32 + VgpuVirtualizationCaps uint32 + GuestVgpuVersion uint32 + OpaqueDataSize uint32 + OpaqueData [4]uint8 +} + +type nvmlVgpuPgpuMetadata struct { + Version uint32 + Revision uint32 + HostDriverVersion [80]uint8 + PgpuVirtualizationCaps uint32 + Reserved [5]uint32 + HostSupportedVgpuRange VgpuVersion + OpaqueDataSize uint32 + OpaqueData [4]uint8 +} + +type VgpuPgpuCompatibility struct { + VgpuVmCompatibility uint32 + CompatibilityLimitCode uint32 +} + +type ExcludedDeviceInfo struct { + PciInfo PciInfo + Uuid [80]uint8 +} + +type PRMTLV_v1 struct { + DataSize uint32 + Status uint32 + InData [496]uint8 +} + +type GpuInstancePlacement struct { + Start uint32 + Size uint32 +} + +type GpuInstanceProfileInfo struct { + Id uint32 + IsP2pSupported uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + CopyEngineCount uint32 + DecoderCount uint32 + EncoderCount uint32 + JpegCount uint32 + OfaCount uint32 + MemorySizeMB uint64 +} + +type GpuInstanceProfileInfo_v2 struct { + Version uint32 + Id uint32 + IsP2pSupported uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + CopyEngineCount uint32 + DecoderCount uint32 + EncoderCount uint32 + JpegCount uint32 + OfaCount uint32 + MemorySizeMB uint64 + Name [96]uint8 +} + +type GpuInstanceProfileInfo_v3 struct { + Version uint32 + Id uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + CopyEngineCount uint32 + DecoderCount uint32 + EncoderCount uint32 + JpegCount uint32 + OfaCount uint32 + MemorySizeMB uint64 + Name [96]uint8 + Capabilities uint32 + Pad_cgo_0 [4]byte +} + +type nvmlGpuInstanceInfo struct { + Device nvmlDevice + Id uint32 + ProfileId uint32 + Placement GpuInstancePlacement +} + +type ComputeInstancePlacement struct { + Start uint32 + Size uint32 +} + +type ComputeInstanceProfileInfo struct { + Id uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + SharedCopyEngineCount uint32 + SharedDecoderCount uint32 + SharedEncoderCount uint32 + SharedJpegCount uint32 + SharedOfaCount uint32 +} + +type ComputeInstanceProfileInfo_v2 struct { + Version uint32 + Id uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + SharedCopyEngineCount uint32 + SharedDecoderCount uint32 + SharedEncoderCount uint32 + SharedJpegCount uint32 + SharedOfaCount uint32 + Name [96]uint8 +} + +type ComputeInstanceProfileInfo_v3 struct { + Version uint32 + Id uint32 + SliceCount uint32 + InstanceCount uint32 + MultiprocessorCount uint32 + SharedCopyEngineCount uint32 + SharedDecoderCount uint32 + SharedEncoderCount uint32 + SharedJpegCount uint32 + SharedOfaCount uint32 + Name [96]uint8 + Capabilities uint32 +} + +type nvmlComputeInstanceInfo struct { + Device nvmlDevice + GpuInstance nvmlGpuInstance + Id uint32 + ProfileId uint32 + Placement ComputeInstancePlacement +} + +type nvmlComputeInstance struct { + Handle *_Ctype_struct_nvmlComputeInstance_st +} + +type nvmlGpmSample struct { + Handle *_Ctype_struct_nvmlGpmSample_st +} + +type GpmMetric struct { + MetricId uint32 + NvmlReturn uint32 + Value float64 + MetricInfo _Ctype_struct___19 +} + +type nvmlGpmMetricsGetType struct { + Version uint32 + NumMetrics uint32 + Sample1 nvmlGpmSample + Sample2 nvmlGpmSample + Metrics [210]GpmMetric +} + +type GpmSupport struct { + Version uint32 + IsSupportedDevice uint32 +} + +type DeviceCapabilities_v1 struct { + Version uint32 + CapMask uint32 +} + +type DeviceCapabilities struct { + Version uint32 + CapMask uint32 +} + +type Mask255 struct { + Mask [8]uint32 +} + +type WorkloadPowerProfileInfo_v1 struct { + Version uint32 + ProfileId uint32 + Priority uint32 + ConflictingMask Mask255 +} + +type WorkloadPowerProfileInfo struct { + Version uint32 + ProfileId uint32 + Priority uint32 + ConflictingMask Mask255 +} + +type WorkloadPowerProfileProfilesInfo_v1 struct { + Version uint32 + PerfProfilesMask Mask255 + PerfProfile [255]WorkloadPowerProfileInfo +} + +type WorkloadPowerProfileProfilesInfo struct { + Version uint32 + PerfProfilesMask Mask255 + PerfProfile [255]WorkloadPowerProfileInfo +} + +type WorkloadPowerProfileCurrentProfiles_v1 struct { + Version uint32 + PerfProfilesMask Mask255 + RequestedProfilesMask Mask255 + EnforcedProfilesMask Mask255 +} + +type WorkloadPowerProfileCurrentProfiles struct { + Version uint32 + PerfProfilesMask Mask255 + RequestedProfilesMask Mask255 + EnforcedProfilesMask Mask255 +} + +type WorkloadPowerProfileRequestedProfiles_v1 struct { + Version uint32 + RequestedProfilesMask Mask255 +} + +type WorkloadPowerProfileRequestedProfiles struct { + Version uint32 + RequestedProfilesMask Mask255 +} + +type PowerSmoothingProfile_v1 struct { + Version uint32 + ProfileId uint32 + ParamId uint32 + Value float64 +} + +type PowerSmoothingProfile struct { + Version uint32 + ProfileId uint32 + ParamId uint32 + Value float64 +} + +type PowerSmoothingState_v1 struct { + Version uint32 + State uint32 +} + +type PowerSmoothingState struct { + Version uint32 + State uint32 +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/unit.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/unit.go new file mode 100644 index 00000000..617ad546 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/unit.go @@ -0,0 +1,113 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +// nvml.UnitGetCount() +func (l *library) UnitGetCount() (int, Return) { + var UnitCount uint32 + ret := nvmlUnitGetCount(&UnitCount) + return int(UnitCount), ret +} + +// nvml.UnitGetHandleByIndex() +func (l *library) UnitGetHandleByIndex(index int) (Unit, Return) { + var unit nvmlUnit + ret := nvmlUnitGetHandleByIndex(uint32(index), &unit) + return unit, ret +} + +// nvml.UnitGetUnitInfo() +func (l *library) UnitGetUnitInfo(unit Unit) (UnitInfo, Return) { + return unit.GetUnitInfo() +} + +func (unit nvmlUnit) GetUnitInfo() (UnitInfo, Return) { + var info UnitInfo + ret := nvmlUnitGetUnitInfo(unit, &info) + return info, ret +} + +// nvml.UnitGetLedState() +func (l *library) UnitGetLedState(unit Unit) (LedState, Return) { + return unit.GetLedState() +} + +func (unit nvmlUnit) GetLedState() (LedState, Return) { + var state LedState + ret := nvmlUnitGetLedState(unit, &state) + return state, ret +} + +// nvml.UnitGetPsuInfo() +func (l *library) UnitGetPsuInfo(unit Unit) (PSUInfo, Return) { + return unit.GetPsuInfo() +} + +func (unit nvmlUnit) GetPsuInfo() (PSUInfo, Return) { + var psu PSUInfo + ret := nvmlUnitGetPsuInfo(unit, &psu) + return psu, ret +} + +// nvml.UnitGetTemperature() +func (l *library) UnitGetTemperature(unit Unit, ttype int) (uint32, Return) { + return unit.GetTemperature(ttype) +} + +func (unit nvmlUnit) GetTemperature(ttype int) (uint32, Return) { + var temp uint32 + ret := nvmlUnitGetTemperature(unit, uint32(ttype), &temp) + return temp, ret +} + +// nvml.UnitGetFanSpeedInfo() +func (l *library) UnitGetFanSpeedInfo(unit Unit) (UnitFanSpeeds, Return) { + return unit.GetFanSpeedInfo() +} + +func (unit nvmlUnit) GetFanSpeedInfo() (UnitFanSpeeds, Return) { + var fanSpeeds UnitFanSpeeds + ret := nvmlUnitGetFanSpeedInfo(unit, &fanSpeeds) + return fanSpeeds, ret +} + +// nvml.UnitGetDevices() +func (l *library) UnitGetDevices(unit Unit) ([]Device, Return) { + return unit.GetDevices() +} + +func (unit nvmlUnit) GetDevices() ([]Device, Return) { + var deviceCount uint32 = 1 // Will be reduced upon returning + for { + devices := make([]nvmlDevice, deviceCount) + ret := nvmlUnitGetDevices(unit, &deviceCount, &devices[0]) + if ret == SUCCESS { + return convertSlice[nvmlDevice, Device](devices[:deviceCount]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + deviceCount *= 2 + } +} + +// nvml.UnitSetLedState() +func (l *library) UnitSetLedState(unit Unit, color LedColor) Return { + return unit.SetLedState(color) +} + +func (unit nvmlUnit) SetLedState(color LedColor) Return { + return nvmlUnitSetLedState(unit, color) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/vgpu.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/vgpu.go new file mode 100644 index 00000000..9ab649a4 --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/vgpu.go @@ -0,0 +1,511 @@ +// Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package nvml + +import ( + "unsafe" +) + +// nvml.VgpuMetadata +type VgpuMetadata struct { + nvmlVgpuMetadata + OpaqueData []byte +} + +// nvml.VgpuPgpuMetadata +type VgpuPgpuMetadata struct { + nvmlVgpuPgpuMetadata + OpaqueData []byte +} + +// nvml.VgpuTypeGetClass() +func (l *library) VgpuTypeGetClass(vgpuTypeId VgpuTypeId) (string, Return) { + return vgpuTypeId.GetClass() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetClass() (string, Return) { + var size uint32 = DEVICE_NAME_BUFFER_SIZE + vgpuTypeClass := make([]byte, DEVICE_NAME_BUFFER_SIZE) + ret := nvmlVgpuTypeGetClass(vgpuTypeId, &vgpuTypeClass[0], &size) + return string(vgpuTypeClass[:clen(vgpuTypeClass)]), ret +} + +// nvml.VgpuTypeGetName() +func (l *library) VgpuTypeGetName(vgpuTypeId VgpuTypeId) (string, Return) { + return vgpuTypeId.GetName() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetName() (string, Return) { + var size uint32 = DEVICE_NAME_BUFFER_SIZE + vgpuTypeName := make([]byte, DEVICE_NAME_BUFFER_SIZE) + ret := nvmlVgpuTypeGetName(vgpuTypeId, &vgpuTypeName[0], &size) + return string(vgpuTypeName[:clen(vgpuTypeName)]), ret +} + +// nvml.VgpuTypeGetGpuInstanceProfileId() +func (l *library) VgpuTypeGetGpuInstanceProfileId(vgpuTypeId VgpuTypeId) (uint32, Return) { + return vgpuTypeId.GetGpuInstanceProfileId() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetGpuInstanceProfileId() (uint32, Return) { + var size uint32 + ret := nvmlVgpuTypeGetGpuInstanceProfileId(vgpuTypeId, &size) + return size, ret +} + +// nvml.VgpuTypeGetDeviceID() +func (l *library) VgpuTypeGetDeviceID(vgpuTypeId VgpuTypeId) (uint64, uint64, Return) { + return vgpuTypeId.GetDeviceID() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetDeviceID() (uint64, uint64, Return) { + var deviceID, subsystemID uint64 + ret := nvmlVgpuTypeGetDeviceID(vgpuTypeId, &deviceID, &subsystemID) + return deviceID, subsystemID, ret +} + +// nvml.VgpuTypeGetFramebufferSize() +func (l *library) VgpuTypeGetFramebufferSize(vgpuTypeId VgpuTypeId) (uint64, Return) { + return vgpuTypeId.GetFramebufferSize() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetFramebufferSize() (uint64, Return) { + var fbSize uint64 + ret := nvmlVgpuTypeGetFramebufferSize(vgpuTypeId, &fbSize) + return fbSize, ret +} + +// nvml.VgpuTypeGetNumDisplayHeads() +func (l *library) VgpuTypeGetNumDisplayHeads(vgpuTypeId VgpuTypeId) (int, Return) { + return vgpuTypeId.GetNumDisplayHeads() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetNumDisplayHeads() (int, Return) { + var numDisplayHeads uint32 + ret := nvmlVgpuTypeGetNumDisplayHeads(vgpuTypeId, &numDisplayHeads) + return int(numDisplayHeads), ret +} + +// nvml.VgpuTypeGetResolution() +func (l *library) VgpuTypeGetResolution(vgpuTypeId VgpuTypeId, displayIndex int) (uint32, uint32, Return) { + return vgpuTypeId.GetResolution(displayIndex) +} + +func (vgpuTypeId nvmlVgpuTypeId) GetResolution(displayIndex int) (uint32, uint32, Return) { + var xdim, ydim uint32 + ret := nvmlVgpuTypeGetResolution(vgpuTypeId, uint32(displayIndex), &xdim, &ydim) + return xdim, ydim, ret +} + +// nvml.VgpuTypeGetLicense() +func (l *library) VgpuTypeGetLicense(vgpuTypeId VgpuTypeId) (string, Return) { + return vgpuTypeId.GetLicense() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetLicense() (string, Return) { + vgpuTypeLicenseString := make([]byte, GRID_LICENSE_BUFFER_SIZE) + ret := nvmlVgpuTypeGetLicense(vgpuTypeId, &vgpuTypeLicenseString[0], GRID_LICENSE_BUFFER_SIZE) + return string(vgpuTypeLicenseString[:clen(vgpuTypeLicenseString)]), ret +} + +// nvml.VgpuTypeGetFrameRateLimit() +func (l *library) VgpuTypeGetFrameRateLimit(vgpuTypeId VgpuTypeId) (uint32, Return) { + return vgpuTypeId.GetFrameRateLimit() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetFrameRateLimit() (uint32, Return) { + var frameRateLimit uint32 + ret := nvmlVgpuTypeGetFrameRateLimit(vgpuTypeId, &frameRateLimit) + return frameRateLimit, ret +} + +// nvml.VgpuTypeGetMaxInstances() +func (l *library) VgpuTypeGetMaxInstances(device Device, vgpuTypeId VgpuTypeId) (int, Return) { + return vgpuTypeId.GetMaxInstances(device) +} + +func (device nvmlDevice) VgpuTypeGetMaxInstances(vgpuTypeId VgpuTypeId) (int, Return) { + return vgpuTypeId.GetMaxInstances(device) +} + +func (vgpuTypeId nvmlVgpuTypeId) GetMaxInstances(device Device) (int, Return) { + var vgpuInstanceCount uint32 + ret := nvmlVgpuTypeGetMaxInstances(nvmlDeviceHandle(device), vgpuTypeId, &vgpuInstanceCount) + return int(vgpuInstanceCount), ret +} + +// nvml.VgpuTypeGetMaxInstancesPerVm() +func (l *library) VgpuTypeGetMaxInstancesPerVm(vgpuTypeId VgpuTypeId) (int, Return) { + return vgpuTypeId.GetMaxInstancesPerVm() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetMaxInstancesPerVm() (int, Return) { + var vgpuInstanceCountPerVm uint32 + ret := nvmlVgpuTypeGetMaxInstancesPerVm(vgpuTypeId, &vgpuInstanceCountPerVm) + return int(vgpuInstanceCountPerVm), ret +} + +// nvml.VgpuInstanceGetVmID() +func (l *library) VgpuInstanceGetVmID(vgpuInstance VgpuInstance) (string, VgpuVmIdType, Return) { + return vgpuInstance.GetVmID() +} + +func (vgpuInstance nvmlVgpuInstance) GetVmID() (string, VgpuVmIdType, Return) { + var vmIdType VgpuVmIdType + vmId := make([]byte, DEVICE_UUID_BUFFER_SIZE) + ret := nvmlVgpuInstanceGetVmID(vgpuInstance, &vmId[0], DEVICE_UUID_BUFFER_SIZE, &vmIdType) + return string(vmId[:clen(vmId)]), vmIdType, ret +} + +// nvml.VgpuInstanceGetUUID() +func (l *library) VgpuInstanceGetUUID(vgpuInstance VgpuInstance) (string, Return) { + return vgpuInstance.GetUUID() +} + +func (vgpuInstance nvmlVgpuInstance) GetUUID() (string, Return) { + uuid := make([]byte, DEVICE_UUID_BUFFER_SIZE) + ret := nvmlVgpuInstanceGetUUID(vgpuInstance, &uuid[0], DEVICE_UUID_BUFFER_SIZE) + return string(uuid[:clen(uuid)]), ret +} + +// nvml.VgpuInstanceGetVmDriverVersion() +func (l *library) VgpuInstanceGetVmDriverVersion(vgpuInstance VgpuInstance) (string, Return) { + return vgpuInstance.GetVmDriverVersion() +} + +func (vgpuInstance nvmlVgpuInstance) GetVmDriverVersion() (string, Return) { + version := make([]byte, SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + ret := nvmlVgpuInstanceGetVmDriverVersion(vgpuInstance, &version[0], SYSTEM_DRIVER_VERSION_BUFFER_SIZE) + return string(version[:clen(version)]), ret +} + +// nvml.VgpuInstanceGetFbUsage() +func (l *library) VgpuInstanceGetFbUsage(vgpuInstance VgpuInstance) (uint64, Return) { + return vgpuInstance.GetFbUsage() +} + +func (vgpuInstance nvmlVgpuInstance) GetFbUsage() (uint64, Return) { + var fbUsage uint64 + ret := nvmlVgpuInstanceGetFbUsage(vgpuInstance, &fbUsage) + return fbUsage, ret +} + +// nvml.VgpuInstanceGetLicenseInfo() +func (l *library) VgpuInstanceGetLicenseInfo(vgpuInstance VgpuInstance) (VgpuLicenseInfo, Return) { + return vgpuInstance.GetLicenseInfo() +} + +func (vgpuInstance nvmlVgpuInstance) GetLicenseInfo() (VgpuLicenseInfo, Return) { + var licenseInfo VgpuLicenseInfo + ret := nvmlVgpuInstanceGetLicenseInfo(vgpuInstance, &licenseInfo) + return licenseInfo, ret +} + +// nvml.VgpuInstanceGetLicenseStatus() +// +// Deprecated: Use VgpuInstanceGetLicenseInfo instead. +func (l *library) VgpuInstanceGetLicenseStatus(vgpuInstance VgpuInstance) (int, Return) { + return vgpuInstance.GetLicenseStatus() +} + +func (vgpuInstance nvmlVgpuInstance) GetLicenseStatus() (int, Return) { + var licensed uint32 + ret := nvmlVgpuInstanceGetLicenseStatus(vgpuInstance, &licensed) + return int(licensed), ret +} + +// nvml.VgpuInstanceGetType() +func (l *library) VgpuInstanceGetType(vgpuInstance VgpuInstance) (VgpuTypeId, Return) { + return vgpuInstance.GetType() +} + +func (vgpuInstance nvmlVgpuInstance) GetType() (VgpuTypeId, Return) { + var vgpuTypeId nvmlVgpuTypeId + ret := nvmlVgpuInstanceGetType(vgpuInstance, &vgpuTypeId) + return vgpuTypeId, ret +} + +// nvml.VgpuInstanceGetFrameRateLimit() +func (l *library) VgpuInstanceGetFrameRateLimit(vgpuInstance VgpuInstance) (uint32, Return) { + return vgpuInstance.GetFrameRateLimit() +} + +func (vgpuInstance nvmlVgpuInstance) GetFrameRateLimit() (uint32, Return) { + var frameRateLimit uint32 + ret := nvmlVgpuInstanceGetFrameRateLimit(vgpuInstance, &frameRateLimit) + return frameRateLimit, ret +} + +// nvml.VgpuInstanceGetEccMode() +func (l *library) VgpuInstanceGetEccMode(vgpuInstance VgpuInstance) (EnableState, Return) { + return vgpuInstance.GetEccMode() +} + +func (vgpuInstance nvmlVgpuInstance) GetEccMode() (EnableState, Return) { + var eccMode EnableState + ret := nvmlVgpuInstanceGetEccMode(vgpuInstance, &eccMode) + return eccMode, ret +} + +// nvml.VgpuInstanceGetEncoderCapacity() +func (l *library) VgpuInstanceGetEncoderCapacity(vgpuInstance VgpuInstance) (int, Return) { + return vgpuInstance.GetEncoderCapacity() +} + +func (vgpuInstance nvmlVgpuInstance) GetEncoderCapacity() (int, Return) { + var encoderCapacity uint32 + ret := nvmlVgpuInstanceGetEncoderCapacity(vgpuInstance, &encoderCapacity) + return int(encoderCapacity), ret +} + +// nvml.VgpuInstanceSetEncoderCapacity() +func (l *library) VgpuInstanceSetEncoderCapacity(vgpuInstance VgpuInstance, encoderCapacity int) Return { + return vgpuInstance.SetEncoderCapacity(encoderCapacity) +} + +func (vgpuInstance nvmlVgpuInstance) SetEncoderCapacity(encoderCapacity int) Return { + return nvmlVgpuInstanceSetEncoderCapacity(vgpuInstance, uint32(encoderCapacity)) +} + +// nvml.VgpuInstanceGetEncoderStats() +func (l *library) VgpuInstanceGetEncoderStats(vgpuInstance VgpuInstance) (int, uint32, uint32, Return) { + return vgpuInstance.GetEncoderStats() +} + +func (vgpuInstance nvmlVgpuInstance) GetEncoderStats() (int, uint32, uint32, Return) { + var sessionCount, averageFps, averageLatency uint32 + ret := nvmlVgpuInstanceGetEncoderStats(vgpuInstance, &sessionCount, &averageFps, &averageLatency) + return int(sessionCount), averageFps, averageLatency, ret +} + +// nvml.VgpuInstanceGetEncoderSessions() +func (l *library) VgpuInstanceGetEncoderSessions(vgpuInstance VgpuInstance) (int, EncoderSessionInfo, Return) { + return vgpuInstance.GetEncoderSessions() +} + +func (vgpuInstance nvmlVgpuInstance) GetEncoderSessions() (int, EncoderSessionInfo, Return) { + var sessionCount uint32 + var sessionInfo EncoderSessionInfo + ret := nvmlVgpuInstanceGetEncoderSessions(vgpuInstance, &sessionCount, &sessionInfo) + return int(sessionCount), sessionInfo, ret +} + +// nvml.VgpuInstanceGetFBCStats() +func (l *library) VgpuInstanceGetFBCStats(vgpuInstance VgpuInstance) (FBCStats, Return) { + return vgpuInstance.GetFBCStats() +} + +func (vgpuInstance nvmlVgpuInstance) GetFBCStats() (FBCStats, Return) { + var fbcStats FBCStats + ret := nvmlVgpuInstanceGetFBCStats(vgpuInstance, &fbcStats) + return fbcStats, ret +} + +// nvml.VgpuInstanceGetFBCSessions() +func (l *library) VgpuInstanceGetFBCSessions(vgpuInstance VgpuInstance) (int, FBCSessionInfo, Return) { + return vgpuInstance.GetFBCSessions() +} + +func (vgpuInstance nvmlVgpuInstance) GetFBCSessions() (int, FBCSessionInfo, Return) { + var sessionCount uint32 + var sessionInfo FBCSessionInfo + ret := nvmlVgpuInstanceGetFBCSessions(vgpuInstance, &sessionCount, &sessionInfo) + return int(sessionCount), sessionInfo, ret +} + +// nvml.VgpuInstanceGetGpuInstanceId() +func (l *library) VgpuInstanceGetGpuInstanceId(vgpuInstance VgpuInstance) (int, Return) { + return vgpuInstance.GetGpuInstanceId() +} + +func (vgpuInstance nvmlVgpuInstance) GetGpuInstanceId() (int, Return) { + var gpuInstanceId uint32 + ret := nvmlVgpuInstanceGetGpuInstanceId(vgpuInstance, &gpuInstanceId) + return int(gpuInstanceId), ret +} + +// nvml.VgpuInstanceGetGpuPciId() +func (l *library) VgpuInstanceGetGpuPciId(vgpuInstance VgpuInstance) (string, Return) { + return vgpuInstance.GetGpuPciId() +} + +func (vgpuInstance nvmlVgpuInstance) GetGpuPciId() (string, Return) { + var length uint32 = 1 // Will be reduced upon returning + for { + vgpuPciId := make([]byte, length) + ret := nvmlVgpuInstanceGetGpuPciId(vgpuInstance, &vgpuPciId[0], &length) + if ret == SUCCESS { + return string(vgpuPciId[:clen(vgpuPciId)]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return "", ret + } + length *= 2 + } +} + +// nvml.VgpuInstanceGetMetadata() +func (l *library) VgpuInstanceGetMetadata(vgpuInstance VgpuInstance) (VgpuMetadata, Return) { + return vgpuInstance.GetMetadata() +} + +func (vgpuInstance nvmlVgpuInstance) GetMetadata() (VgpuMetadata, Return) { + var vgpuMetadata VgpuMetadata + opaqueDataSize := unsafe.Sizeof(vgpuMetadata.nvmlVgpuMetadata.OpaqueData) + vgpuMetadataSize := unsafe.Sizeof(vgpuMetadata.nvmlVgpuMetadata) - opaqueDataSize + for { + bufferSize := uint32(vgpuMetadataSize + opaqueDataSize) + buffer := make([]byte, bufferSize) + nvmlVgpuMetadataPtr := (*nvmlVgpuMetadata)(unsafe.Pointer(&buffer[0])) + ret := nvmlVgpuInstanceGetMetadata(vgpuInstance, nvmlVgpuMetadataPtr, &bufferSize) + if ret == SUCCESS { + vgpuMetadata.nvmlVgpuMetadata = *nvmlVgpuMetadataPtr + vgpuMetadata.OpaqueData = buffer[vgpuMetadataSize:bufferSize] + return vgpuMetadata, ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return vgpuMetadata, ret + } + opaqueDataSize = 2 * opaqueDataSize + } +} + +// nvml.VgpuInstanceGetAccountingMode() +func (l *library) VgpuInstanceGetAccountingMode(vgpuInstance VgpuInstance) (EnableState, Return) { + return vgpuInstance.GetAccountingMode() +} + +func (vgpuInstance nvmlVgpuInstance) GetAccountingMode() (EnableState, Return) { + var mode EnableState + ret := nvmlVgpuInstanceGetAccountingMode(vgpuInstance, &mode) + return mode, ret +} + +// nvml.VgpuInstanceGetAccountingPids() +func (l *library) VgpuInstanceGetAccountingPids(vgpuInstance VgpuInstance) ([]int, Return) { + return vgpuInstance.GetAccountingPids() +} + +func (vgpuInstance nvmlVgpuInstance) GetAccountingPids() ([]int, Return) { + var count uint32 = 1 // Will be reduced upon returning + for { + pids := make([]uint32, count) + ret := nvmlVgpuInstanceGetAccountingPids(vgpuInstance, &count, &pids[0]) + if ret == SUCCESS { + return uint32SliceToIntSlice(pids[:count]), ret + } + if ret != ERROR_INSUFFICIENT_SIZE { + return nil, ret + } + count *= 2 + } +} + +// nvml.VgpuInstanceGetAccountingStats() +func (l *library) VgpuInstanceGetAccountingStats(vgpuInstance VgpuInstance, pid int) (AccountingStats, Return) { + return vgpuInstance.GetAccountingStats(pid) +} + +func (vgpuInstance nvmlVgpuInstance) GetAccountingStats(pid int) (AccountingStats, Return) { + var stats AccountingStats + ret := nvmlVgpuInstanceGetAccountingStats(vgpuInstance, uint32(pid), &stats) + return stats, ret +} + +// nvml.GetVgpuCompatibility() +func (l *library) GetVgpuCompatibility(vgpuMetadata *VgpuMetadata, pgpuMetadata *VgpuPgpuMetadata) (VgpuPgpuCompatibility, Return) { + var compatibilityInfo VgpuPgpuCompatibility + ret := nvmlGetVgpuCompatibility(&vgpuMetadata.nvmlVgpuMetadata, &pgpuMetadata.nvmlVgpuPgpuMetadata, &compatibilityInfo) + return compatibilityInfo, ret +} + +// nvml.GetVgpuVersion() +func (l *library) GetVgpuVersion() (VgpuVersion, VgpuVersion, Return) { + var supported, current VgpuVersion + ret := nvmlGetVgpuVersion(&supported, ¤t) + return supported, current, ret +} + +// nvml.SetVgpuVersion() +func (l *library) SetVgpuVersion(vgpuVersion *VgpuVersion) Return { + return nvmlSetVgpuVersion(vgpuVersion) +} + +// nvml.VgpuInstanceClearAccountingPids() +func (l *library) VgpuInstanceClearAccountingPids(vgpuInstance VgpuInstance) Return { + return vgpuInstance.ClearAccountingPids() +} + +func (vgpuInstance nvmlVgpuInstance) ClearAccountingPids() Return { + return nvmlVgpuInstanceClearAccountingPids(vgpuInstance) +} + +// nvml.VgpuInstanceGetMdevUUID() +func (l *library) VgpuInstanceGetMdevUUID(vgpuInstance VgpuInstance) (string, Return) { + return vgpuInstance.GetMdevUUID() +} + +func (vgpuInstance nvmlVgpuInstance) GetMdevUUID() (string, Return) { + mdevUUID := make([]byte, DEVICE_UUID_BUFFER_SIZE) + ret := nvmlVgpuInstanceGetMdevUUID(vgpuInstance, &mdevUUID[0], DEVICE_UUID_BUFFER_SIZE) + return string(mdevUUID[:clen(mdevUUID)]), ret +} + +// nvml.VgpuTypeGetCapabilities() +func (l *library) VgpuTypeGetCapabilities(vgpuTypeId VgpuTypeId, capability VgpuCapability) (bool, Return) { + return vgpuTypeId.GetCapabilities(capability) +} + +func (vgpuTypeId nvmlVgpuTypeId) GetCapabilities(capability VgpuCapability) (bool, Return) { + var capResult uint32 + ret := nvmlVgpuTypeGetCapabilities(vgpuTypeId, capability, &capResult) + return (capResult != 0), ret +} + +// nvml.GetVgpuDriverCapabilities() +func (l *library) GetVgpuDriverCapabilities(capability VgpuDriverCapability) (bool, Return) { + var capResult uint32 + ret := nvmlGetVgpuDriverCapabilities(capability, &capResult) + return (capResult != 0), ret +} + +// nvml.VgpuTypeGetBAR1Info() +func (l *library) VgpuTypeGetBAR1Info(vgpuTypeId VgpuTypeId) (VgpuTypeBar1Info, Return) { + return vgpuTypeId.GetBAR1Info() +} + +func (vgpuTypeId nvmlVgpuTypeId) GetBAR1Info() (VgpuTypeBar1Info, Return) { + var bar1Info VgpuTypeBar1Info + bar1Info.Version = STRUCT_VERSION(bar1Info, 1) + ret := nvmlVgpuTypeGetBAR1Info(vgpuTypeId, &bar1Info) + return bar1Info, ret +} + +// nvml.VgpuInstanceGetRuntimeStateSize() +func (l *library) VgpuInstanceGetRuntimeStateSize(vgpuInstance VgpuInstance) (VgpuRuntimeState, Return) { + return vgpuInstance.GetRuntimeStateSize() +} + +func (vgpuInstance nvmlVgpuInstance) GetRuntimeStateSize() (VgpuRuntimeState, Return) { + var pState VgpuRuntimeState + pState.Version = STRUCT_VERSION(pState, 1) + ret := nvmlVgpuInstanceGetRuntimeStateSize(vgpuInstance, &pState) + return pState, ret +} + +// nvml.VgpuTypeGetMaxInstancesPerGpuInstance() +func (l *library) VgpuTypeGetMaxInstancesPerGpuInstance(maxInstance *VgpuTypeMaxInstance) Return { + return nvmlVgpuTypeGetMaxInstancesPerGpuInstance(maxInstance) +} diff --git a/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/zz_generated.api.go b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/zz_generated.api.go new file mode 100644 index 00000000..f4930ffd --- /dev/null +++ b/vendor/github.com/NVIDIA/go-nvml/pkg/nvml/zz_generated.api.go @@ -0,0 +1,1154 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// Generated Code; DO NOT EDIT. + +package nvml + +// The variables below represent package level methods from the library type. +var ( + ComputeInstanceDestroy = libnvml.ComputeInstanceDestroy + ComputeInstanceGetInfo = libnvml.ComputeInstanceGetInfo + DeviceClearAccountingPids = libnvml.DeviceClearAccountingPids + DeviceClearCpuAffinity = libnvml.DeviceClearCpuAffinity + DeviceClearEccErrorCounts = libnvml.DeviceClearEccErrorCounts + DeviceClearFieldValues = libnvml.DeviceClearFieldValues + DeviceCreateGpuInstance = libnvml.DeviceCreateGpuInstance + DeviceCreateGpuInstanceWithPlacement = libnvml.DeviceCreateGpuInstanceWithPlacement + DeviceDiscoverGpus = libnvml.DeviceDiscoverGpus + DeviceFreezeNvLinkUtilizationCounter = libnvml.DeviceFreezeNvLinkUtilizationCounter + DeviceGetAPIRestriction = libnvml.DeviceGetAPIRestriction + DeviceGetAccountingBufferSize = libnvml.DeviceGetAccountingBufferSize + DeviceGetAccountingMode = libnvml.DeviceGetAccountingMode + DeviceGetAccountingPids = libnvml.DeviceGetAccountingPids + DeviceGetAccountingStats = libnvml.DeviceGetAccountingStats + DeviceGetActiveVgpus = libnvml.DeviceGetActiveVgpus + DeviceGetAdaptiveClockInfoStatus = libnvml.DeviceGetAdaptiveClockInfoStatus + DeviceGetAddressingMode = libnvml.DeviceGetAddressingMode + DeviceGetApplicationsClock = libnvml.DeviceGetApplicationsClock + DeviceGetArchitecture = libnvml.DeviceGetArchitecture + DeviceGetAttributes = libnvml.DeviceGetAttributes + DeviceGetAutoBoostedClocksEnabled = libnvml.DeviceGetAutoBoostedClocksEnabled + DeviceGetBAR1MemoryInfo = libnvml.DeviceGetBAR1MemoryInfo + DeviceGetBoardId = libnvml.DeviceGetBoardId + DeviceGetBoardPartNumber = libnvml.DeviceGetBoardPartNumber + DeviceGetBrand = libnvml.DeviceGetBrand + DeviceGetBridgeChipInfo = libnvml.DeviceGetBridgeChipInfo + DeviceGetBusType = libnvml.DeviceGetBusType + DeviceGetC2cModeInfoV = libnvml.DeviceGetC2cModeInfoV + DeviceGetCapabilities = libnvml.DeviceGetCapabilities + DeviceGetClkMonStatus = libnvml.DeviceGetClkMonStatus + DeviceGetClock = libnvml.DeviceGetClock + DeviceGetClockInfo = libnvml.DeviceGetClockInfo + DeviceGetClockOffsets = libnvml.DeviceGetClockOffsets + DeviceGetComputeInstanceId = libnvml.DeviceGetComputeInstanceId + DeviceGetComputeMode = libnvml.DeviceGetComputeMode + DeviceGetComputeRunningProcesses = libnvml.DeviceGetComputeRunningProcesses + DeviceGetConfComputeGpuAttestationReport = libnvml.DeviceGetConfComputeGpuAttestationReport + DeviceGetConfComputeGpuCertificate = libnvml.DeviceGetConfComputeGpuCertificate + DeviceGetConfComputeMemSizeInfo = libnvml.DeviceGetConfComputeMemSizeInfo + DeviceGetConfComputeProtectedMemoryUsage = libnvml.DeviceGetConfComputeProtectedMemoryUsage + DeviceGetCoolerInfo = libnvml.DeviceGetCoolerInfo + DeviceGetCount = libnvml.DeviceGetCount + DeviceGetCpuAffinity = libnvml.DeviceGetCpuAffinity + DeviceGetCpuAffinityWithinScope = libnvml.DeviceGetCpuAffinityWithinScope + DeviceGetCreatableVgpus = libnvml.DeviceGetCreatableVgpus + DeviceGetCudaComputeCapability = libnvml.DeviceGetCudaComputeCapability + DeviceGetCurrPcieLinkGeneration = libnvml.DeviceGetCurrPcieLinkGeneration + DeviceGetCurrPcieLinkWidth = libnvml.DeviceGetCurrPcieLinkWidth + DeviceGetCurrentClockFreqs = libnvml.DeviceGetCurrentClockFreqs + DeviceGetCurrentClocksEventReasons = libnvml.DeviceGetCurrentClocksEventReasons + DeviceGetCurrentClocksThrottleReasons = libnvml.DeviceGetCurrentClocksThrottleReasons + DeviceGetDecoderUtilization = libnvml.DeviceGetDecoderUtilization + DeviceGetDefaultApplicationsClock = libnvml.DeviceGetDefaultApplicationsClock + DeviceGetDefaultEccMode = libnvml.DeviceGetDefaultEccMode + DeviceGetDetailedEccErrors = libnvml.DeviceGetDetailedEccErrors + DeviceGetDeviceHandleFromMigDeviceHandle = libnvml.DeviceGetDeviceHandleFromMigDeviceHandle + DeviceGetDisplayActive = libnvml.DeviceGetDisplayActive + DeviceGetDisplayMode = libnvml.DeviceGetDisplayMode + DeviceGetDramEncryptionMode = libnvml.DeviceGetDramEncryptionMode + DeviceGetDriverModel = libnvml.DeviceGetDriverModel + DeviceGetDriverModel_v2 = libnvml.DeviceGetDriverModel_v2 + DeviceGetDynamicPstatesInfo = libnvml.DeviceGetDynamicPstatesInfo + DeviceGetEccMode = libnvml.DeviceGetEccMode + DeviceGetEncoderCapacity = libnvml.DeviceGetEncoderCapacity + DeviceGetEncoderSessions = libnvml.DeviceGetEncoderSessions + DeviceGetEncoderStats = libnvml.DeviceGetEncoderStats + DeviceGetEncoderUtilization = libnvml.DeviceGetEncoderUtilization + DeviceGetEnforcedPowerLimit = libnvml.DeviceGetEnforcedPowerLimit + DeviceGetFBCSessions = libnvml.DeviceGetFBCSessions + DeviceGetFBCStats = libnvml.DeviceGetFBCStats + DeviceGetFanControlPolicy_v2 = libnvml.DeviceGetFanControlPolicy_v2 + DeviceGetFanSpeed = libnvml.DeviceGetFanSpeed + DeviceGetFanSpeedRPM = libnvml.DeviceGetFanSpeedRPM + DeviceGetFanSpeed_v2 = libnvml.DeviceGetFanSpeed_v2 + DeviceGetFieldValues = libnvml.DeviceGetFieldValues + DeviceGetGpcClkMinMaxVfOffset = libnvml.DeviceGetGpcClkMinMaxVfOffset + DeviceGetGpcClkVfOffset = libnvml.DeviceGetGpcClkVfOffset + DeviceGetGpuFabricInfo = libnvml.DeviceGetGpuFabricInfo + DeviceGetGpuFabricInfoV = libnvml.DeviceGetGpuFabricInfoV + DeviceGetGpuInstanceById = libnvml.DeviceGetGpuInstanceById + DeviceGetGpuInstanceId = libnvml.DeviceGetGpuInstanceId + DeviceGetGpuInstancePossiblePlacements = libnvml.DeviceGetGpuInstancePossiblePlacements + DeviceGetGpuInstanceProfileInfo = libnvml.DeviceGetGpuInstanceProfileInfo + DeviceGetGpuInstanceProfileInfoByIdV = libnvml.DeviceGetGpuInstanceProfileInfoByIdV + DeviceGetGpuInstanceProfileInfoV = libnvml.DeviceGetGpuInstanceProfileInfoV + DeviceGetGpuInstanceRemainingCapacity = libnvml.DeviceGetGpuInstanceRemainingCapacity + DeviceGetGpuInstances = libnvml.DeviceGetGpuInstances + DeviceGetGpuMaxPcieLinkGeneration = libnvml.DeviceGetGpuMaxPcieLinkGeneration + DeviceGetGpuOperationMode = libnvml.DeviceGetGpuOperationMode + DeviceGetGraphicsRunningProcesses = libnvml.DeviceGetGraphicsRunningProcesses + DeviceGetGridLicensableFeatures = libnvml.DeviceGetGridLicensableFeatures + DeviceGetGspFirmwareMode = libnvml.DeviceGetGspFirmwareMode + DeviceGetGspFirmwareVersion = libnvml.DeviceGetGspFirmwareVersion + DeviceGetHandleByIndex = libnvml.DeviceGetHandleByIndex + DeviceGetHandleByPciBusId = libnvml.DeviceGetHandleByPciBusId + DeviceGetHandleBySerial = libnvml.DeviceGetHandleBySerial + DeviceGetHandleByUUID = libnvml.DeviceGetHandleByUUID + DeviceGetHandleByUUIDV = libnvml.DeviceGetHandleByUUIDV + DeviceGetHostVgpuMode = libnvml.DeviceGetHostVgpuMode + DeviceGetIndex = libnvml.DeviceGetIndex + DeviceGetInforomConfigurationChecksum = libnvml.DeviceGetInforomConfigurationChecksum + DeviceGetInforomImageVersion = libnvml.DeviceGetInforomImageVersion + DeviceGetInforomVersion = libnvml.DeviceGetInforomVersion + DeviceGetIrqNum = libnvml.DeviceGetIrqNum + DeviceGetJpgUtilization = libnvml.DeviceGetJpgUtilization + DeviceGetLastBBXFlushTime = libnvml.DeviceGetLastBBXFlushTime + DeviceGetMPSComputeRunningProcesses = libnvml.DeviceGetMPSComputeRunningProcesses + DeviceGetMarginTemperature = libnvml.DeviceGetMarginTemperature + DeviceGetMaxClockInfo = libnvml.DeviceGetMaxClockInfo + DeviceGetMaxCustomerBoostClock = libnvml.DeviceGetMaxCustomerBoostClock + DeviceGetMaxMigDeviceCount = libnvml.DeviceGetMaxMigDeviceCount + DeviceGetMaxPcieLinkGeneration = libnvml.DeviceGetMaxPcieLinkGeneration + DeviceGetMaxPcieLinkWidth = libnvml.DeviceGetMaxPcieLinkWidth + DeviceGetMemClkMinMaxVfOffset = libnvml.DeviceGetMemClkMinMaxVfOffset + DeviceGetMemClkVfOffset = libnvml.DeviceGetMemClkVfOffset + DeviceGetMemoryAffinity = libnvml.DeviceGetMemoryAffinity + DeviceGetMemoryBusWidth = libnvml.DeviceGetMemoryBusWidth + DeviceGetMemoryErrorCounter = libnvml.DeviceGetMemoryErrorCounter + DeviceGetMemoryInfo = libnvml.DeviceGetMemoryInfo + DeviceGetMemoryInfo_v2 = libnvml.DeviceGetMemoryInfo_v2 + DeviceGetMigDeviceHandleByIndex = libnvml.DeviceGetMigDeviceHandleByIndex + DeviceGetMigMode = libnvml.DeviceGetMigMode + DeviceGetMinMaxClockOfPState = libnvml.DeviceGetMinMaxClockOfPState + DeviceGetMinMaxFanSpeed = libnvml.DeviceGetMinMaxFanSpeed + DeviceGetMinorNumber = libnvml.DeviceGetMinorNumber + DeviceGetModuleId = libnvml.DeviceGetModuleId + DeviceGetMultiGpuBoard = libnvml.DeviceGetMultiGpuBoard + DeviceGetName = libnvml.DeviceGetName + DeviceGetNumFans = libnvml.DeviceGetNumFans + DeviceGetNumGpuCores = libnvml.DeviceGetNumGpuCores + DeviceGetNumaNodeId = libnvml.DeviceGetNumaNodeId + DeviceGetNvLinkCapability = libnvml.DeviceGetNvLinkCapability + DeviceGetNvLinkErrorCounter = libnvml.DeviceGetNvLinkErrorCounter + DeviceGetNvLinkInfo = libnvml.DeviceGetNvLinkInfo + DeviceGetNvLinkRemoteDeviceType = libnvml.DeviceGetNvLinkRemoteDeviceType + DeviceGetNvLinkRemotePciInfo = libnvml.DeviceGetNvLinkRemotePciInfo + DeviceGetNvLinkState = libnvml.DeviceGetNvLinkState + DeviceGetNvLinkUtilizationControl = libnvml.DeviceGetNvLinkUtilizationControl + DeviceGetNvLinkUtilizationCounter = libnvml.DeviceGetNvLinkUtilizationCounter + DeviceGetNvLinkVersion = libnvml.DeviceGetNvLinkVersion + DeviceGetNvlinkBwMode = libnvml.DeviceGetNvlinkBwMode + DeviceGetNvlinkSupportedBwModes = libnvml.DeviceGetNvlinkSupportedBwModes + DeviceGetOfaUtilization = libnvml.DeviceGetOfaUtilization + DeviceGetP2PStatus = libnvml.DeviceGetP2PStatus + DeviceGetPciInfo = libnvml.DeviceGetPciInfo + DeviceGetPciInfoExt = libnvml.DeviceGetPciInfoExt + DeviceGetPcieLinkMaxSpeed = libnvml.DeviceGetPcieLinkMaxSpeed + DeviceGetPcieReplayCounter = libnvml.DeviceGetPcieReplayCounter + DeviceGetPcieSpeed = libnvml.DeviceGetPcieSpeed + DeviceGetPcieThroughput = libnvml.DeviceGetPcieThroughput + DeviceGetPdi = libnvml.DeviceGetPdi + DeviceGetPerformanceModes = libnvml.DeviceGetPerformanceModes + DeviceGetPerformanceState = libnvml.DeviceGetPerformanceState + DeviceGetPersistenceMode = libnvml.DeviceGetPersistenceMode + DeviceGetPgpuMetadataString = libnvml.DeviceGetPgpuMetadataString + DeviceGetPlatformInfo = libnvml.DeviceGetPlatformInfo + DeviceGetPowerManagementDefaultLimit = libnvml.DeviceGetPowerManagementDefaultLimit + DeviceGetPowerManagementLimit = libnvml.DeviceGetPowerManagementLimit + DeviceGetPowerManagementLimitConstraints = libnvml.DeviceGetPowerManagementLimitConstraints + DeviceGetPowerManagementMode = libnvml.DeviceGetPowerManagementMode + DeviceGetPowerMizerMode_v1 = libnvml.DeviceGetPowerMizerMode_v1 + DeviceGetPowerSource = libnvml.DeviceGetPowerSource + DeviceGetPowerState = libnvml.DeviceGetPowerState + DeviceGetPowerUsage = libnvml.DeviceGetPowerUsage + DeviceGetProcessUtilization = libnvml.DeviceGetProcessUtilization + DeviceGetProcessesUtilizationInfo = libnvml.DeviceGetProcessesUtilizationInfo + DeviceGetRemappedRows = libnvml.DeviceGetRemappedRows + DeviceGetRepairStatus = libnvml.DeviceGetRepairStatus + DeviceGetRetiredPages = libnvml.DeviceGetRetiredPages + DeviceGetRetiredPagesPendingStatus = libnvml.DeviceGetRetiredPagesPendingStatus + DeviceGetRetiredPages_v2 = libnvml.DeviceGetRetiredPages_v2 + DeviceGetRowRemapperHistogram = libnvml.DeviceGetRowRemapperHistogram + DeviceGetRunningProcessDetailList = libnvml.DeviceGetRunningProcessDetailList + DeviceGetSamples = libnvml.DeviceGetSamples + DeviceGetSerial = libnvml.DeviceGetSerial + DeviceGetSramEccErrorStatus = libnvml.DeviceGetSramEccErrorStatus + DeviceGetSramUniqueUncorrectedEccErrorCounts = libnvml.DeviceGetSramUniqueUncorrectedEccErrorCounts + DeviceGetSupportedClocksEventReasons = libnvml.DeviceGetSupportedClocksEventReasons + DeviceGetSupportedClocksThrottleReasons = libnvml.DeviceGetSupportedClocksThrottleReasons + DeviceGetSupportedEventTypes = libnvml.DeviceGetSupportedEventTypes + DeviceGetSupportedGraphicsClocks = libnvml.DeviceGetSupportedGraphicsClocks + DeviceGetSupportedMemoryClocks = libnvml.DeviceGetSupportedMemoryClocks + DeviceGetSupportedPerformanceStates = libnvml.DeviceGetSupportedPerformanceStates + DeviceGetSupportedVgpus = libnvml.DeviceGetSupportedVgpus + DeviceGetTargetFanSpeed = libnvml.DeviceGetTargetFanSpeed + DeviceGetTemperature = libnvml.DeviceGetTemperature + DeviceGetTemperatureThreshold = libnvml.DeviceGetTemperatureThreshold + DeviceGetTemperatureV = libnvml.DeviceGetTemperatureV + DeviceGetThermalSettings = libnvml.DeviceGetThermalSettings + DeviceGetTopologyCommonAncestor = libnvml.DeviceGetTopologyCommonAncestor + DeviceGetTopologyNearestGpus = libnvml.DeviceGetTopologyNearestGpus + DeviceGetTotalEccErrors = libnvml.DeviceGetTotalEccErrors + DeviceGetTotalEnergyConsumption = libnvml.DeviceGetTotalEnergyConsumption + DeviceGetUUID = libnvml.DeviceGetUUID + DeviceGetUtilizationRates = libnvml.DeviceGetUtilizationRates + DeviceGetVbiosVersion = libnvml.DeviceGetVbiosVersion + DeviceGetVgpuCapabilities = libnvml.DeviceGetVgpuCapabilities + DeviceGetVgpuHeterogeneousMode = libnvml.DeviceGetVgpuHeterogeneousMode + DeviceGetVgpuInstancesUtilizationInfo = libnvml.DeviceGetVgpuInstancesUtilizationInfo + DeviceGetVgpuMetadata = libnvml.DeviceGetVgpuMetadata + DeviceGetVgpuProcessUtilization = libnvml.DeviceGetVgpuProcessUtilization + DeviceGetVgpuProcessesUtilizationInfo = libnvml.DeviceGetVgpuProcessesUtilizationInfo + DeviceGetVgpuSchedulerCapabilities = libnvml.DeviceGetVgpuSchedulerCapabilities + DeviceGetVgpuSchedulerLog = libnvml.DeviceGetVgpuSchedulerLog + DeviceGetVgpuSchedulerState = libnvml.DeviceGetVgpuSchedulerState + DeviceGetVgpuTypeCreatablePlacements = libnvml.DeviceGetVgpuTypeCreatablePlacements + DeviceGetVgpuTypeSupportedPlacements = libnvml.DeviceGetVgpuTypeSupportedPlacements + DeviceGetVgpuUtilization = libnvml.DeviceGetVgpuUtilization + DeviceGetViolationStatus = libnvml.DeviceGetViolationStatus + DeviceGetVirtualizationMode = libnvml.DeviceGetVirtualizationMode + DeviceIsMigDeviceHandle = libnvml.DeviceIsMigDeviceHandle + DeviceModifyDrainState = libnvml.DeviceModifyDrainState + DeviceOnSameBoard = libnvml.DeviceOnSameBoard + DevicePowerSmoothingActivatePresetProfile = libnvml.DevicePowerSmoothingActivatePresetProfile + DevicePowerSmoothingSetState = libnvml.DevicePowerSmoothingSetState + DevicePowerSmoothingUpdatePresetProfileParam = libnvml.DevicePowerSmoothingUpdatePresetProfileParam + DeviceQueryDrainState = libnvml.DeviceQueryDrainState + DeviceReadWritePRM_v1 = libnvml.DeviceReadWritePRM_v1 + DeviceRegisterEvents = libnvml.DeviceRegisterEvents + DeviceRemoveGpu = libnvml.DeviceRemoveGpu + DeviceRemoveGpu_v2 = libnvml.DeviceRemoveGpu_v2 + DeviceResetApplicationsClocks = libnvml.DeviceResetApplicationsClocks + DeviceResetGpuLockedClocks = libnvml.DeviceResetGpuLockedClocks + DeviceResetMemoryLockedClocks = libnvml.DeviceResetMemoryLockedClocks + DeviceResetNvLinkErrorCounters = libnvml.DeviceResetNvLinkErrorCounters + DeviceResetNvLinkUtilizationCounter = libnvml.DeviceResetNvLinkUtilizationCounter + DeviceSetAPIRestriction = libnvml.DeviceSetAPIRestriction + DeviceSetAccountingMode = libnvml.DeviceSetAccountingMode + DeviceSetApplicationsClocks = libnvml.DeviceSetApplicationsClocks + DeviceSetAutoBoostedClocksEnabled = libnvml.DeviceSetAutoBoostedClocksEnabled + DeviceSetClockOffsets = libnvml.DeviceSetClockOffsets + DeviceSetComputeMode = libnvml.DeviceSetComputeMode + DeviceSetConfComputeUnprotectedMemSize = libnvml.DeviceSetConfComputeUnprotectedMemSize + DeviceSetCpuAffinity = libnvml.DeviceSetCpuAffinity + DeviceSetDefaultAutoBoostedClocksEnabled = libnvml.DeviceSetDefaultAutoBoostedClocksEnabled + DeviceSetDefaultFanSpeed_v2 = libnvml.DeviceSetDefaultFanSpeed_v2 + DeviceSetDramEncryptionMode = libnvml.DeviceSetDramEncryptionMode + DeviceSetDriverModel = libnvml.DeviceSetDriverModel + DeviceSetEccMode = libnvml.DeviceSetEccMode + DeviceSetFanControlPolicy = libnvml.DeviceSetFanControlPolicy + DeviceSetFanSpeed_v2 = libnvml.DeviceSetFanSpeed_v2 + DeviceSetGpcClkVfOffset = libnvml.DeviceSetGpcClkVfOffset + DeviceSetGpuLockedClocks = libnvml.DeviceSetGpuLockedClocks + DeviceSetGpuOperationMode = libnvml.DeviceSetGpuOperationMode + DeviceSetMemClkVfOffset = libnvml.DeviceSetMemClkVfOffset + DeviceSetMemoryLockedClocks = libnvml.DeviceSetMemoryLockedClocks + DeviceSetMigMode = libnvml.DeviceSetMigMode + DeviceSetNvLinkDeviceLowPowerThreshold = libnvml.DeviceSetNvLinkDeviceLowPowerThreshold + DeviceSetNvLinkUtilizationControl = libnvml.DeviceSetNvLinkUtilizationControl + DeviceSetNvlinkBwMode = libnvml.DeviceSetNvlinkBwMode + DeviceSetPersistenceMode = libnvml.DeviceSetPersistenceMode + DeviceSetPowerManagementLimit = libnvml.DeviceSetPowerManagementLimit + DeviceSetPowerManagementLimit_v2 = libnvml.DeviceSetPowerManagementLimit_v2 + DeviceSetTemperatureThreshold = libnvml.DeviceSetTemperatureThreshold + DeviceSetVgpuCapabilities = libnvml.DeviceSetVgpuCapabilities + DeviceSetVgpuHeterogeneousMode = libnvml.DeviceSetVgpuHeterogeneousMode + DeviceSetVgpuSchedulerState = libnvml.DeviceSetVgpuSchedulerState + DeviceSetVirtualizationMode = libnvml.DeviceSetVirtualizationMode + DeviceValidateInforom = libnvml.DeviceValidateInforom + DeviceWorkloadPowerProfileClearRequestedProfiles = libnvml.DeviceWorkloadPowerProfileClearRequestedProfiles + DeviceWorkloadPowerProfileGetCurrentProfiles = libnvml.DeviceWorkloadPowerProfileGetCurrentProfiles + DeviceWorkloadPowerProfileGetProfilesInfo = libnvml.DeviceWorkloadPowerProfileGetProfilesInfo + DeviceWorkloadPowerProfileSetRequestedProfiles = libnvml.DeviceWorkloadPowerProfileSetRequestedProfiles + ErrorString = libnvml.ErrorString + EventSetCreate = libnvml.EventSetCreate + EventSetFree = libnvml.EventSetFree + EventSetWait = libnvml.EventSetWait + Extensions = libnvml.Extensions + GetExcludedDeviceCount = libnvml.GetExcludedDeviceCount + GetExcludedDeviceInfoByIndex = libnvml.GetExcludedDeviceInfoByIndex + GetVgpuCompatibility = libnvml.GetVgpuCompatibility + GetVgpuDriverCapabilities = libnvml.GetVgpuDriverCapabilities + GetVgpuVersion = libnvml.GetVgpuVersion + GpmMetricsGet = libnvml.GpmMetricsGet + GpmMetricsGetV = libnvml.GpmMetricsGetV + GpmMigSampleGet = libnvml.GpmMigSampleGet + GpmQueryDeviceSupport = libnvml.GpmQueryDeviceSupport + GpmQueryDeviceSupportV = libnvml.GpmQueryDeviceSupportV + GpmQueryIfStreamingEnabled = libnvml.GpmQueryIfStreamingEnabled + GpmSampleAlloc = libnvml.GpmSampleAlloc + GpmSampleFree = libnvml.GpmSampleFree + GpmSampleGet = libnvml.GpmSampleGet + GpmSetStreamingEnabled = libnvml.GpmSetStreamingEnabled + GpuInstanceCreateComputeInstance = libnvml.GpuInstanceCreateComputeInstance + GpuInstanceCreateComputeInstanceWithPlacement = libnvml.GpuInstanceCreateComputeInstanceWithPlacement + GpuInstanceDestroy = libnvml.GpuInstanceDestroy + GpuInstanceGetActiveVgpus = libnvml.GpuInstanceGetActiveVgpus + GpuInstanceGetComputeInstanceById = libnvml.GpuInstanceGetComputeInstanceById + GpuInstanceGetComputeInstancePossiblePlacements = libnvml.GpuInstanceGetComputeInstancePossiblePlacements + GpuInstanceGetComputeInstanceProfileInfo = libnvml.GpuInstanceGetComputeInstanceProfileInfo + GpuInstanceGetComputeInstanceProfileInfoV = libnvml.GpuInstanceGetComputeInstanceProfileInfoV + GpuInstanceGetComputeInstanceRemainingCapacity = libnvml.GpuInstanceGetComputeInstanceRemainingCapacity + GpuInstanceGetComputeInstances = libnvml.GpuInstanceGetComputeInstances + GpuInstanceGetCreatableVgpus = libnvml.GpuInstanceGetCreatableVgpus + GpuInstanceGetInfo = libnvml.GpuInstanceGetInfo + GpuInstanceGetVgpuHeterogeneousMode = libnvml.GpuInstanceGetVgpuHeterogeneousMode + GpuInstanceGetVgpuSchedulerLog = libnvml.GpuInstanceGetVgpuSchedulerLog + GpuInstanceGetVgpuSchedulerState = libnvml.GpuInstanceGetVgpuSchedulerState + GpuInstanceGetVgpuTypeCreatablePlacements = libnvml.GpuInstanceGetVgpuTypeCreatablePlacements + GpuInstanceSetVgpuHeterogeneousMode = libnvml.GpuInstanceSetVgpuHeterogeneousMode + GpuInstanceSetVgpuSchedulerState = libnvml.GpuInstanceSetVgpuSchedulerState + Init = libnvml.Init + InitWithFlags = libnvml.InitWithFlags + SetVgpuVersion = libnvml.SetVgpuVersion + Shutdown = libnvml.Shutdown + SystemEventSetCreate = libnvml.SystemEventSetCreate + SystemEventSetFree = libnvml.SystemEventSetFree + SystemEventSetWait = libnvml.SystemEventSetWait + SystemGetConfComputeCapabilities = libnvml.SystemGetConfComputeCapabilities + SystemGetConfComputeGpusReadyState = libnvml.SystemGetConfComputeGpusReadyState + SystemGetConfComputeKeyRotationThresholdInfo = libnvml.SystemGetConfComputeKeyRotationThresholdInfo + SystemGetConfComputeSettings = libnvml.SystemGetConfComputeSettings + SystemGetConfComputeState = libnvml.SystemGetConfComputeState + SystemGetCudaDriverVersion = libnvml.SystemGetCudaDriverVersion + SystemGetCudaDriverVersion_v2 = libnvml.SystemGetCudaDriverVersion_v2 + SystemGetDriverBranch = libnvml.SystemGetDriverBranch + SystemGetDriverVersion = libnvml.SystemGetDriverVersion + SystemGetHicVersion = libnvml.SystemGetHicVersion + SystemGetNVMLVersion = libnvml.SystemGetNVMLVersion + SystemGetNvlinkBwMode = libnvml.SystemGetNvlinkBwMode + SystemGetProcessName = libnvml.SystemGetProcessName + SystemGetTopologyGpuSet = libnvml.SystemGetTopologyGpuSet + SystemRegisterEvents = libnvml.SystemRegisterEvents + SystemSetConfComputeGpusReadyState = libnvml.SystemSetConfComputeGpusReadyState + SystemSetConfComputeKeyRotationThresholdInfo = libnvml.SystemSetConfComputeKeyRotationThresholdInfo + SystemSetNvlinkBwMode = libnvml.SystemSetNvlinkBwMode + UnitGetCount = libnvml.UnitGetCount + UnitGetDevices = libnvml.UnitGetDevices + UnitGetFanSpeedInfo = libnvml.UnitGetFanSpeedInfo + UnitGetHandleByIndex = libnvml.UnitGetHandleByIndex + UnitGetLedState = libnvml.UnitGetLedState + UnitGetPsuInfo = libnvml.UnitGetPsuInfo + UnitGetTemperature = libnvml.UnitGetTemperature + UnitGetUnitInfo = libnvml.UnitGetUnitInfo + UnitSetLedState = libnvml.UnitSetLedState + VgpuInstanceClearAccountingPids = libnvml.VgpuInstanceClearAccountingPids + VgpuInstanceGetAccountingMode = libnvml.VgpuInstanceGetAccountingMode + VgpuInstanceGetAccountingPids = libnvml.VgpuInstanceGetAccountingPids + VgpuInstanceGetAccountingStats = libnvml.VgpuInstanceGetAccountingStats + VgpuInstanceGetEccMode = libnvml.VgpuInstanceGetEccMode + VgpuInstanceGetEncoderCapacity = libnvml.VgpuInstanceGetEncoderCapacity + VgpuInstanceGetEncoderSessions = libnvml.VgpuInstanceGetEncoderSessions + VgpuInstanceGetEncoderStats = libnvml.VgpuInstanceGetEncoderStats + VgpuInstanceGetFBCSessions = libnvml.VgpuInstanceGetFBCSessions + VgpuInstanceGetFBCStats = libnvml.VgpuInstanceGetFBCStats + VgpuInstanceGetFbUsage = libnvml.VgpuInstanceGetFbUsage + VgpuInstanceGetFrameRateLimit = libnvml.VgpuInstanceGetFrameRateLimit + VgpuInstanceGetGpuInstanceId = libnvml.VgpuInstanceGetGpuInstanceId + VgpuInstanceGetGpuPciId = libnvml.VgpuInstanceGetGpuPciId + VgpuInstanceGetLicenseInfo = libnvml.VgpuInstanceGetLicenseInfo + VgpuInstanceGetLicenseStatus = libnvml.VgpuInstanceGetLicenseStatus + VgpuInstanceGetMdevUUID = libnvml.VgpuInstanceGetMdevUUID + VgpuInstanceGetMetadata = libnvml.VgpuInstanceGetMetadata + VgpuInstanceGetRuntimeStateSize = libnvml.VgpuInstanceGetRuntimeStateSize + VgpuInstanceGetType = libnvml.VgpuInstanceGetType + VgpuInstanceGetUUID = libnvml.VgpuInstanceGetUUID + VgpuInstanceGetVmDriverVersion = libnvml.VgpuInstanceGetVmDriverVersion + VgpuInstanceGetVmID = libnvml.VgpuInstanceGetVmID + VgpuInstanceSetEncoderCapacity = libnvml.VgpuInstanceSetEncoderCapacity + VgpuTypeGetBAR1Info = libnvml.VgpuTypeGetBAR1Info + VgpuTypeGetCapabilities = libnvml.VgpuTypeGetCapabilities + VgpuTypeGetClass = libnvml.VgpuTypeGetClass + VgpuTypeGetDeviceID = libnvml.VgpuTypeGetDeviceID + VgpuTypeGetFrameRateLimit = libnvml.VgpuTypeGetFrameRateLimit + VgpuTypeGetFramebufferSize = libnvml.VgpuTypeGetFramebufferSize + VgpuTypeGetGpuInstanceProfileId = libnvml.VgpuTypeGetGpuInstanceProfileId + VgpuTypeGetLicense = libnvml.VgpuTypeGetLicense + VgpuTypeGetMaxInstances = libnvml.VgpuTypeGetMaxInstances + VgpuTypeGetMaxInstancesPerGpuInstance = libnvml.VgpuTypeGetMaxInstancesPerGpuInstance + VgpuTypeGetMaxInstancesPerVm = libnvml.VgpuTypeGetMaxInstancesPerVm + VgpuTypeGetName = libnvml.VgpuTypeGetName + VgpuTypeGetNumDisplayHeads = libnvml.VgpuTypeGetNumDisplayHeads + VgpuTypeGetResolution = libnvml.VgpuTypeGetResolution +) + +// Interface represents the interface for the library type. +// +//go:generate moq -out mock/interface.go -pkg mock . Interface:Interface +type Interface interface { + ComputeInstanceDestroy(ComputeInstance) Return + ComputeInstanceGetInfo(ComputeInstance) (ComputeInstanceInfo, Return) + DeviceClearAccountingPids(Device) Return + DeviceClearCpuAffinity(Device) Return + DeviceClearEccErrorCounts(Device, EccCounterType) Return + DeviceClearFieldValues(Device, []FieldValue) Return + DeviceCreateGpuInstance(Device, *GpuInstanceProfileInfo) (GpuInstance, Return) + DeviceCreateGpuInstanceWithPlacement(Device, *GpuInstanceProfileInfo, *GpuInstancePlacement) (GpuInstance, Return) + DeviceDiscoverGpus() (PciInfo, Return) + DeviceFreezeNvLinkUtilizationCounter(Device, int, int, EnableState) Return + DeviceGetAPIRestriction(Device, RestrictedAPI) (EnableState, Return) + DeviceGetAccountingBufferSize(Device) (int, Return) + DeviceGetAccountingMode(Device) (EnableState, Return) + DeviceGetAccountingPids(Device) ([]int, Return) + DeviceGetAccountingStats(Device, uint32) (AccountingStats, Return) + DeviceGetActiveVgpus(Device) ([]VgpuInstance, Return) + DeviceGetAdaptiveClockInfoStatus(Device) (uint32, Return) + DeviceGetAddressingMode(Device) (DeviceAddressingMode, Return) + DeviceGetApplicationsClock(Device, ClockType) (uint32, Return) + DeviceGetArchitecture(Device) (DeviceArchitecture, Return) + DeviceGetAttributes(Device) (DeviceAttributes, Return) + DeviceGetAutoBoostedClocksEnabled(Device) (EnableState, EnableState, Return) + DeviceGetBAR1MemoryInfo(Device) (BAR1Memory, Return) + DeviceGetBoardId(Device) (uint32, Return) + DeviceGetBoardPartNumber(Device) (string, Return) + DeviceGetBrand(Device) (BrandType, Return) + DeviceGetBridgeChipInfo(Device) (BridgeChipHierarchy, Return) + DeviceGetBusType(Device) (BusType, Return) + DeviceGetC2cModeInfoV(Device) C2cModeInfoHandler + DeviceGetCapabilities(Device) (DeviceCapabilities, Return) + DeviceGetClkMonStatus(Device) (ClkMonStatus, Return) + DeviceGetClock(Device, ClockType, ClockId) (uint32, Return) + DeviceGetClockInfo(Device, ClockType) (uint32, Return) + DeviceGetClockOffsets(Device) (ClockOffset, Return) + DeviceGetComputeInstanceId(Device) (int, Return) + DeviceGetComputeMode(Device) (ComputeMode, Return) + DeviceGetComputeRunningProcesses(Device) ([]ProcessInfo, Return) + DeviceGetConfComputeGpuAttestationReport(Device, *ConfComputeGpuAttestationReport) Return + DeviceGetConfComputeGpuCertificate(Device) (ConfComputeGpuCertificate, Return) + DeviceGetConfComputeMemSizeInfo(Device) (ConfComputeMemSizeInfo, Return) + DeviceGetConfComputeProtectedMemoryUsage(Device) (Memory, Return) + DeviceGetCoolerInfo(Device) (CoolerInfo, Return) + DeviceGetCount() (int, Return) + DeviceGetCpuAffinity(Device, int) ([]uint, Return) + DeviceGetCpuAffinityWithinScope(Device, int, AffinityScope) ([]uint, Return) + DeviceGetCreatableVgpus(Device) ([]VgpuTypeId, Return) + DeviceGetCudaComputeCapability(Device) (int, int, Return) + DeviceGetCurrPcieLinkGeneration(Device) (int, Return) + DeviceGetCurrPcieLinkWidth(Device) (int, Return) + DeviceGetCurrentClockFreqs(Device) (DeviceCurrentClockFreqs, Return) + DeviceGetCurrentClocksEventReasons(Device) (uint64, Return) + DeviceGetCurrentClocksThrottleReasons(Device) (uint64, Return) + DeviceGetDecoderUtilization(Device) (uint32, uint32, Return) + DeviceGetDefaultApplicationsClock(Device, ClockType) (uint32, Return) + DeviceGetDefaultEccMode(Device) (EnableState, Return) + DeviceGetDetailedEccErrors(Device, MemoryErrorType, EccCounterType) (EccErrorCounts, Return) + DeviceGetDeviceHandleFromMigDeviceHandle(Device) (Device, Return) + DeviceGetDisplayActive(Device) (EnableState, Return) + DeviceGetDisplayMode(Device) (EnableState, Return) + DeviceGetDramEncryptionMode(Device) (DramEncryptionInfo, DramEncryptionInfo, Return) + DeviceGetDriverModel(Device) (DriverModel, DriverModel, Return) + DeviceGetDriverModel_v2(Device) (DriverModel, DriverModel, Return) + DeviceGetDynamicPstatesInfo(Device) (GpuDynamicPstatesInfo, Return) + DeviceGetEccMode(Device) (EnableState, EnableState, Return) + DeviceGetEncoderCapacity(Device, EncoderType) (int, Return) + DeviceGetEncoderSessions(Device) ([]EncoderSessionInfo, Return) + DeviceGetEncoderStats(Device) (int, uint32, uint32, Return) + DeviceGetEncoderUtilization(Device) (uint32, uint32, Return) + DeviceGetEnforcedPowerLimit(Device) (uint32, Return) + DeviceGetFBCSessions(Device) ([]FBCSessionInfo, Return) + DeviceGetFBCStats(Device) (FBCStats, Return) + DeviceGetFanControlPolicy_v2(Device, int) (FanControlPolicy, Return) + DeviceGetFanSpeed(Device) (uint32, Return) + DeviceGetFanSpeedRPM(Device) (FanSpeedInfo, Return) + DeviceGetFanSpeed_v2(Device, int) (uint32, Return) + DeviceGetFieldValues(Device, []FieldValue) Return + DeviceGetGpcClkMinMaxVfOffset(Device) (int, int, Return) + DeviceGetGpcClkVfOffset(Device) (int, Return) + DeviceGetGpuFabricInfo(Device) (GpuFabricInfo, Return) + DeviceGetGpuFabricInfoV(Device) GpuFabricInfoHandler + DeviceGetGpuInstanceById(Device, int) (GpuInstance, Return) + DeviceGetGpuInstanceId(Device) (int, Return) + DeviceGetGpuInstancePossiblePlacements(Device, *GpuInstanceProfileInfo) ([]GpuInstancePlacement, Return) + DeviceGetGpuInstanceProfileInfo(Device, int) (GpuInstanceProfileInfo, Return) + DeviceGetGpuInstanceProfileInfoByIdV(Device, int) GpuInstanceProfileInfoByIdHandler + DeviceGetGpuInstanceProfileInfoV(Device, int) GpuInstanceProfileInfoHandler + DeviceGetGpuInstanceRemainingCapacity(Device, *GpuInstanceProfileInfo) (int, Return) + DeviceGetGpuInstances(Device, *GpuInstanceProfileInfo) ([]GpuInstance, Return) + DeviceGetGpuMaxPcieLinkGeneration(Device) (int, Return) + DeviceGetGpuOperationMode(Device) (GpuOperationMode, GpuOperationMode, Return) + DeviceGetGraphicsRunningProcesses(Device) ([]ProcessInfo, Return) + DeviceGetGridLicensableFeatures(Device) (GridLicensableFeatures, Return) + DeviceGetGspFirmwareMode(Device) (bool, bool, Return) + DeviceGetGspFirmwareVersion(Device) (string, Return) + DeviceGetHandleByIndex(int) (Device, Return) + DeviceGetHandleByPciBusId(string) (Device, Return) + DeviceGetHandleBySerial(string) (Device, Return) + DeviceGetHandleByUUID(string) (Device, Return) + DeviceGetHandleByUUIDV(*UUID) (Device, Return) + DeviceGetHostVgpuMode(Device) (HostVgpuMode, Return) + DeviceGetIndex(Device) (int, Return) + DeviceGetInforomConfigurationChecksum(Device) (uint32, Return) + DeviceGetInforomImageVersion(Device) (string, Return) + DeviceGetInforomVersion(Device, InforomObject) (string, Return) + DeviceGetIrqNum(Device) (int, Return) + DeviceGetJpgUtilization(Device) (uint32, uint32, Return) + DeviceGetLastBBXFlushTime(Device) (uint64, uint, Return) + DeviceGetMPSComputeRunningProcesses(Device) ([]ProcessInfo, Return) + DeviceGetMarginTemperature(Device) (MarginTemperature, Return) + DeviceGetMaxClockInfo(Device, ClockType) (uint32, Return) + DeviceGetMaxCustomerBoostClock(Device, ClockType) (uint32, Return) + DeviceGetMaxMigDeviceCount(Device) (int, Return) + DeviceGetMaxPcieLinkGeneration(Device) (int, Return) + DeviceGetMaxPcieLinkWidth(Device) (int, Return) + DeviceGetMemClkMinMaxVfOffset(Device) (int, int, Return) + DeviceGetMemClkVfOffset(Device) (int, Return) + DeviceGetMemoryAffinity(Device, int, AffinityScope) ([]uint, Return) + DeviceGetMemoryBusWidth(Device) (uint32, Return) + DeviceGetMemoryErrorCounter(Device, MemoryErrorType, EccCounterType, MemoryLocation) (uint64, Return) + DeviceGetMemoryInfo(Device) (Memory, Return) + DeviceGetMemoryInfo_v2(Device) (Memory_v2, Return) + DeviceGetMigDeviceHandleByIndex(Device, int) (Device, Return) + DeviceGetMigMode(Device) (int, int, Return) + DeviceGetMinMaxClockOfPState(Device, ClockType, Pstates) (uint32, uint32, Return) + DeviceGetMinMaxFanSpeed(Device) (int, int, Return) + DeviceGetMinorNumber(Device) (int, Return) + DeviceGetModuleId(Device) (int, Return) + DeviceGetMultiGpuBoard(Device) (int, Return) + DeviceGetName(Device) (string, Return) + DeviceGetNumFans(Device) (int, Return) + DeviceGetNumGpuCores(Device) (int, Return) + DeviceGetNumaNodeId(Device) (int, Return) + DeviceGetNvLinkCapability(Device, int, NvLinkCapability) (uint32, Return) + DeviceGetNvLinkErrorCounter(Device, int, NvLinkErrorCounter) (uint64, Return) + DeviceGetNvLinkInfo(Device) NvLinkInfoHandler + DeviceGetNvLinkRemoteDeviceType(Device, int) (IntNvLinkDeviceType, Return) + DeviceGetNvLinkRemotePciInfo(Device, int) (PciInfo, Return) + DeviceGetNvLinkState(Device, int) (EnableState, Return) + DeviceGetNvLinkUtilizationControl(Device, int, int) (NvLinkUtilizationControl, Return) + DeviceGetNvLinkUtilizationCounter(Device, int, int) (uint64, uint64, Return) + DeviceGetNvLinkVersion(Device, int) (uint32, Return) + DeviceGetNvlinkBwMode(Device) (NvlinkGetBwMode, Return) + DeviceGetNvlinkSupportedBwModes(Device) (NvlinkSupportedBwModes, Return) + DeviceGetOfaUtilization(Device) (uint32, uint32, Return) + DeviceGetP2PStatus(Device, Device, GpuP2PCapsIndex) (GpuP2PStatus, Return) + DeviceGetPciInfo(Device) (PciInfo, Return) + DeviceGetPciInfoExt(Device) (PciInfoExt, Return) + DeviceGetPcieLinkMaxSpeed(Device) (uint32, Return) + DeviceGetPcieReplayCounter(Device) (int, Return) + DeviceGetPcieSpeed(Device) (int, Return) + DeviceGetPcieThroughput(Device, PcieUtilCounter) (uint32, Return) + DeviceGetPdi(Device) (Pdi, Return) + DeviceGetPerformanceModes(Device) (DevicePerfModes, Return) + DeviceGetPerformanceState(Device) (Pstates, Return) + DeviceGetPersistenceMode(Device) (EnableState, Return) + DeviceGetPgpuMetadataString(Device) (string, Return) + DeviceGetPlatformInfo(Device) (PlatformInfo, Return) + DeviceGetPowerManagementDefaultLimit(Device) (uint32, Return) + DeviceGetPowerManagementLimit(Device) (uint32, Return) + DeviceGetPowerManagementLimitConstraints(Device) (uint32, uint32, Return) + DeviceGetPowerManagementMode(Device) (EnableState, Return) + DeviceGetPowerMizerMode_v1(Device) (DevicePowerMizerModes_v1, Return) + DeviceGetPowerSource(Device) (PowerSource, Return) + DeviceGetPowerState(Device) (Pstates, Return) + DeviceGetPowerUsage(Device) (uint32, Return) + DeviceGetProcessUtilization(Device, uint64) ([]ProcessUtilizationSample, Return) + DeviceGetProcessesUtilizationInfo(Device) (ProcessesUtilizationInfo, Return) + DeviceGetRemappedRows(Device) (int, int, bool, bool, Return) + DeviceGetRepairStatus(Device) (RepairStatus, Return) + DeviceGetRetiredPages(Device, PageRetirementCause) ([]uint64, Return) + DeviceGetRetiredPagesPendingStatus(Device) (EnableState, Return) + DeviceGetRetiredPages_v2(Device, PageRetirementCause) ([]uint64, []uint64, Return) + DeviceGetRowRemapperHistogram(Device) (RowRemapperHistogramValues, Return) + DeviceGetRunningProcessDetailList(Device) (ProcessDetailList, Return) + DeviceGetSamples(Device, SamplingType, uint64) (ValueType, []Sample, Return) + DeviceGetSerial(Device) (string, Return) + DeviceGetSramEccErrorStatus(Device) (EccSramErrorStatus, Return) + DeviceGetSramUniqueUncorrectedEccErrorCounts(Device, *EccSramUniqueUncorrectedErrorCounts) Return + DeviceGetSupportedClocksEventReasons(Device) (uint64, Return) + DeviceGetSupportedClocksThrottleReasons(Device) (uint64, Return) + DeviceGetSupportedEventTypes(Device) (uint64, Return) + DeviceGetSupportedGraphicsClocks(Device, int) (int, uint32, Return) + DeviceGetSupportedMemoryClocks(Device) (int, uint32, Return) + DeviceGetSupportedPerformanceStates(Device) ([]Pstates, Return) + DeviceGetSupportedVgpus(Device) ([]VgpuTypeId, Return) + DeviceGetTargetFanSpeed(Device, int) (int, Return) + DeviceGetTemperature(Device, TemperatureSensors) (uint32, Return) + DeviceGetTemperatureThreshold(Device, TemperatureThresholds) (uint32, Return) + DeviceGetTemperatureV(Device) TemperatureHandler + DeviceGetThermalSettings(Device, uint32) (GpuThermalSettings, Return) + DeviceGetTopologyCommonAncestor(Device, Device) (GpuTopologyLevel, Return) + DeviceGetTopologyNearestGpus(Device, GpuTopologyLevel) ([]Device, Return) + DeviceGetTotalEccErrors(Device, MemoryErrorType, EccCounterType) (uint64, Return) + DeviceGetTotalEnergyConsumption(Device) (uint64, Return) + DeviceGetUUID(Device) (string, Return) + DeviceGetUtilizationRates(Device) (Utilization, Return) + DeviceGetVbiosVersion(Device) (string, Return) + DeviceGetVgpuCapabilities(Device, DeviceVgpuCapability) (bool, Return) + DeviceGetVgpuHeterogeneousMode(Device) (VgpuHeterogeneousMode, Return) + DeviceGetVgpuInstancesUtilizationInfo(Device) (VgpuInstancesUtilizationInfo, Return) + DeviceGetVgpuMetadata(Device) (VgpuPgpuMetadata, Return) + DeviceGetVgpuProcessUtilization(Device, uint64) ([]VgpuProcessUtilizationSample, Return) + DeviceGetVgpuProcessesUtilizationInfo(Device) (VgpuProcessesUtilizationInfo, Return) + DeviceGetVgpuSchedulerCapabilities(Device) (VgpuSchedulerCapabilities, Return) + DeviceGetVgpuSchedulerLog(Device) (VgpuSchedulerLog, Return) + DeviceGetVgpuSchedulerState(Device) (VgpuSchedulerGetState, Return) + DeviceGetVgpuTypeCreatablePlacements(Device, VgpuTypeId) (VgpuPlacementList, Return) + DeviceGetVgpuTypeSupportedPlacements(Device, VgpuTypeId) (VgpuPlacementList, Return) + DeviceGetVgpuUtilization(Device, uint64) (ValueType, []VgpuInstanceUtilizationSample, Return) + DeviceGetViolationStatus(Device, PerfPolicyType) (ViolationTime, Return) + DeviceGetVirtualizationMode(Device) (GpuVirtualizationMode, Return) + DeviceIsMigDeviceHandle(Device) (bool, Return) + DeviceModifyDrainState(*PciInfo, EnableState) Return + DeviceOnSameBoard(Device, Device) (int, Return) + DevicePowerSmoothingActivatePresetProfile(Device, *PowerSmoothingProfile) Return + DevicePowerSmoothingSetState(Device, *PowerSmoothingState) Return + DevicePowerSmoothingUpdatePresetProfileParam(Device, *PowerSmoothingProfile) Return + DeviceQueryDrainState(*PciInfo) (EnableState, Return) + DeviceReadWritePRM_v1(Device, *PRMTLV_v1) Return + DeviceRegisterEvents(Device, uint64, EventSet) Return + DeviceRemoveGpu(*PciInfo) Return + DeviceRemoveGpu_v2(*PciInfo, DetachGpuState, PcieLinkState) Return + DeviceResetApplicationsClocks(Device) Return + DeviceResetGpuLockedClocks(Device) Return + DeviceResetMemoryLockedClocks(Device) Return + DeviceResetNvLinkErrorCounters(Device, int) Return + DeviceResetNvLinkUtilizationCounter(Device, int, int) Return + DeviceSetAPIRestriction(Device, RestrictedAPI, EnableState) Return + DeviceSetAccountingMode(Device, EnableState) Return + DeviceSetApplicationsClocks(Device, uint32, uint32) Return + DeviceSetAutoBoostedClocksEnabled(Device, EnableState) Return + DeviceSetClockOffsets(Device, ClockOffset) Return + DeviceSetComputeMode(Device, ComputeMode) Return + DeviceSetConfComputeUnprotectedMemSize(Device, uint64) Return + DeviceSetCpuAffinity(Device) Return + DeviceSetDefaultAutoBoostedClocksEnabled(Device, EnableState, uint32) Return + DeviceSetDefaultFanSpeed_v2(Device, int) Return + DeviceSetDramEncryptionMode(Device, *DramEncryptionInfo) Return + DeviceSetDriverModel(Device, DriverModel, uint32) Return + DeviceSetEccMode(Device, EnableState) Return + DeviceSetFanControlPolicy(Device, int, FanControlPolicy) Return + DeviceSetFanSpeed_v2(Device, int, int) Return + DeviceSetGpcClkVfOffset(Device, int) Return + DeviceSetGpuLockedClocks(Device, uint32, uint32) Return + DeviceSetGpuOperationMode(Device, GpuOperationMode) Return + DeviceSetMemClkVfOffset(Device, int) Return + DeviceSetMemoryLockedClocks(Device, uint32, uint32) Return + DeviceSetMigMode(Device, int) (Return, Return) + DeviceSetNvLinkDeviceLowPowerThreshold(Device, *NvLinkPowerThres) Return + DeviceSetNvLinkUtilizationControl(Device, int, int, *NvLinkUtilizationControl, bool) Return + DeviceSetNvlinkBwMode(Device, *NvlinkSetBwMode) Return + DeviceSetPersistenceMode(Device, EnableState) Return + DeviceSetPowerManagementLimit(Device, uint32) Return + DeviceSetPowerManagementLimit_v2(Device, *PowerValue_v2) Return + DeviceSetTemperatureThreshold(Device, TemperatureThresholds, int) Return + DeviceSetVgpuCapabilities(Device, DeviceVgpuCapability, EnableState) Return + DeviceSetVgpuHeterogeneousMode(Device, VgpuHeterogeneousMode) Return + DeviceSetVgpuSchedulerState(Device, *VgpuSchedulerSetState) Return + DeviceSetVirtualizationMode(Device, GpuVirtualizationMode) Return + DeviceValidateInforom(Device) Return + DeviceWorkloadPowerProfileClearRequestedProfiles(Device, *WorkloadPowerProfileRequestedProfiles) Return + DeviceWorkloadPowerProfileGetCurrentProfiles(Device) (WorkloadPowerProfileCurrentProfiles, Return) + DeviceWorkloadPowerProfileGetProfilesInfo(Device) (WorkloadPowerProfileProfilesInfo, Return) + DeviceWorkloadPowerProfileSetRequestedProfiles(Device, *WorkloadPowerProfileRequestedProfiles) Return + ErrorString(Return) string + EventSetCreate() (EventSet, Return) + EventSetFree(EventSet) Return + EventSetWait(EventSet, uint32) (EventData, Return) + Extensions() ExtendedInterface + GetExcludedDeviceCount() (int, Return) + GetExcludedDeviceInfoByIndex(int) (ExcludedDeviceInfo, Return) + GetVgpuCompatibility(*VgpuMetadata, *VgpuPgpuMetadata) (VgpuPgpuCompatibility, Return) + GetVgpuDriverCapabilities(VgpuDriverCapability) (bool, Return) + GetVgpuVersion() (VgpuVersion, VgpuVersion, Return) + GpmMetricsGet(*GpmMetricsGetType) Return + GpmMetricsGetV(*GpmMetricsGetType) GpmMetricsGetVType + GpmMigSampleGet(Device, int, GpmSample) Return + GpmQueryDeviceSupport(Device) (GpmSupport, Return) + GpmQueryDeviceSupportV(Device) GpmSupportV + GpmQueryIfStreamingEnabled(Device) (uint32, Return) + GpmSampleAlloc() (GpmSample, Return) + GpmSampleFree(GpmSample) Return + GpmSampleGet(Device, GpmSample) Return + GpmSetStreamingEnabled(Device, uint32) Return + GpuInstanceCreateComputeInstance(GpuInstance, *ComputeInstanceProfileInfo) (ComputeInstance, Return) + GpuInstanceCreateComputeInstanceWithPlacement(GpuInstance, *ComputeInstanceProfileInfo, *ComputeInstancePlacement) (ComputeInstance, Return) + GpuInstanceDestroy(GpuInstance) Return + GpuInstanceGetActiveVgpus(GpuInstance) (ActiveVgpuInstanceInfo, Return) + GpuInstanceGetComputeInstanceById(GpuInstance, int) (ComputeInstance, Return) + GpuInstanceGetComputeInstancePossiblePlacements(GpuInstance, *ComputeInstanceProfileInfo) ([]ComputeInstancePlacement, Return) + GpuInstanceGetComputeInstanceProfileInfo(GpuInstance, int, int) (ComputeInstanceProfileInfo, Return) + GpuInstanceGetComputeInstanceProfileInfoV(GpuInstance, int, int) ComputeInstanceProfileInfoHandler + GpuInstanceGetComputeInstanceRemainingCapacity(GpuInstance, *ComputeInstanceProfileInfo) (int, Return) + GpuInstanceGetComputeInstances(GpuInstance, *ComputeInstanceProfileInfo) ([]ComputeInstance, Return) + GpuInstanceGetCreatableVgpus(GpuInstance) (VgpuTypeIdInfo, Return) + GpuInstanceGetInfo(GpuInstance) (GpuInstanceInfo, Return) + GpuInstanceGetVgpuHeterogeneousMode(GpuInstance) (VgpuHeterogeneousMode, Return) + GpuInstanceGetVgpuSchedulerLog(GpuInstance) (VgpuSchedulerLogInfo, Return) + GpuInstanceGetVgpuSchedulerState(GpuInstance) (VgpuSchedulerStateInfo, Return) + GpuInstanceGetVgpuTypeCreatablePlacements(GpuInstance) (VgpuCreatablePlacementInfo, Return) + GpuInstanceSetVgpuHeterogeneousMode(GpuInstance, *VgpuHeterogeneousMode) Return + GpuInstanceSetVgpuSchedulerState(GpuInstance, *VgpuSchedulerState) Return + Init() Return + InitWithFlags(uint32) Return + SetVgpuVersion(*VgpuVersion) Return + Shutdown() Return + SystemEventSetCreate(*SystemEventSetCreateRequest) Return + SystemEventSetFree(*SystemEventSetFreeRequest) Return + SystemEventSetWait(*SystemEventSetWaitRequest) Return + SystemGetConfComputeCapabilities() (ConfComputeSystemCaps, Return) + SystemGetConfComputeGpusReadyState() (uint32, Return) + SystemGetConfComputeKeyRotationThresholdInfo() (ConfComputeGetKeyRotationThresholdInfo, Return) + SystemGetConfComputeSettings() (SystemConfComputeSettings, Return) + SystemGetConfComputeState() (ConfComputeSystemState, Return) + SystemGetCudaDriverVersion() (int, Return) + SystemGetCudaDriverVersion_v2() (int, Return) + SystemGetDriverBranch() (SystemDriverBranchInfo, Return) + SystemGetDriverVersion() (string, Return) + SystemGetHicVersion() ([]HwbcEntry, Return) + SystemGetNVMLVersion() (string, Return) + SystemGetNvlinkBwMode() (uint32, Return) + SystemGetProcessName(int) (string, Return) + SystemGetTopologyGpuSet(int) ([]Device, Return) + SystemRegisterEvents(*SystemRegisterEventRequest) Return + SystemSetConfComputeGpusReadyState(uint32) Return + SystemSetConfComputeKeyRotationThresholdInfo(ConfComputeSetKeyRotationThresholdInfo) Return + SystemSetNvlinkBwMode(uint32) Return + UnitGetCount() (int, Return) + UnitGetDevices(Unit) ([]Device, Return) + UnitGetFanSpeedInfo(Unit) (UnitFanSpeeds, Return) + UnitGetHandleByIndex(int) (Unit, Return) + UnitGetLedState(Unit) (LedState, Return) + UnitGetPsuInfo(Unit) (PSUInfo, Return) + UnitGetTemperature(Unit, int) (uint32, Return) + UnitGetUnitInfo(Unit) (UnitInfo, Return) + UnitSetLedState(Unit, LedColor) Return + VgpuInstanceClearAccountingPids(VgpuInstance) Return + VgpuInstanceGetAccountingMode(VgpuInstance) (EnableState, Return) + VgpuInstanceGetAccountingPids(VgpuInstance) ([]int, Return) + VgpuInstanceGetAccountingStats(VgpuInstance, int) (AccountingStats, Return) + VgpuInstanceGetEccMode(VgpuInstance) (EnableState, Return) + VgpuInstanceGetEncoderCapacity(VgpuInstance) (int, Return) + VgpuInstanceGetEncoderSessions(VgpuInstance) (int, EncoderSessionInfo, Return) + VgpuInstanceGetEncoderStats(VgpuInstance) (int, uint32, uint32, Return) + VgpuInstanceGetFBCSessions(VgpuInstance) (int, FBCSessionInfo, Return) + VgpuInstanceGetFBCStats(VgpuInstance) (FBCStats, Return) + VgpuInstanceGetFbUsage(VgpuInstance) (uint64, Return) + VgpuInstanceGetFrameRateLimit(VgpuInstance) (uint32, Return) + VgpuInstanceGetGpuInstanceId(VgpuInstance) (int, Return) + VgpuInstanceGetGpuPciId(VgpuInstance) (string, Return) + VgpuInstanceGetLicenseInfo(VgpuInstance) (VgpuLicenseInfo, Return) + VgpuInstanceGetLicenseStatus(VgpuInstance) (int, Return) + VgpuInstanceGetMdevUUID(VgpuInstance) (string, Return) + VgpuInstanceGetMetadata(VgpuInstance) (VgpuMetadata, Return) + VgpuInstanceGetRuntimeStateSize(VgpuInstance) (VgpuRuntimeState, Return) + VgpuInstanceGetType(VgpuInstance) (VgpuTypeId, Return) + VgpuInstanceGetUUID(VgpuInstance) (string, Return) + VgpuInstanceGetVmDriverVersion(VgpuInstance) (string, Return) + VgpuInstanceGetVmID(VgpuInstance) (string, VgpuVmIdType, Return) + VgpuInstanceSetEncoderCapacity(VgpuInstance, int) Return + VgpuTypeGetBAR1Info(VgpuTypeId) (VgpuTypeBar1Info, Return) + VgpuTypeGetCapabilities(VgpuTypeId, VgpuCapability) (bool, Return) + VgpuTypeGetClass(VgpuTypeId) (string, Return) + VgpuTypeGetDeviceID(VgpuTypeId) (uint64, uint64, Return) + VgpuTypeGetFrameRateLimit(VgpuTypeId) (uint32, Return) + VgpuTypeGetFramebufferSize(VgpuTypeId) (uint64, Return) + VgpuTypeGetGpuInstanceProfileId(VgpuTypeId) (uint32, Return) + VgpuTypeGetLicense(VgpuTypeId) (string, Return) + VgpuTypeGetMaxInstances(Device, VgpuTypeId) (int, Return) + VgpuTypeGetMaxInstancesPerGpuInstance(*VgpuTypeMaxInstance) Return + VgpuTypeGetMaxInstancesPerVm(VgpuTypeId) (int, Return) + VgpuTypeGetName(VgpuTypeId) (string, Return) + VgpuTypeGetNumDisplayHeads(VgpuTypeId) (int, Return) + VgpuTypeGetResolution(VgpuTypeId, int) (uint32, uint32, Return) +} + +// Device represents the interface for the nvmlDevice type. +// +//go:generate moq -out mock/device.go -pkg mock . Device:Device +type Device interface { + ClearAccountingPids() Return + ClearCpuAffinity() Return + ClearEccErrorCounts(EccCounterType) Return + ClearFieldValues([]FieldValue) Return + CreateGpuInstance(*GpuInstanceProfileInfo) (GpuInstance, Return) + CreateGpuInstanceWithPlacement(*GpuInstanceProfileInfo, *GpuInstancePlacement) (GpuInstance, Return) + FreezeNvLinkUtilizationCounter(int, int, EnableState) Return + GetAPIRestriction(RestrictedAPI) (EnableState, Return) + GetAccountingBufferSize() (int, Return) + GetAccountingMode() (EnableState, Return) + GetAccountingPids() ([]int, Return) + GetAccountingStats(uint32) (AccountingStats, Return) + GetActiveVgpus() ([]VgpuInstance, Return) + GetAdaptiveClockInfoStatus() (uint32, Return) + GetAddressingMode() (DeviceAddressingMode, Return) + GetApplicationsClock(ClockType) (uint32, Return) + GetArchitecture() (DeviceArchitecture, Return) + GetAttributes() (DeviceAttributes, Return) + GetAutoBoostedClocksEnabled() (EnableState, EnableState, Return) + GetBAR1MemoryInfo() (BAR1Memory, Return) + GetBoardId() (uint32, Return) + GetBoardPartNumber() (string, Return) + GetBrand() (BrandType, Return) + GetBridgeChipInfo() (BridgeChipHierarchy, Return) + GetBusType() (BusType, Return) + GetC2cModeInfoV() C2cModeInfoHandler + GetCapabilities() (DeviceCapabilities, Return) + GetClkMonStatus() (ClkMonStatus, Return) + GetClock(ClockType, ClockId) (uint32, Return) + GetClockInfo(ClockType) (uint32, Return) + GetClockOffsets() (ClockOffset, Return) + GetComputeInstanceId() (int, Return) + GetComputeMode() (ComputeMode, Return) + GetComputeRunningProcesses() ([]ProcessInfo, Return) + GetConfComputeGpuAttestationReport(*ConfComputeGpuAttestationReport) Return + GetConfComputeGpuCertificate() (ConfComputeGpuCertificate, Return) + GetConfComputeMemSizeInfo() (ConfComputeMemSizeInfo, Return) + GetConfComputeProtectedMemoryUsage() (Memory, Return) + GetCoolerInfo() (CoolerInfo, Return) + GetCpuAffinity(int) ([]uint, Return) + GetCpuAffinityWithinScope(int, AffinityScope) ([]uint, Return) + GetCreatableVgpus() ([]VgpuTypeId, Return) + GetCudaComputeCapability() (int, int, Return) + GetCurrPcieLinkGeneration() (int, Return) + GetCurrPcieLinkWidth() (int, Return) + GetCurrentClockFreqs() (DeviceCurrentClockFreqs, Return) + GetCurrentClocksEventReasons() (uint64, Return) + GetCurrentClocksThrottleReasons() (uint64, Return) + GetDecoderUtilization() (uint32, uint32, Return) + GetDefaultApplicationsClock(ClockType) (uint32, Return) + GetDefaultEccMode() (EnableState, Return) + GetDetailedEccErrors(MemoryErrorType, EccCounterType) (EccErrorCounts, Return) + GetDeviceHandleFromMigDeviceHandle() (Device, Return) + GetDisplayActive() (EnableState, Return) + GetDisplayMode() (EnableState, Return) + GetDramEncryptionMode() (DramEncryptionInfo, DramEncryptionInfo, Return) + GetDriverModel() (DriverModel, DriverModel, Return) + GetDriverModel_v2() (DriverModel, DriverModel, Return) + GetDynamicPstatesInfo() (GpuDynamicPstatesInfo, Return) + GetEccMode() (EnableState, EnableState, Return) + GetEncoderCapacity(EncoderType) (int, Return) + GetEncoderSessions() ([]EncoderSessionInfo, Return) + GetEncoderStats() (int, uint32, uint32, Return) + GetEncoderUtilization() (uint32, uint32, Return) + GetEnforcedPowerLimit() (uint32, Return) + GetFBCSessions() ([]FBCSessionInfo, Return) + GetFBCStats() (FBCStats, Return) + GetFanControlPolicy_v2(int) (FanControlPolicy, Return) + GetFanSpeed() (uint32, Return) + GetFanSpeedRPM() (FanSpeedInfo, Return) + GetFanSpeed_v2(int) (uint32, Return) + GetFieldValues([]FieldValue) Return + GetGpcClkMinMaxVfOffset() (int, int, Return) + GetGpcClkVfOffset() (int, Return) + GetGpuFabricInfo() (GpuFabricInfo, Return) + GetGpuFabricInfoV() GpuFabricInfoHandler + GetGpuInstanceById(int) (GpuInstance, Return) + GetGpuInstanceId() (int, Return) + GetGpuInstancePossiblePlacements(*GpuInstanceProfileInfo) ([]GpuInstancePlacement, Return) + GetGpuInstanceProfileInfo(int) (GpuInstanceProfileInfo, Return) + GetGpuInstanceProfileInfoByIdV(int) GpuInstanceProfileInfoByIdHandler + GetGpuInstanceProfileInfoV(int) GpuInstanceProfileInfoHandler + GetGpuInstanceRemainingCapacity(*GpuInstanceProfileInfo) (int, Return) + GetGpuInstances(*GpuInstanceProfileInfo) ([]GpuInstance, Return) + GetGpuMaxPcieLinkGeneration() (int, Return) + GetGpuOperationMode() (GpuOperationMode, GpuOperationMode, Return) + GetGraphicsRunningProcesses() ([]ProcessInfo, Return) + GetGridLicensableFeatures() (GridLicensableFeatures, Return) + GetGspFirmwareMode() (bool, bool, Return) + GetGspFirmwareVersion() (string, Return) + GetHostVgpuMode() (HostVgpuMode, Return) + GetIndex() (int, Return) + GetInforomConfigurationChecksum() (uint32, Return) + GetInforomImageVersion() (string, Return) + GetInforomVersion(InforomObject) (string, Return) + GetIrqNum() (int, Return) + GetJpgUtilization() (uint32, uint32, Return) + GetLastBBXFlushTime() (uint64, uint, Return) + GetMPSComputeRunningProcesses() ([]ProcessInfo, Return) + GetMarginTemperature() (MarginTemperature, Return) + GetMaxClockInfo(ClockType) (uint32, Return) + GetMaxCustomerBoostClock(ClockType) (uint32, Return) + GetMaxMigDeviceCount() (int, Return) + GetMaxPcieLinkGeneration() (int, Return) + GetMaxPcieLinkWidth() (int, Return) + GetMemClkMinMaxVfOffset() (int, int, Return) + GetMemClkVfOffset() (int, Return) + GetMemoryAffinity(int, AffinityScope) ([]uint, Return) + GetMemoryBusWidth() (uint32, Return) + GetMemoryErrorCounter(MemoryErrorType, EccCounterType, MemoryLocation) (uint64, Return) + GetMemoryInfo() (Memory, Return) + GetMemoryInfo_v2() (Memory_v2, Return) + GetMigDeviceHandleByIndex(int) (Device, Return) + GetMigMode() (int, int, Return) + GetMinMaxClockOfPState(ClockType, Pstates) (uint32, uint32, Return) + GetMinMaxFanSpeed() (int, int, Return) + GetMinorNumber() (int, Return) + GetModuleId() (int, Return) + GetMultiGpuBoard() (int, Return) + GetName() (string, Return) + GetNumFans() (int, Return) + GetNumGpuCores() (int, Return) + GetNumaNodeId() (int, Return) + GetNvLinkCapability(int, NvLinkCapability) (uint32, Return) + GetNvLinkErrorCounter(int, NvLinkErrorCounter) (uint64, Return) + GetNvLinkInfo() NvLinkInfoHandler + GetNvLinkRemoteDeviceType(int) (IntNvLinkDeviceType, Return) + GetNvLinkRemotePciInfo(int) (PciInfo, Return) + GetNvLinkState(int) (EnableState, Return) + GetNvLinkUtilizationControl(int, int) (NvLinkUtilizationControl, Return) + GetNvLinkUtilizationCounter(int, int) (uint64, uint64, Return) + GetNvLinkVersion(int) (uint32, Return) + GetNvlinkBwMode() (NvlinkGetBwMode, Return) + GetNvlinkSupportedBwModes() (NvlinkSupportedBwModes, Return) + GetOfaUtilization() (uint32, uint32, Return) + GetP2PStatus(Device, GpuP2PCapsIndex) (GpuP2PStatus, Return) + GetPciInfo() (PciInfo, Return) + GetPciInfoExt() (PciInfoExt, Return) + GetPcieLinkMaxSpeed() (uint32, Return) + GetPcieReplayCounter() (int, Return) + GetPcieSpeed() (int, Return) + GetPcieThroughput(PcieUtilCounter) (uint32, Return) + GetPdi() (Pdi, Return) + GetPerformanceModes() (DevicePerfModes, Return) + GetPerformanceState() (Pstates, Return) + GetPersistenceMode() (EnableState, Return) + GetPgpuMetadataString() (string, Return) + GetPlatformInfo() (PlatformInfo, Return) + GetPowerManagementDefaultLimit() (uint32, Return) + GetPowerManagementLimit() (uint32, Return) + GetPowerManagementLimitConstraints() (uint32, uint32, Return) + GetPowerManagementMode() (EnableState, Return) + GetPowerMizerMode_v1() (DevicePowerMizerModes_v1, Return) + GetPowerSource() (PowerSource, Return) + GetPowerState() (Pstates, Return) + GetPowerUsage() (uint32, Return) + GetProcessUtilization(uint64) ([]ProcessUtilizationSample, Return) + GetProcessesUtilizationInfo() (ProcessesUtilizationInfo, Return) + GetRemappedRows() (int, int, bool, bool, Return) + GetRepairStatus() (RepairStatus, Return) + GetRetiredPages(PageRetirementCause) ([]uint64, Return) + GetRetiredPagesPendingStatus() (EnableState, Return) + GetRetiredPages_v2(PageRetirementCause) ([]uint64, []uint64, Return) + GetRowRemapperHistogram() (RowRemapperHistogramValues, Return) + GetRunningProcessDetailList() (ProcessDetailList, Return) + GetSamples(SamplingType, uint64) (ValueType, []Sample, Return) + GetSerial() (string, Return) + GetSramEccErrorStatus() (EccSramErrorStatus, Return) + GetSramUniqueUncorrectedEccErrorCounts(*EccSramUniqueUncorrectedErrorCounts) Return + GetSupportedClocksEventReasons() (uint64, Return) + GetSupportedClocksThrottleReasons() (uint64, Return) + GetSupportedEventTypes() (uint64, Return) + GetSupportedGraphicsClocks(int) (int, uint32, Return) + GetSupportedMemoryClocks() (int, uint32, Return) + GetSupportedPerformanceStates() ([]Pstates, Return) + GetSupportedVgpus() ([]VgpuTypeId, Return) + GetTargetFanSpeed(int) (int, Return) + GetTemperature(TemperatureSensors) (uint32, Return) + GetTemperatureThreshold(TemperatureThresholds) (uint32, Return) + GetTemperatureV() TemperatureHandler + GetThermalSettings(uint32) (GpuThermalSettings, Return) + GetTopologyCommonAncestor(Device) (GpuTopologyLevel, Return) + GetTopologyNearestGpus(GpuTopologyLevel) ([]Device, Return) + GetTotalEccErrors(MemoryErrorType, EccCounterType) (uint64, Return) + GetTotalEnergyConsumption() (uint64, Return) + GetUUID() (string, Return) + GetUtilizationRates() (Utilization, Return) + GetVbiosVersion() (string, Return) + GetVgpuCapabilities(DeviceVgpuCapability) (bool, Return) + GetVgpuHeterogeneousMode() (VgpuHeterogeneousMode, Return) + GetVgpuInstancesUtilizationInfo() (VgpuInstancesUtilizationInfo, Return) + GetVgpuMetadata() (VgpuPgpuMetadata, Return) + GetVgpuProcessUtilization(uint64) ([]VgpuProcessUtilizationSample, Return) + GetVgpuProcessesUtilizationInfo() (VgpuProcessesUtilizationInfo, Return) + GetVgpuSchedulerCapabilities() (VgpuSchedulerCapabilities, Return) + GetVgpuSchedulerLog() (VgpuSchedulerLog, Return) + GetVgpuSchedulerState() (VgpuSchedulerGetState, Return) + GetVgpuTypeCreatablePlacements(VgpuTypeId) (VgpuPlacementList, Return) + GetVgpuTypeSupportedPlacements(VgpuTypeId) (VgpuPlacementList, Return) + GetVgpuUtilization(uint64) (ValueType, []VgpuInstanceUtilizationSample, Return) + GetViolationStatus(PerfPolicyType) (ViolationTime, Return) + GetVirtualizationMode() (GpuVirtualizationMode, Return) + GpmMigSampleGet(int, GpmSample) Return + GpmQueryDeviceSupport() (GpmSupport, Return) + GpmQueryDeviceSupportV() GpmSupportV + GpmQueryIfStreamingEnabled() (uint32, Return) + GpmSampleGet(GpmSample) Return + GpmSetStreamingEnabled(uint32) Return + IsMigDeviceHandle() (bool, Return) + OnSameBoard(Device) (int, Return) + PowerSmoothingActivatePresetProfile(*PowerSmoothingProfile) Return + PowerSmoothingSetState(*PowerSmoothingState) Return + PowerSmoothingUpdatePresetProfileParam(*PowerSmoothingProfile) Return + ReadWritePRM_v1(*PRMTLV_v1) Return + RegisterEvents(uint64, EventSet) Return + ResetApplicationsClocks() Return + ResetGpuLockedClocks() Return + ResetMemoryLockedClocks() Return + ResetNvLinkErrorCounters(int) Return + ResetNvLinkUtilizationCounter(int, int) Return + SetAPIRestriction(RestrictedAPI, EnableState) Return + SetAccountingMode(EnableState) Return + SetApplicationsClocks(uint32, uint32) Return + SetAutoBoostedClocksEnabled(EnableState) Return + SetClockOffsets(ClockOffset) Return + SetComputeMode(ComputeMode) Return + SetConfComputeUnprotectedMemSize(uint64) Return + SetCpuAffinity() Return + SetDefaultAutoBoostedClocksEnabled(EnableState, uint32) Return + SetDefaultFanSpeed_v2(int) Return + SetDramEncryptionMode(*DramEncryptionInfo) Return + SetDriverModel(DriverModel, uint32) Return + SetEccMode(EnableState) Return + SetFanControlPolicy(int, FanControlPolicy) Return + SetFanSpeed_v2(int, int) Return + SetGpcClkVfOffset(int) Return + SetGpuLockedClocks(uint32, uint32) Return + SetGpuOperationMode(GpuOperationMode) Return + SetMemClkVfOffset(int) Return + SetMemoryLockedClocks(uint32, uint32) Return + SetMigMode(int) (Return, Return) + SetNvLinkDeviceLowPowerThreshold(*NvLinkPowerThres) Return + SetNvLinkUtilizationControl(int, int, *NvLinkUtilizationControl, bool) Return + SetNvlinkBwMode(*NvlinkSetBwMode) Return + SetPersistenceMode(EnableState) Return + SetPowerManagementLimit(uint32) Return + SetPowerManagementLimit_v2(*PowerValue_v2) Return + SetTemperatureThreshold(TemperatureThresholds, int) Return + SetVgpuCapabilities(DeviceVgpuCapability, EnableState) Return + SetVgpuHeterogeneousMode(VgpuHeterogeneousMode) Return + SetVgpuSchedulerState(*VgpuSchedulerSetState) Return + SetVirtualizationMode(GpuVirtualizationMode) Return + ValidateInforom() Return + VgpuTypeGetMaxInstances(VgpuTypeId) (int, Return) + WorkloadPowerProfileClearRequestedProfiles(*WorkloadPowerProfileRequestedProfiles) Return + WorkloadPowerProfileGetCurrentProfiles() (WorkloadPowerProfileCurrentProfiles, Return) + WorkloadPowerProfileGetProfilesInfo() (WorkloadPowerProfileProfilesInfo, Return) + WorkloadPowerProfileSetRequestedProfiles(*WorkloadPowerProfileRequestedProfiles) Return +} + +// GpuInstance represents the interface for the nvmlGpuInstance type. +// +//go:generate moq -out mock/gpuinstance.go -pkg mock . GpuInstance:GpuInstance +type GpuInstance interface { + CreateComputeInstance(*ComputeInstanceProfileInfo) (ComputeInstance, Return) + CreateComputeInstanceWithPlacement(*ComputeInstanceProfileInfo, *ComputeInstancePlacement) (ComputeInstance, Return) + Destroy() Return + GetActiveVgpus() (ActiveVgpuInstanceInfo, Return) + GetComputeInstanceById(int) (ComputeInstance, Return) + GetComputeInstancePossiblePlacements(*ComputeInstanceProfileInfo) ([]ComputeInstancePlacement, Return) + GetComputeInstanceProfileInfo(int, int) (ComputeInstanceProfileInfo, Return) + GetComputeInstanceProfileInfoV(int, int) ComputeInstanceProfileInfoHandler + GetComputeInstanceRemainingCapacity(*ComputeInstanceProfileInfo) (int, Return) + GetComputeInstances(*ComputeInstanceProfileInfo) ([]ComputeInstance, Return) + GetCreatableVgpus() (VgpuTypeIdInfo, Return) + GetInfo() (GpuInstanceInfo, Return) + GetVgpuHeterogeneousMode() (VgpuHeterogeneousMode, Return) + GetVgpuSchedulerLog() (VgpuSchedulerLogInfo, Return) + GetVgpuSchedulerState() (VgpuSchedulerStateInfo, Return) + GetVgpuTypeCreatablePlacements() (VgpuCreatablePlacementInfo, Return) + SetVgpuHeterogeneousMode(*VgpuHeterogeneousMode) Return + SetVgpuSchedulerState(*VgpuSchedulerState) Return +} + +// ComputeInstance represents the interface for the nvmlComputeInstance type. +// +//go:generate moq -out mock/computeinstance.go -pkg mock . ComputeInstance:ComputeInstance +type ComputeInstance interface { + Destroy() Return + GetInfo() (ComputeInstanceInfo, Return) +} + +// EventSet represents the interface for the nvmlEventSet type. +// +//go:generate moq -out mock/eventset.go -pkg mock . EventSet:EventSet +type EventSet interface { + Free() Return + Wait(uint32) (EventData, Return) +} + +// GpmSample represents the interface for the nvmlGpmSample type. +// +//go:generate moq -out mock/gpmsample.go -pkg mock . GpmSample:GpmSample +type GpmSample interface { + Free() Return + Get(Device) Return + MigGet(Device, int) Return +} + +// Unit represents the interface for the nvmlUnit type. +// +//go:generate moq -out mock/unit.go -pkg mock . Unit:Unit +type Unit interface { + GetDevices() ([]Device, Return) + GetFanSpeedInfo() (UnitFanSpeeds, Return) + GetLedState() (LedState, Return) + GetPsuInfo() (PSUInfo, Return) + GetTemperature(int) (uint32, Return) + GetUnitInfo() (UnitInfo, Return) + SetLedState(LedColor) Return +} + +// VgpuInstance represents the interface for the nvmlVgpuInstance type. +// +//go:generate moq -out mock/vgpuinstance.go -pkg mock . VgpuInstance:VgpuInstance +type VgpuInstance interface { + ClearAccountingPids() Return + GetAccountingMode() (EnableState, Return) + GetAccountingPids() ([]int, Return) + GetAccountingStats(int) (AccountingStats, Return) + GetEccMode() (EnableState, Return) + GetEncoderCapacity() (int, Return) + GetEncoderSessions() (int, EncoderSessionInfo, Return) + GetEncoderStats() (int, uint32, uint32, Return) + GetFBCSessions() (int, FBCSessionInfo, Return) + GetFBCStats() (FBCStats, Return) + GetFbUsage() (uint64, Return) + GetFrameRateLimit() (uint32, Return) + GetGpuInstanceId() (int, Return) + GetGpuPciId() (string, Return) + GetLicenseInfo() (VgpuLicenseInfo, Return) + GetLicenseStatus() (int, Return) + GetMdevUUID() (string, Return) + GetMetadata() (VgpuMetadata, Return) + GetRuntimeStateSize() (VgpuRuntimeState, Return) + GetType() (VgpuTypeId, Return) + GetUUID() (string, Return) + GetVmDriverVersion() (string, Return) + GetVmID() (string, VgpuVmIdType, Return) + SetEncoderCapacity(int) Return +} + +// VgpuTypeId represents the interface for the nvmlVgpuTypeId type. +// +//go:generate moq -out mock/vgputypeid.go -pkg mock . VgpuTypeId:VgpuTypeId +type VgpuTypeId interface { + GetBAR1Info() (VgpuTypeBar1Info, Return) + GetCapabilities(VgpuCapability) (bool, Return) + GetClass() (string, Return) + GetCreatablePlacements(Device) (VgpuPlacementList, Return) + GetDeviceID() (uint64, uint64, Return) + GetFrameRateLimit() (uint32, Return) + GetFramebufferSize() (uint64, Return) + GetGpuInstanceProfileId() (uint32, Return) + GetLicense() (string, Return) + GetMaxInstances(Device) (int, Return) + GetMaxInstancesPerVm() (int, Return) + GetName() (string, Return) + GetNumDisplayHeads() (int, Return) + GetResolution(int) (uint32, uint32, Return) + GetSupportedPlacements(Device) (VgpuPlacementList, Return) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/LICENSE b/vendor/github.com/NVIDIA/nvidia-container-toolkit/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/builder.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/builder.go new file mode 100644 index 00000000..332d017a --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/builder.go @@ -0,0 +1,102 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +import ( + "fmt" + "strings" + + "github.com/opencontainers/runtime-spec/specs-go" +) + +type builder struct { + env map[string]string + mounts []specs.Mount + disableRequire bool +} + +// New creates a new CUDA image from the input options. +func New(opt ...Option) (CUDA, error) { + b := &builder{} + for _, o := range opt { + if err := o(b); err != nil { + return CUDA{}, err + } + } + if b.env == nil { + b.env = make(map[string]string) + } + + return b.build() +} + +// build creates a CUDA image from the builder. +func (b builder) build() (CUDA, error) { + if b.disableRequire { + b.env[EnvVarNvidiaDisableRequire] = "true" + } + + c := CUDA{ + env: b.env, + mounts: b.mounts, + } + return c, nil +} + +// Option is a functional option for creating a CUDA image. +type Option func(*builder) error + +// WithDisableRequire sets the disable require option. +func WithDisableRequire(disableRequire bool) Option { + return func(b *builder) error { + b.disableRequire = disableRequire + return nil + } +} + +// WithEnv sets the environment variables to use when creating the CUDA image. +// Note that this also overwrites the values set with WithEnvMap. +func WithEnv(env []string) Option { + return func(b *builder) error { + envmap := make(map[string]string) + for _, e := range env { + parts := strings.SplitN(e, "=", 2) + if len(parts) != 2 { + return fmt.Errorf("invalid environment variable: %v", e) + } + envmap[parts[0]] = parts[1] + } + return WithEnvMap(envmap)(b) + } +} + +// WithEnvMap sets the environment variable map to use when creating the CUDA image. +// Note that this also overwrites the values set with WithEnv. +func WithEnvMap(env map[string]string) Option { + return func(b *builder) error { + b.env = env + return nil + } +} + +// WithMounts sets the mounts associated with the CUDA image. +func WithMounts(mounts []specs.Mount) Option { + return func(b *builder) error { + b.mounts = mounts + return nil + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/capabilities.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/capabilities.go new file mode 100644 index 00000000..824a6db9 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/capabilities.go @@ -0,0 +1,146 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +import ( + "sort" + "strings" +) + +// DriverCapability represents the possible values of NVIDIA_DRIVER_CAPABILITIES +type DriverCapability string + +// Constants for the supported driver capabilities +const ( + DriverCapabilityAll DriverCapability = "all" + DriverCapabilityNone DriverCapability = "none" + DriverCapabilityCompat32 DriverCapability = "compat32" + DriverCapabilityCompute DriverCapability = "compute" + DriverCapabilityDisplay DriverCapability = "display" + DriverCapabilityGraphics DriverCapability = "graphics" + DriverCapabilityNgx DriverCapability = "ngx" + DriverCapabilityUtility DriverCapability = "utility" + DriverCapabilityVideo DriverCapability = "video" +) + +var ( + driverCapabilitiesNone = NewDriverCapabilities() + driverCapabilitiesAll = NewDriverCapabilities("all") + + // DefaultDriverCapabilities sets the value for driver capabilities if no value is set. + DefaultDriverCapabilities = NewDriverCapabilities("utility,compute") + // SupportedDriverCapabilities defines the set of all supported driver capabilities. + SupportedDriverCapabilities = NewDriverCapabilities("compute,compat32,graphics,utility,video,display,ngx") +) + +// NewDriverCapabilities creates a set of driver capabilities from the specified capabilities +func NewDriverCapabilities(capabilities ...string) DriverCapabilities { + dc := make(DriverCapabilities) + for _, capability := range capabilities { + for _, c := range strings.Split(capability, ",") { + trimmed := strings.TrimSpace(c) + if trimmed == "" { + continue + } + dc[DriverCapability(trimmed)] = true + } + } + return dc +} + +// DriverCapabilities represents the NVIDIA_DRIVER_CAPABILITIES set for the specified image. +type DriverCapabilities map[DriverCapability]bool + +// Has check whether the specified capability is selected. +func (c DriverCapabilities) Has(capability DriverCapability) bool { + if c.IsAll() { + return true + } + return c[capability] +} + +// Any checks whether any of the specified capabilities are set +func (c DriverCapabilities) Any(capabilities ...DriverCapability) bool { + if c.IsAll() { + return true + } + for _, cap := range capabilities { + if c.Has(cap) { + return true + } + } + return false +} + +// List returns the list of driver capabilities. +// The list is sorted. +func (c DriverCapabilities) List() []string { + var capabilities []string + for capability := range c { + capabilities = append(capabilities, string(capability)) + } + sort.Strings(capabilities) + return capabilities +} + +// String returns the string repesentation of the driver capabilities. +func (c DriverCapabilities) String() string { + if c.IsAll() { + return "all" + } + return strings.Join(c.List(), ",") +} + +// IsAll indicates whether the set of capabilities is `all` +func (c DriverCapabilities) IsAll() bool { + return c[DriverCapabilityAll] +} + +// Intersection returns a new set which includes the item in BOTH d and s2. +// For example: d = {a1, a2} s2 = {a2, a3} s1.Intersection(s2) = {a2} +func (c DriverCapabilities) Intersection(s2 DriverCapabilities) DriverCapabilities { + if s2.IsAll() { + return c + } + if c.IsAll() { + return s2 + } + + intersection := make(DriverCapabilities) + for capability := range s2 { + if c[capability] { + intersection[capability] = true + } + } + + return intersection +} + +// IsSuperset returns true if and only if d is a superset of s2. +func (c DriverCapabilities) IsSuperset(s2 DriverCapabilities) bool { + if c.IsAll() { + return true + } + + for capability := range s2 { + if !c[capability] { + return false + } + } + + return true +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/cuda_image.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/cuda_image.go new file mode 100644 index 00000000..d5bbc224 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/cuda_image.go @@ -0,0 +1,312 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +import ( + "fmt" + "path/filepath" + "strconv" + "strings" + + "github.com/opencontainers/runtime-spec/specs-go" + "golang.org/x/mod/semver" + "tags.cncf.io/container-device-interface/pkg/parser" +) + +const ( + DeviceListAsVolumeMountsRoot = "/var/run/nvidia-container-devices" + + volumeMountDevicePrefixCDI = "cdi/" + volumeMountDevicePrefixImex = "imex/" +) + +// CUDA represents a CUDA image that can be used for GPU computing. This wraps +// a map of environment variable to values that can be used to perform lookups +// such as requirements. +type CUDA struct { + env map[string]string + mounts []specs.Mount +} + +// NewCUDAImageFromSpec creates a CUDA image from the input OCI runtime spec. +// The process environment is read (if present) to construc the CUDA Image. +func NewCUDAImageFromSpec(spec *specs.Spec) (CUDA, error) { + var env []string + if spec != nil && spec.Process != nil { + env = spec.Process.Env + } + + return New( + WithEnv(env), + WithMounts(spec.Mounts), + ) +} + +// NewCUDAImageFromEnv creates a CUDA image from the input environment. The environment +// is a list of strings of the form ENVAR=VALUE. +func NewCUDAImageFromEnv(env []string) (CUDA, error) { + return New(WithEnv(env)) +} + +// Getenv returns the value of the specified environment variable. +// If the environment variable is not specified, an empty string is returned. +func (i CUDA) Getenv(key string) string { + return i.env[key] +} + +// HasEnvvar checks whether the specified envvar is defined in the image. +func (i CUDA) HasEnvvar(key string) bool { + _, exists := i.env[key] + return exists +} + +// IsLegacy returns whether the associated CUDA image is a "legacy" image. An +// image is considered legacy if it has a CUDA_VERSION environment variable defined +// and no NVIDIA_REQUIRE_CUDA environment variable defined. +func (i CUDA) IsLegacy() bool { + legacyCudaVersion := i.env[EnvVarCudaVersion] + cudaRequire := i.env[EnvVarNvidiaRequireCuda] + return len(legacyCudaVersion) > 0 && len(cudaRequire) == 0 +} + +// GetRequirements returns the requirements from all NVIDIA_REQUIRE_ environment +// variables. +func (i CUDA) GetRequirements() ([]string, error) { + if i.HasDisableRequire() { + return nil, nil + } + + // All variables with the "NVIDIA_REQUIRE_" prefix are passed to nvidia-container-cli + var requirements []string + for name, value := range i.env { + if strings.HasPrefix(name, NvidiaRequirePrefix) && !strings.HasPrefix(name, EnvVarNvidiaRequireJetpack) { + requirements = append(requirements, value) + } + } + if i.IsLegacy() { + v, err := i.legacyVersion() + if err != nil { + return nil, fmt.Errorf("failed to get version: %v", err) + } + cudaRequire := fmt.Sprintf("cuda>=%s", v) + requirements = append(requirements, cudaRequire) + } + return requirements, nil +} + +// HasDisableRequire checks for the value of the NVIDIA_DISABLE_REQUIRE. If set +// to a valid (true) boolean value this can be used to disable the requirement checks +func (i CUDA) HasDisableRequire() bool { + if disable, exists := i.env[EnvVarNvidiaDisableRequire]; exists { + // i.logger.Debugf("NVIDIA_DISABLE_REQUIRE=%v; skipping requirement checks", disable) + d, _ := strconv.ParseBool(disable) + return d + } + + return false +} + +// DevicesFromEnvvars returns the devices requested by the image through environment variables +func (i CUDA) DevicesFromEnvvars(envVars ...string) VisibleDevices { + // We concantenate all the devices from the specified env. + var isSet bool + var devices []string + requested := make(map[string]bool) + for _, envVar := range envVars { + if devs, ok := i.env[envVar]; ok { + isSet = true + for _, d := range strings.Split(devs, ",") { + trimmed := strings.TrimSpace(d) + if len(trimmed) == 0 { + continue + } + devices = append(devices, trimmed) + requested[trimmed] = true + } + } + } + + // Environment variable unset with legacy image: default to "all". + if !isSet && len(devices) == 0 && i.IsLegacy() { + return NewVisibleDevices("all") + } + + // Environment variable unset or empty or "void": return nil + if len(devices) == 0 || requested["void"] { + return NewVisibleDevices("void") + } + + return NewVisibleDevices(devices...) +} + +// GetDriverCapabilities returns the requested driver capabilities. +func (i CUDA) GetDriverCapabilities() DriverCapabilities { + env := i.env[EnvVarNvidiaDriverCapabilities] + + capabilities := make(DriverCapabilities) + for _, c := range strings.Split(env, ",") { + capabilities[DriverCapability(c)] = true + } + + return capabilities +} + +func (i CUDA) legacyVersion() (string, error) { + cudaVersion := i.env[EnvVarCudaVersion] + majorMinor, err := parseMajorMinorVersion(cudaVersion) + if err != nil { + return "", fmt.Errorf("invalid CUDA version %v: %v", cudaVersion, err) + } + + return majorMinor, nil +} + +func parseMajorMinorVersion(version string) (string, error) { + vVersion := "v" + strings.TrimPrefix(version, "v") + + if !semver.IsValid(vVersion) { + return "", fmt.Errorf("invalid version string") + } + + majorMinor := strings.TrimPrefix(semver.MajorMinor(vVersion), "v") + parts := strings.Split(majorMinor, ".") + + var err error + _, err = strconv.ParseUint(parts[0], 10, 32) + if err != nil { + return "", fmt.Errorf("invalid major version") + } + _, err = strconv.ParseUint(parts[1], 10, 32) + if err != nil { + return "", fmt.Errorf("invalid minor version") + } + return majorMinor, nil +} + +// OnlyFullyQualifiedCDIDevices returns true if all devices requested in the image are requested as CDI devices/ +func (i CUDA) OnlyFullyQualifiedCDIDevices() bool { + var hasCDIdevice bool + for _, device := range i.VisibleDevicesFromEnvVar() { + if !parser.IsQualifiedName(device) { + return false + } + hasCDIdevice = true + } + + for _, device := range i.DevicesFromMounts() { + if !strings.HasPrefix(device, "cdi/") { + return false + } + hasCDIdevice = true + } + return hasCDIdevice +} + +// VisibleDevicesFromEnvVar returns the set of visible devices requested through +// the NVIDIA_VISIBLE_DEVICES environment variable. +func (i CUDA) VisibleDevicesFromEnvVar() []string { + return i.DevicesFromEnvvars(EnvVarNvidiaVisibleDevices).List() +} + +// VisibleDevicesFromMounts returns the set of visible devices requested as mounts. +func (i CUDA) VisibleDevicesFromMounts() []string { + var devices []string + for _, device := range i.DevicesFromMounts() { + switch { + case strings.HasPrefix(device, volumeMountDevicePrefixCDI): + continue + case strings.HasPrefix(device, volumeMountDevicePrefixImex): + continue + } + devices = append(devices, device) + } + return devices +} + +// DevicesFromMounts returns a list of device specified as mounts. +// TODO: This should be merged with getDevicesFromMounts used in the NVIDIA Container Runtime +func (i CUDA) DevicesFromMounts() []string { + root := filepath.Clean(DeviceListAsVolumeMountsRoot) + seen := make(map[string]bool) + var devices []string + for _, m := range i.mounts { + source := filepath.Clean(m.Source) + // Only consider mounts who's host volume is /dev/null + if source != "/dev/null" { + continue + } + + destination := filepath.Clean(m.Destination) + if seen[destination] { + continue + } + seen[destination] = true + + // Only consider container mount points that begin with 'root' + if !strings.HasPrefix(destination, root) { + continue + } + + // Grab the full path beyond 'root' and add it to the list of devices + device := strings.Trim(strings.TrimPrefix(destination, root), "/") + if len(device) == 0 { + continue + } + devices = append(devices, device) + } + return devices +} + +// CDIDevicesFromMounts returns a list of CDI devices specified as mounts on the image. +func (i CUDA) CDIDevicesFromMounts() []string { + var devices []string + for _, mountDevice := range i.DevicesFromMounts() { + if !strings.HasPrefix(mountDevice, volumeMountDevicePrefixCDI) { + continue + } + parts := strings.SplitN(strings.TrimPrefix(mountDevice, volumeMountDevicePrefixCDI), "/", 3) + if len(parts) != 3 { + continue + } + vendor := parts[0] + class := parts[1] + device := parts[2] + devices = append(devices, fmt.Sprintf("%s/%s=%s", vendor, class, device)) + } + return devices +} + +// ImexChannelsFromEnvVar returns the list of IMEX channels requested for the image. +func (i CUDA) ImexChannelsFromEnvVar() []string { + imexChannels := i.DevicesFromEnvvars(EnvVarNvidiaImexChannels).List() + if len(imexChannels) == 1 && imexChannels[0] == "all" { + return nil + } + return imexChannels +} + +// ImexChannelsFromMounts returns the list of IMEX channels requested for the image. +func (i CUDA) ImexChannelsFromMounts() []string { + var channels []string + for _, mountDevice := range i.DevicesFromMounts() { + if !strings.HasPrefix(mountDevice, volumeMountDevicePrefixImex) { + continue + } + channels = append(channels, strings.TrimPrefix(mountDevice, volumeMountDevicePrefixImex)) + } + return channels +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/devices.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/devices.go new file mode 100644 index 00000000..f5a6ad95 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/devices.go @@ -0,0 +1,127 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +import ( + "strings" +) + +// VisibleDevices represents the devices selected in a container image +// through the NVIDIA_VISIBLE_DEVICES or other environment variables +type VisibleDevices interface { + List() []string + Has(string) bool +} + +var _ VisibleDevices = (*all)(nil) +var _ VisibleDevices = (*none)(nil) +var _ VisibleDevices = (*void)(nil) +var _ VisibleDevices = (*devices)(nil) + +// NewVisibleDevices creates a VisibleDevices based on the value of the specified envvar. +func NewVisibleDevices(envvars ...string) VisibleDevices { + for _, envvar := range envvars { + if envvar == "all" { + return all{} + } + if envvar == "none" { + return none{} + } + if envvar == "" || envvar == "void" { + return void{} + } + } + + return newDevices(envvars...) +} + +type all struct{} + +// List returns ["all"] for all devices +func (a all) List() []string { + return []string{"all"} +} + +// Has for all devices is true for any id except the empty ID +func (a all) Has(id string) bool { + return id != "" +} + +type none struct{} + +// List returns [""] for the none devices +func (n none) List() []string { + return []string{""} +} + +// Has for none devices is false for any id +func (n none) Has(id string) bool { + return false +} + +type void struct { + none +} + +// List returns nil for the void devices +func (v void) List() []string { + return nil +} + +type devices struct { + len int + lookup map[string]int +} + +func newDevices(idOrCommaSeparated ...string) devices { + lookup := make(map[string]int) + + i := 0 + for _, commaSeparated := range idOrCommaSeparated { + for _, id := range strings.Split(commaSeparated, ",") { + lookup[id] = i + i++ + } + } + + d := devices{ + len: i, + lookup: lookup, + } + return d +} + +// List returns the list of requested devices +func (d devices) List() []string { + list := make([]string, d.len) + + for id, i := range d.lookup { + list[i] = id + } + + return list +} + +// Has checks whether the specified ID is in the set of requested devices +func (d devices) Has(id string) bool { + if id == "" { + return false + } + + _, exist := d.lookup[id] + return exist +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/envvars.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/envvars.go new file mode 100644 index 00000000..0789f22f --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/envvars.go @@ -0,0 +1,31 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +const ( + EnvVarCudaVersion = "CUDA_VERSION" + EnvVarNvidiaDisableRequire = "NVIDIA_DISABLE_REQUIRE" + EnvVarNvidiaDriverCapabilities = "NVIDIA_DRIVER_CAPABILITIES" + EnvVarNvidiaImexChannels = "NVIDIA_IMEX_CHANNELS" + EnvVarNvidiaMigConfigDevices = "NVIDIA_MIG_CONFIG_DEVICES" + EnvVarNvidiaMigMonitorDevices = "NVIDIA_MIG_MONITOR_DEVICES" + EnvVarNvidiaRequireCuda = NvidiaRequirePrefix + "CUDA" + EnvVarNvidiaRequireJetpack = NvidiaRequirePrefix + "JETPACK" + EnvVarNvidiaVisibleDevices = "NVIDIA_VISIBLE_DEVICES" + + NvidiaRequirePrefix = "NVIDIA_REQUIRE_" +) diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/privileged.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/privileged.go new file mode 100644 index 00000000..a54598d6 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/config/image/privileged.go @@ -0,0 +1,43 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package image + +import ( + "github.com/opencontainers/runtime-spec/specs-go" +) + +const ( + capSysAdmin = "CAP_SYS_ADMIN" +) + +// IsPrivileged returns true if the container is a privileged container. +func IsPrivileged(s *specs.Spec) bool { + if s.Process.Capabilities == nil { + return false + } + + // We only make sure that the bounding capabibility set has + // CAP_SYS_ADMIN. This allows us to make sure that the container was + // actually started as '--privileged', but also allow non-root users to + // access the privileged NVIDIA capabilities. + for _, c := range s.Process.Capabilities.Bounding { + if c == capSysAdmin { + return true + } + } + return false +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/cache.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/cache.go new file mode 100644 index 00000000..e9e4b615 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/cache.go @@ -0,0 +1,80 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "sync" + +type cache struct { + d Discover + + sync.Mutex + devices []Device + hooks []Hook + mounts []Mount +} + +var _ Discover = (*cache)(nil) + +// WithCache decorates the specified disoverer with a cache. +func WithCache(d Discover) Discover { + if d == nil { + return None{} + } + return &cache{d: d} +} + +func (c *cache) Devices() ([]Device, error) { + c.Lock() + defer c.Unlock() + + if c.devices == nil { + devices, err := c.d.Devices() + if err != nil { + return nil, err + } + c.devices = devices + } + return c.devices, nil +} + +func (c *cache) Hooks() ([]Hook, error) { + c.Lock() + defer c.Unlock() + + if c.hooks == nil { + hooks, err := c.d.Hooks() + if err != nil { + return nil, err + } + c.hooks = hooks + } + return c.hooks, nil +} + +func (c *cache) Mounts() ([]Mount, error) { + c.Lock() + defer c.Unlock() + + if c.mounts == nil { + mounts, err := c.d.Mounts() + if err != nil { + return nil, err + } + c.mounts = mounts + } + return c.mounts, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/char_devices.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/char_devices.go new file mode 100644 index 00000000..8d59430d --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/char_devices.go @@ -0,0 +1,62 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +// charDevices is a discover for a list of character devices +type charDevices mounts + +var _ Discover = (*charDevices)(nil) + +// NewCharDeviceDiscoverer creates a discoverer which locates the specified set of device nodes. +func NewCharDeviceDiscoverer(logger logger.Interface, devRoot string, devices []string) Discover { + locator := lookup.NewCharDeviceLocator( + lookup.WithLogger(logger), + lookup.WithRoot(devRoot), + ) + + return (*charDevices)(newMounts(logger, locator, devRoot, devices)) +} + +// Mounts returns the discovered mounts for the charDevices. +// Since this explicitly specifies a device list, the mounts are nil. +func (d *charDevices) Mounts() ([]Mount, error) { + return nil, nil +} + +// Devices returns the discovered devices for the charDevices. +// Here the device nodes are first discovered as mounts and these are converted to devices. +func (d *charDevices) Devices() ([]Device, error) { + devicesAsMounts, err := (*mounts)(d).Mounts() + if err != nil { + return nil, err + } + var devices []Device + for _, mount := range devicesAsMounts { + device := Device{ + HostPath: mount.HostPath, + Path: mount.Path, + } + devices = append(devices, device) + } + + return devices, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/compat_libs.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/compat_libs.go new file mode 100644 index 00000000..027ca2ed --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/compat_libs.go @@ -0,0 +1,24 @@ +package discover + +import ( + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root" +) + +// NewCUDACompatHookDiscoverer creates a discoverer for a enable-cuda-compat hook. +// This hook is responsible for setting up CUDA compatibility in the container and depends on the host driver version. +func NewCUDACompatHookDiscoverer(logger logger.Interface, nvidiaCDIHookPath string, driver *root.Driver) Discover { + _, cudaVersionPattern := getCUDALibRootAndVersionPattern(logger, driver) + var args []string + if !strings.Contains(cudaVersionPattern, "*") { + args = append(args, "--host-driver-version="+cudaVersionPattern) + } + + return CreateNvidiaCDIHook( + nvidiaCDIHookPath, + "enable-cuda-compat", + args..., + ) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover.go new file mode 100644 index 00000000..2ec33174 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover.go @@ -0,0 +1,47 @@ +/* +# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package discover + +// Device represents a discovered character device. +type Device struct { + HostPath string + Path string +} + +// Mount represents a discovered mount. +type Mount struct { + HostPath string + Path string + Options []string +} + +// Hook represents a discovered hook. +type Hook struct { + Lifecycle string + Path string + Args []string + Env []string +} + +// Discover defines an interface for discovering the devices, mounts, and hooks available on a system +// +//go:generate moq -stub -out discover_mock.go . Discover +type Discover interface { + Devices() ([]Device, error) + Mounts() ([]Mount, error) + Hooks() ([]Hook, error) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover_mock.go new file mode 100644 index 00000000..d9be6ffb --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/discover_mock.go @@ -0,0 +1,153 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package discover + +import ( + "sync" +) + +// Ensure, that DiscoverMock does implement Discover. +// If this is not the case, regenerate this file with moq. +var _ Discover = &DiscoverMock{} + +// DiscoverMock is a mock implementation of Discover. +// +// func TestSomethingThatUsesDiscover(t *testing.T) { +// +// // make and configure a mocked Discover +// mockedDiscover := &DiscoverMock{ +// DevicesFunc: func() ([]Device, error) { +// panic("mock out the Devices method") +// }, +// HooksFunc: func() ([]Hook, error) { +// panic("mock out the Hooks method") +// }, +// MountsFunc: func() ([]Mount, error) { +// panic("mock out the Mounts method") +// }, +// } +// +// // use mockedDiscover in code that requires Discover +// // and then make assertions. +// +// } +type DiscoverMock struct { + // DevicesFunc mocks the Devices method. + DevicesFunc func() ([]Device, error) + + // HooksFunc mocks the Hooks method. + HooksFunc func() ([]Hook, error) + + // MountsFunc mocks the Mounts method. + MountsFunc func() ([]Mount, error) + + // calls tracks calls to the methods. + calls struct { + // Devices holds details about calls to the Devices method. + Devices []struct { + } + // Hooks holds details about calls to the Hooks method. + Hooks []struct { + } + // Mounts holds details about calls to the Mounts method. + Mounts []struct { + } + } + lockDevices sync.RWMutex + lockHooks sync.RWMutex + lockMounts sync.RWMutex +} + +// Devices calls DevicesFunc. +func (mock *DiscoverMock) Devices() ([]Device, error) { + callInfo := struct { + }{} + mock.lockDevices.Lock() + mock.calls.Devices = append(mock.calls.Devices, callInfo) + mock.lockDevices.Unlock() + if mock.DevicesFunc == nil { + var ( + devicesOut []Device + errOut error + ) + return devicesOut, errOut + } + return mock.DevicesFunc() +} + +// DevicesCalls gets all the calls that were made to Devices. +// Check the length with: +// +// len(mockedDiscover.DevicesCalls()) +func (mock *DiscoverMock) DevicesCalls() []struct { +} { + var calls []struct { + } + mock.lockDevices.RLock() + calls = mock.calls.Devices + mock.lockDevices.RUnlock() + return calls +} + +// Hooks calls HooksFunc. +func (mock *DiscoverMock) Hooks() ([]Hook, error) { + callInfo := struct { + }{} + mock.lockHooks.Lock() + mock.calls.Hooks = append(mock.calls.Hooks, callInfo) + mock.lockHooks.Unlock() + if mock.HooksFunc == nil { + var ( + hooksOut []Hook + errOut error + ) + return hooksOut, errOut + } + return mock.HooksFunc() +} + +// HooksCalls gets all the calls that were made to Hooks. +// Check the length with: +// +// len(mockedDiscover.HooksCalls()) +func (mock *DiscoverMock) HooksCalls() []struct { +} { + var calls []struct { + } + mock.lockHooks.RLock() + calls = mock.calls.Hooks + mock.lockHooks.RUnlock() + return calls +} + +// Mounts calls MountsFunc. +func (mock *DiscoverMock) Mounts() ([]Mount, error) { + callInfo := struct { + }{} + mock.lockMounts.Lock() + mock.calls.Mounts = append(mock.calls.Mounts, callInfo) + mock.lockMounts.Unlock() + if mock.MountsFunc == nil { + var ( + mountsOut []Mount + errOut error + ) + return mountsOut, errOut + } + return mock.MountsFunc() +} + +// MountsCalls gets all the calls that were made to Mounts. +// Check the length with: +// +// len(mockedDiscover.MountsCalls()) +func (mock *DiscoverMock) MountsCalls() []struct { +} { + var calls []struct { + } + mock.lockMounts.RLock() + calls = mock.calls.Mounts + mock.lockMounts.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/filter.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/filter.go new file mode 100644 index 00000000..9de1c3fb --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/filter.go @@ -0,0 +1,62 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + +// Filter defines an interface for filtering discovered entities +type Filter interface { + DeviceIsSelected(device Device) bool +} + +// filtered represents a filtered discoverer +type filtered struct { + Discover + logger logger.Interface + filter Filter +} + +// newFilteredDiscoverer creates a discoverer that applies the specified filter to the returned entities of the discoverer +func newFilteredDiscoverer(logger logger.Interface, applyTo Discover, filter Filter) Discover { + return filtered{ + Discover: applyTo, + logger: logger, + filter: filter, + } +} + +// Devices returns a filtered list of devices based on the specified filter. +func (d filtered) Devices() ([]Device, error) { + devices, err := d.Discover.Devices() + if err != nil { + return nil, err + } + + if d.filter == nil { + return devices, nil + } + + var selected []Device + for _, device := range devices { + if d.filter.DeviceIsSelected(device) { + selected = append(selected, device) + } + d.logger.Debugf("skipping device %v", device) + } + + return selected, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/first-valid.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/first-valid.go new file mode 100644 index 00000000..36de9204 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/first-valid.go @@ -0,0 +1,72 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "errors" + +type firstOf []Discover + +// FirstValid returns a discoverer that returns the first non-error result from a list of discoverers. +func FirstValid(discoverers ...Discover) Discover { + var f firstOf + for _, d := range discoverers { + if d == nil { + continue + } + f = append(f, d) + } + return f +} + +func (f firstOf) Devices() ([]Device, error) { + var errs error + for _, d := range f { + devices, err := d.Devices() + if err != nil { + errs = errors.Join(errs, err) + continue + } + return devices, nil + } + return nil, errs +} + +func (f firstOf) Hooks() ([]Hook, error) { + var errs error + for _, d := range f { + hooks, err := d.Hooks() + if err != nil { + errs = errors.Join(errs, err) + continue + } + return hooks, nil + } + return nil, errs +} + +func (f firstOf) Mounts() ([]Mount, error) { + var errs error + for _, d := range f { + mounts, err := d.Mounts() + if err != nil { + errs = errors.Join(errs, err) + continue + } + return mounts, nil + } + return nil, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gdrcopy.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gdrcopy.go new file mode 100644 index 00000000..e6dcaec2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gdrcopy.go @@ -0,0 +1,27 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + +func NewGDRCopyDiscoverer(logger logger.Interface, devRoot string) (Discover, error) { + return NewCharDeviceDiscoverer( + logger, + devRoot, + []string{"/dev/gdrdrv"}, + ), nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gds.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gds.go new file mode 100644 index 00000000..cf762cd8 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/gds.go @@ -0,0 +1,80 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +type gdsDeviceDiscoverer struct { + None + logger logger.Interface + devices Discover + mounts Discover +} + +// NewGDSDiscoverer creates a discoverer for GPUDirect Storage devices and mounts. +func NewGDSDiscoverer(logger logger.Interface, driverRoot string, devRoot string) (Discover, error) { + devices := NewCharDeviceDiscoverer( + logger, + devRoot, + []string{"/dev/nvidia-fs*"}, + ) + + udev := NewMounts( + logger, + lookup.NewDirectoryLocator(lookup.WithLogger(logger), lookup.WithRoot(driverRoot)), + driverRoot, + []string{"/run/udev"}, + ) + + cufile := NewMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithRoot(driverRoot), + ), + driverRoot, + []string{"/etc/cufile.json"}, + ) + + d := gdsDeviceDiscoverer{ + logger: logger, + devices: devices, + mounts: Merge(udev, cufile), + } + + return &d, nil +} + +// Devices discovers the nvidia-fs device nodes for use with GPUDirect Storage +func (d *gdsDeviceDiscoverer) Devices() ([]Device, error) { + return d.devices.Devices() +} + +// Mounts discovers the required mounts for GPUDirect Storage. +// If no devices are discovered the discovered mounts are empty +func (d *gdsDeviceDiscoverer) Mounts() ([]Mount, error) { + devices, err := d.Devices() + if err != nil || len(devices) == 0 { + d.logger.Debugf("No nvidia-fs devices detected; skipping detection of mounts") + return nil, nil + } + + return d.mounts.Mounts() +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/graphics.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/graphics.go new file mode 100644 index 00000000..e80dd0be --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/graphics.go @@ -0,0 +1,441 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/config/image" + "github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm" + "github.com/NVIDIA/nvidia-container-toolkit/internal/info/proc" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root" +) + +// NewDRMNodesDiscoverer returns a discoverer for the DRM device nodes associated with the specified visible devices. +// +// TODO: The logic for creating DRM devices should be consolidated between this +// and the logic for generating CDI specs for a single device. This is only used +// when applying OCI spec modifications to an incoming spec in "legacy" mode. +func NewDRMNodesDiscoverer(logger logger.Interface, devices image.VisibleDevices, devRoot string, nvidiaCDIHookPath string) (Discover, error) { + drmDeviceNodes, err := newDRMDeviceDiscoverer(logger, devices, devRoot) + if err != nil { + return nil, fmt.Errorf("failed to create DRM device discoverer: %v", err) + } + + drmByPathSymlinks := newCreateDRMByPathSymlinks(logger, drmDeviceNodes, devRoot, nvidiaCDIHookPath) + + discover := Merge(drmDeviceNodes, drmByPathSymlinks) + return discover, nil +} + +// NewGraphicsMountsDiscoverer creates a discoverer for the mounts required by graphics tools such as vulkan. +func NewGraphicsMountsDiscoverer(logger logger.Interface, driver *root.Driver, nvidiaCDIHookPath string) (Discover, error) { + libraries := newGraphicsLibrariesDiscoverer(logger, driver, nvidiaCDIHookPath) + + configs := NewMounts( + logger, + driver.Configs(), + driver.Root, + []string{ + "glvnd/egl_vendor.d/10_nvidia.json", + "egl/egl_external_platform.d/15_nvidia_gbm.json", + "egl/egl_external_platform.d/10_nvidia_wayland.json", + "nvidia/nvoptix.bin", + "X11/xorg.conf.d/10-nvidia.conf", + "X11/xorg.conf.d/nvidia-drm-outputclass.conf", + }, + ) + + discover := Merge( + libraries, + configs, + newVulkanConfigsDiscover(logger, driver), + ) + + return discover, nil +} + +// newVulkanConfigsDiscover creates a discoverer for vulkan ICD files. +// For these files we search the standard driver config paths as well as the +// driver root itself. This allows us to support GKE installations where the +// vulkan ICD files are at {{ .driverRoot }}/vulkan instead of in /etc/vulkan. +func newVulkanConfigsDiscover(logger logger.Interface, driver *root.Driver) Discover { + locator := lookup.First(driver.Configs(), driver.Files()) + return &mountsToContainerPath{ + logger: logger, + locator: locator, + required: []string{ + "vulkan/icd.d/nvidia_icd.json", + "vulkan/icd.d/nvidia_layers.json", + "vulkan/implicit_layer.d/nvidia_layers.json", + }, + containerRoot: "/etc", + } +} + +type graphicsDriverLibraries struct { + Discover + logger logger.Interface + nvidiaCDIHookPath string +} + +var _ Discover = (*graphicsDriverLibraries)(nil) + +func newGraphicsLibrariesDiscoverer(logger logger.Interface, driver *root.Driver, nvidiaCDIHookPath string) Discover { + cudaLibRoot, cudaVersionPattern := getCUDALibRootAndVersionPattern(logger, driver) + + libraries := NewMounts( + logger, + driver.Libraries(), + driver.Root, + []string{ + // The libnvidia-egl-gbm and libnvidia-egl-wayland libraries do not + // have the RM version. Use the *.* pattern to match X.Y.Z versions. + "libnvidia-egl-gbm.so.*.*", + "libnvidia-egl-wayland.so.*.*", + // We include the following libraries to have them available for + // symlink creation below: + // If CDI injection is used, these should already be detected as: + // * libnvidia-allocator.so.RM_VERSION + // * libnvidia-vulkan-producer.so.RM_VERSION + // but need to be handled for the legacy case too. + "libnvidia-allocator.so." + cudaVersionPattern, + "libnvidia-vulkan-producer.so." + cudaVersionPattern, + }, + ) + + xorgLibraries := NewMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithRoot(driver.Root), + lookup.WithSearchPaths(buildXOrgSearchPaths(cudaLibRoot)...), + lookup.WithCount(1), + ), + driver.Root, + []string{ + "nvidia_drv.so", + "libglxserver_nvidia.so." + cudaVersionPattern, + }, + ) + + return &graphicsDriverLibraries{ + Discover: Merge(libraries, xorgLibraries), + logger: logger, + nvidiaCDIHookPath: nvidiaCDIHookPath, + } +} + +// Mounts discovers the required libraries and filters out libnvidia-allocator.so. +// The library libnvidia-allocator.so is already handled by either the *.RM_VERSION +// injection or by libnvidia-container. We therefore filter it out here as a +// workaround for the case where libnvidia-container will re-mount this in the +// container, which causes issues with shared mount propagation. +func (d graphicsDriverLibraries) Mounts() ([]Mount, error) { + mounts, err := d.Discover.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to get library mounts: %v", err) + } + + var filtered []Mount + for _, mount := range mounts { + if d.isDriverLibrary(filepath.Base(mount.Path), "libnvidia-allocator.so") { + continue + } + filtered = append(filtered, mount) + } + return filtered, nil +} + +// Create necessary library symlinks for graphics drivers +func (d graphicsDriverLibraries) Hooks() ([]Hook, error) { + mounts, err := d.Discover.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to get library mounts: %v", err) + } + + var links []string + for _, mount := range mounts { + dir, filename := filepath.Split(mount.Path) + switch { + case d.isDriverLibrary(filename, "libnvidia-allocator.so"): + // gbm/nvidia-drm_gbm.so is a symlink to ../libnvidia-allocator.so.1 which + // in turn symlinks to libnvidia-allocator.so.RM_VERSION. + // The libnvidia-allocator.so.1 -> libnvidia-allocator.so.RM_VERSION symlink + // is created when ldconfig is run against the container and there + // is no explicit need to create it. + // create gbm/nvidia-drm_gbm.so -> ../libnvidia-allocate.so.1 symlink + linkPath := filepath.Join(dir, "gbm", "nvidia-drm_gbm.so") + links = append(links, fmt.Sprintf("%s::%s", "../libnvidia-allocator.so.1", linkPath)) + case d.isDriverLibrary(filename, "libnvidia-vulkan-producer.so"): + // libnvidia-vulkan-producer.so is a drirect symlink to libnvidia-vulkan-producer.so.RM_VERSION + // create libnvidia-vulkan-producer.so -> libnvidia-vulkan-producer.so.RM_VERSION symlink + linkPath := filepath.Join(dir, "libnvidia-vulkan-producer.so") + links = append(links, fmt.Sprintf("%s::%s", filename, linkPath)) + case d.isDriverLibrary(filename, "libglxserver_nvidia.so"): + // libglxserver_nvidia.so is a directl symlink to libglxserver_nvidia.so.RM_VERSION + // create libglxserver_nvidia.so -> libglxserver_nvidia.so.RM_VERSION symlink + linkPath := filepath.Join(dir, "libglxserver_nvidia.so") + links = append(links, fmt.Sprintf("%s::%s", filename, linkPath)) + } + } + if len(links) == 0 { + return nil, nil + } + + hooks := CreateCreateSymlinkHook(d.nvidiaCDIHookPath, links) + + return hooks.Hooks() +} + +// isDriverLibrary checks whether the specified filename is a specific driver library. +func (d graphicsDriverLibraries) isDriverLibrary(filename string, libraryName string) bool { + // TODO: Instead of `.*.*` we could use the driver version. + pattern := strings.TrimSuffix(libraryName, ".") + ".*.*" + match, _ := filepath.Match(pattern, filename) + return match +} + +// getCUDALibRootAndVersionPattern returns the parent directory and the version +// suffix of the libcuda.so.*.* library at the driver root. +// If the library cannot be located an empty root is returned. +// If the version string cannot be extracted, the generic *.* pattern is returned. +func getCUDALibRootAndVersionPattern(logger logger.Interface, driver *root.Driver) (string, string) { + libCudaPaths, err := cuda.New( + driver.Libraries(), + ).Locate(".*.*") + if err != nil { + logger.Warningf("failed to locate libcuda.so: %v; using *.*", err) + return "", "*.*" + } + libcudaPath := libCudaPaths[0] + + libRoot := filepath.Dir(libcudaPath) + version := strings.TrimPrefix(filepath.Base(libcudaPath), "libcuda.so.") + if version == "" { + logger.Warningf("failed to extract version from %v; using *.*", libcudaPath) + version = "*.*" + } + + return driver.RelativeToRoot(libRoot), version +} + +// buildXOrgSearchPaths returns the ordered list of search paths for XOrg files. +func buildXOrgSearchPaths(libRoot string) []string { + var paths []string + if libRoot != "" { + paths = append(paths, + filepath.Join(libRoot, "nvidia/xorg"), + filepath.Join(libRoot, "xorg", "modules", "drivers"), + filepath.Join(libRoot, "xorg", "modules", "extensions"), + filepath.Join(libRoot, "xorg", "modules/updates", "drivers"), + filepath.Join(libRoot, "xorg", "modules/updates", "extensions"), + ) + } + + return append(paths, + filepath.Join("/usr/lib/xorg", "modules", "drivers"), + filepath.Join("/usr/lib/xorg", "modules", "extensions"), + filepath.Join("/usr/lib/xorg", "modules/updates", "drivers"), + filepath.Join("/usr/lib/xorg", "modules/updates", "extensions"), + filepath.Join("/usr/lib64/xorg", "modules", "drivers"), + filepath.Join("/usr/lib64/xorg", "modules", "extensions"), + filepath.Join("/usr/lib64/xorg", "modules/updates", "drivers"), + filepath.Join("/usr/lib64/xorg", "modules/updates", "extensions"), + filepath.Join("/usr/X11R6/lib", "modules", "drivers"), + filepath.Join("/usr/X11R6/lib", "modules", "extensions"), + filepath.Join("/usr/X11R6/lib", "modules/updates", "drivers"), + filepath.Join("/usr/X11R6/lib", "modules/updates", "extensions"), + filepath.Join("/usr/X11R6/lib64", "modules", "drivers"), + filepath.Join("/usr/X11R6/lib64", "modules", "extensions"), + filepath.Join("/usr/X11R6/lib64", "modules/updates", "drivers"), + filepath.Join("/usr/X11R6/lib64", "modules/updates", "extensions"), + ) +} + +type drmDevicesByPath struct { + None + logger logger.Interface + nvidiaCDIHookPath string + devRoot string + devicesFrom Discover +} + +// newCreateDRMByPathSymlinks creates a discoverer for a hook to create the by-path symlinks for DRM devices discovered by the specified devices discoverer +func newCreateDRMByPathSymlinks(logger logger.Interface, devices Discover, devRoot string, nvidiaCDIHookPath string) Discover { + d := drmDevicesByPath{ + logger: logger, + nvidiaCDIHookPath: nvidiaCDIHookPath, + devRoot: devRoot, + devicesFrom: devices, + } + + return &d +} + +// Hooks returns a hook to create the symlinks from the required CSV files +func (d drmDevicesByPath) Hooks() ([]Hook, error) { + devices, err := d.devicesFrom.Devices() + if err != nil { + return nil, fmt.Errorf("failed to discover devices for by-path symlinks: %v", err) + } + if len(devices) == 0 { + return nil, nil + } + links, err := d.getSpecificLinkArgs(devices) + if err != nil { + return nil, fmt.Errorf("failed to determine specific links: %v", err) + } + if len(links) == 0 { + return nil, nil + } + + var args []string + for _, l := range links { + args = append(args, "--link", l) + } + + hook := CreateNvidiaCDIHook( + d.nvidiaCDIHookPath, + "create-symlinks", + args..., + ) + + return []Hook{hook}, nil +} + +// getSpecificLinkArgs returns the required specific links that need to be created +func (d drmDevicesByPath) getSpecificLinkArgs(devices []Device) ([]string, error) { + selectedDevices := make(map[string]bool) + for _, d := range devices { + selectedDevices[filepath.Base(d.HostPath)] = true + } + + linkLocator := lookup.NewFileLocator( + lookup.WithLogger(d.logger), + lookup.WithRoot(d.devRoot), + ) + candidates, err := linkLocator.Locate("/dev/dri/by-path/pci-*-*") + if err != nil { + d.logger.Warningf("Failed to locate by-path links: %v; ignoring", err) + return nil, nil + } + + var links []string + for _, c := range candidates { + device, err := os.Readlink(c) + if err != nil { + d.logger.Warningf("Failed to evaluate symlink %v; ignoring", c) + continue + } + + if selectedDevices[filepath.Base(device)] { + d.logger.Debugf("adding device symlink %v -> %v", c, device) + links = append(links, fmt.Sprintf("%v::%v", device, c)) + } + } + + return links, nil +} + +// newDRMDeviceDiscoverer creates a discoverer for the DRM devices associated with the requested devices. +func newDRMDeviceDiscoverer(logger logger.Interface, devices image.VisibleDevices, devRoot string) (Discover, error) { + allDevices := NewCharDeviceDiscoverer( + logger, + devRoot, + []string{ + "/dev/dri/card*", + "/dev/dri/renderD*", + }, + ) + + filter, err := newDRMDeviceFilter(devices, devRoot) + if err != nil { + return nil, fmt.Errorf("failed to construct DRM device filter: %v", err) + } + + // We return a discoverer that applies the DRM device filter created above to all discovered DRM device nodes. + d := newFilteredDiscoverer( + logger, + allDevices, + filter, + ) + + return d, err +} + +// newDRMDeviceFilter creates a filter that matches DRM devices nodes for the visible devices. +func newDRMDeviceFilter(devices image.VisibleDevices, devRoot string) (Filter, error) { + gpuInformationPaths, err := proc.GetInformationFilePaths(devRoot) + if err != nil { + return nil, fmt.Errorf("failed to read GPU information: %v", err) + } + + var selectedBusIds []string + for _, f := range gpuInformationPaths { + info, err := proc.ParseGPUInformationFile(f) + if err != nil { + return nil, fmt.Errorf("failed to parse %v: %v", f, err) + } + uuid := info[proc.GPUInfoGPUUUID] + busID := info[proc.GPUInfoBusLocation] + minor := info[proc.GPUInfoDeviceMinor] + + if devices.Has(minor) || devices.Has(uuid) || devices.Has(busID) { + selectedBusIds = append(selectedBusIds, busID) + } + } + + filter := make(selectDeviceByPath) + for _, busID := range selectedBusIds { + drmDeviceNodes, err := drm.GetDeviceNodesByBusID(busID) + if err != nil { + return nil, fmt.Errorf("failed to determine DRM devices for %v: %v", busID, err) + } + for _, drmDeviceNode := range drmDeviceNodes { + filter[drmDeviceNode] = true + } + } + + return filter, nil +} + +// selectDeviceByPath is a filter that allows devices to be selected by the path +type selectDeviceByPath map[string]bool + +var _ Filter = (*selectDeviceByPath)(nil) + +// DeviceIsSelected determines whether the device's path has been selected +func (s selectDeviceByPath) DeviceIsSelected(device Device) bool { + return s[device.Path] +} + +// MountIsSelected is always true +func (s selectDeviceByPath) MountIsSelected(Mount) bool { + return true +} + +// HookIsSelected is always true +func (s selectDeviceByPath) HookIsSelected(Hook) bool { + return true +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/hooks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/hooks.go new file mode 100644 index 00000000..03a57434 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/hooks.go @@ -0,0 +1,82 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "fmt" + "path/filepath" + + "tags.cncf.io/container-device-interface/pkg/cdi" +) + +var _ Discover = (*Hook)(nil) + +// Devices returns an empty list of devices for a Hook discoverer. +func (h Hook) Devices() ([]Device, error) { + return nil, nil +} + +// Mounts returns an empty list of mounts for a Hook discoverer. +func (h Hook) Mounts() ([]Mount, error) { + return nil, nil +} + +// Hooks allows the Hook type to also implement the Discoverer interface. +// It returns a single hook +func (h Hook) Hooks() ([]Hook, error) { + return []Hook{h}, nil +} + +// CreateCreateSymlinkHook creates a hook which creates a symlink from link -> target. +func CreateCreateSymlinkHook(nvidiaCDIHookPath string, links []string) Discover { + if len(links) == 0 { + return None{} + } + + var args []string + for _, link := range links { + args = append(args, "--link", link) + } + return CreateNvidiaCDIHook( + nvidiaCDIHookPath, + "create-symlinks", + args..., + ) +} + +// CreateNvidiaCDIHook creates a hook which invokes the NVIDIA Container CLI hook subcommand. +func CreateNvidiaCDIHook(nvidiaCDIHookPath string, hookName string, additionalArgs ...string) Hook { + return cdiHook(nvidiaCDIHookPath).Create(hookName, additionalArgs...) +} + +type cdiHook string + +func (c cdiHook) Create(name string, args ...string) Hook { + return Hook{ + Lifecycle: cdi.CreateContainerHook, + Path: string(c), + Args: append(c.requiredArgs(name), args...), + Env: []string{fmt.Sprintf("NVIDIA_CTK_DEBUG=%v", false)}, + } +} +func (c cdiHook) requiredArgs(name string) []string { + base := filepath.Base(string(c)) + if base == "nvidia-ctk" { + return []string{base, "hook", name} + } + return []string{base, name} +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ipc.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ipc.go new file mode 100644 index 00000000..f636290f --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ipc.go @@ -0,0 +1,78 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +type ipcMounts mounts + +// NewIPCDiscoverer creats a discoverer for NVIDIA IPC sockets. +func NewIPCDiscoverer(logger logger.Interface, driverRoot string) (Discover, error) { + sockets := newMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithRoot(driverRoot), + lookup.WithSearchPaths("/run", "/var/run"), + lookup.WithCount(1), + ), + driverRoot, + []string{ + "/nvidia-persistenced/socket", + "/nvidia-fabricmanager/socket", + }, + ) + + mps := newMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithRoot(driverRoot), + lookup.WithCount(1), + ), + driverRoot, + []string{ + "/tmp/nvidia-mps", + }, + ) + + d := Merge( + (*ipcMounts)(sockets), + (*ipcMounts)(mps), + ) + return d, nil +} + +// Mounts returns the discovered mounts with "noexec" added to the mount options. +func (d *ipcMounts) Mounts() ([]Mount, error) { + mounts, err := (*mounts)(d).Mounts() + if err != nil { + return nil, err + } + + var modifiedMounts []Mount + for _, m := range mounts { + mount := m + mount.Options = append(mount.Options, "noexec") + modifiedMounts = append(modifiedMounts, mount) + } + + return modifiedMounts, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ldconfig.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ldconfig.go new file mode 100644 index 00000000..b81b9be5 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/ldconfig.go @@ -0,0 +1,128 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +// NewLDCacheUpdateHook creates a discoverer that updates the ldcache for the specified mounts. A logger can also be specified +func NewLDCacheUpdateHook(logger logger.Interface, mounts Discover, nvidiaCDIHookPath, ldconfigPath string) (Discover, error) { + d := ldconfig{ + logger: logger, + nvidiaCDIHookPath: nvidiaCDIHookPath, + ldconfigPath: ldconfigPath, + mountsFrom: mounts, + } + + return &d, nil +} + +type ldconfig struct { + None + logger logger.Interface + nvidiaCDIHookPath string + ldconfigPath string + mountsFrom Discover +} + +// Hooks checks the required mounts for libraries and returns a hook to update the LDcache for the discovered paths. +func (d ldconfig) Hooks() ([]Hook, error) { + mounts, err := d.mountsFrom.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to discover mounts for ldcache update: %v", err) + } + h := CreateLDCacheUpdateHook( + d.nvidiaCDIHookPath, + d.ldconfigPath, + getLibraryPaths(mounts), + ) + return []Hook{h}, nil +} + +// CreateLDCacheUpdateHook locates the NVIDIA Container Toolkit CLI and creates a hook for updating the LD Cache +func CreateLDCacheUpdateHook(executable string, ldconfig string, libraries []string) Hook { + var args []string + + if ldconfig != "" { + args = append(args, "--ldconfig-path", ldconfig) + } + + for _, f := range uniqueFolders(libraries) { + args = append(args, "--folder", f) + } + + hook := CreateNvidiaCDIHook( + executable, + "update-ldcache", + args..., + ) + + return hook +} + +// getLibraryPaths extracts the library dirs from the specified mounts +func getLibraryPaths(mounts []Mount) []string { + var paths []string + for _, m := range mounts { + if !isLibName(m.Path) { + continue + } + paths = append(paths, m.Path) + } + return paths +} + +// isLibName checks if the specified filename is a library (i.e. ends in `.so*`) +func isLibName(filename string) bool { + base := filepath.Base(filename) + + isLib, err := filepath.Match("lib?*.so*", base) + if !isLib || err != nil { + return false + } + + parts := strings.Split(base, ".so") + if len(parts) == 1 { + return true + } + + return parts[len(parts)-1] == "" || strings.HasPrefix(parts[len(parts)-1], ".") +} + +// uniqueFolders returns the unique set of folders for the specified files +func uniqueFolders(libraries []string) []string { + var paths []string + checked := make(map[string]bool) + + for _, l := range libraries { + dir := filepath.Dir(l) + if dir == "" { + continue + } + if checked[dir] { + continue + } + checked[dir] = true + paths = append(paths, dir) + } + return paths +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/list.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/list.go new file mode 100644 index 00000000..fb6e3215 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/list.go @@ -0,0 +1,84 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package discover + +import "fmt" + +// list is a discoverer that contains a list of Discoverers. The output of the +// Mounts functions is the concatenation of the output for each of the +// elements in the list. +type list []Discover + +var _ Discover = (*list)(nil) + +// Merge creates a discoverer that is the composite of a list of discoverers. +func Merge(discoverers ...Discover) Discover { + var l list + for _, d := range discoverers { + if d == nil { + continue + } + l = append(l, d) + } + + return l +} + +// Devices returns all devices from the included discoverers +func (d list) Devices() ([]Device, error) { + var allDevices []Device + + for i, di := range d { + devices, err := di.Devices() + if err != nil { + return nil, fmt.Errorf("error discovering devices for discoverer %v: %v", i, err) + } + allDevices = append(allDevices, devices...) + } + + return allDevices, nil +} + +// Mounts returns all mounts from the included discoverers +func (d list) Mounts() ([]Mount, error) { + var allMounts []Mount + + for i, di := range d { + mounts, err := di.Mounts() + if err != nil { + return nil, fmt.Errorf("error discovering mounts for discoverer %v: %v", i, err) + } + allMounts = append(allMounts, mounts...) + } + + return allMounts, nil +} + +// Hooks returns all Hooks from the included discoverers +func (d list) Hooks() ([]Hook, error) { + var allHooks []Hook + + for i, di := range d { + hooks, err := di.Hooks() + if err != nil { + return nil, fmt.Errorf("error discovering hooks for discoverer %v: %v", i, err) + } + allHooks = append(allHooks, hooks...) + } + + return allHooks, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mofed.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mofed.go new file mode 100644 index 00000000..b9ff4153 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mofed.go @@ -0,0 +1,33 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + +// NewMOFEDDiscoverer creates a discoverer for MOFED devices. +func NewMOFEDDiscoverer(logger logger.Interface, devRoot string) (Discover, error) { + devices := NewCharDeviceDiscoverer( + logger, + devRoot, + []string{ + "/dev/infiniband/uverbs*", + "/dev/infiniband/rdma_cm", + }, + ) + + return devices, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts-to-container-path.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts-to-container-path.go new file mode 100644 index 00000000..602f153d --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts-to-container-path.go @@ -0,0 +1,81 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +// mountsToContainerPath defines a Discoverer for a required set of mounts. +// When these are discovered by a locator the specified container root is used +// to construct the container path for the mount returned. +type mountsToContainerPath struct { + None + logger logger.Interface + locator lookup.Locator + required []string + containerRoot string +} + +func (d *mountsToContainerPath) Mounts() ([]Mount, error) { + seen := make(map[string]bool) + var mounts []Mount + for _, target := range d.required { + if strings.Contains(target, "*") { + // TODO: We could relax this condition. + return nil, fmt.Errorf("wildcard patterns are not supported: %s", target) + } + candidates, err := d.locator.Locate(target) + if err != nil { + d.logger.Warningf("Could not locate %v: %v", target, err) + continue + } + if len(candidates) == 0 { + d.logger.Warningf("Missing %v", target) + continue + } + hostPath := candidates[0] + if seen[hostPath] { + d.logger.Debugf("Skipping duplicate mount %v", hostPath) + continue + } + seen[hostPath] = true + d.logger.Debugf("Located %v as %v", target, hostPath) + + containerPath := filepath.Join(d.containerRoot, target) + d.logger.Infof("Selecting %v as %v", hostPath, containerPath) + + mount := Mount{ + HostPath: hostPath, + Path: containerPath, + Options: []string{ + "ro", + "nosuid", + "nodev", + "bind", + }, + } + mounts = append(mounts, mount) + } + + return mounts, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts.go new file mode 100644 index 00000000..cafa2610 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/mounts.go @@ -0,0 +1,125 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package discover + +import ( + "fmt" + "path/filepath" + "strings" + "sync" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +// mounts is a generic discoverer for Mounts. It is customized by specifying the +// required entities as a list and a Locator that is used to find the target mounts +// based on the entry in the list. +type mounts struct { + None + logger logger.Interface + lookup lookup.Locator + root string + required []string + sync.Mutex + cache []Mount +} + +var _ Discover = (*mounts)(nil) + +// NewMounts creates a discoverer for the required mounts using the specified locator. +func NewMounts(logger logger.Interface, lookup lookup.Locator, root string, required []string) Discover { + return newMounts(logger, lookup, root, required) +} + +// newMounts creates a discoverer for the required mounts using the specified locator. +func newMounts(logger logger.Interface, lookup lookup.Locator, root string, required []string) *mounts { + return &mounts{ + logger: logger, + lookup: lookup, + root: filepath.Join("/", root), + required: required, + } +} + +func (d *mounts) Mounts() ([]Mount, error) { + if d.lookup == nil { + return nil, fmt.Errorf("no lookup defined") + } + + if d.cache != nil { + d.logger.Debugf("returning cached mounts") + return d.cache, nil + } + + d.Lock() + defer d.Unlock() + + var mounts []Mount + seen := make(map[string]bool) + for _, candidate := range d.required { + d.logger.Debugf("Locating %v", candidate) + located, err := d.lookup.Locate(candidate) + if err != nil { + d.logger.Warningf("Could not locate %v: %v", candidate, err) + continue + } + if len(located) == 0 { + d.logger.Warningf("Missing %v", candidate) + continue + } + d.logger.Debugf("Located %v as %v", candidate, located) + for _, p := range located { + if seen[p] { + d.logger.Debugf("Skipping duplicate mount %v", p) + continue + } + + r := d.relativeTo(p) + if r == "" { + r = p + } + + d.logger.Infof("Selecting %v as %v", p, r) + mount := Mount{ + HostPath: p, + Path: r, + Options: []string{ + "ro", + "nosuid", + "nodev", + "bind", + }, + } + mounts = append(mounts, mount) + seen[p] = true + } + } + + d.cache = mounts + + return d.cache, nil +} + +// relativeTo returns the path relative to the root for the file locator +func (d *mounts) relativeTo(path string) string { + if d.root == "/" { + return path + } + + return strings.TrimPrefix(path, d.root) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/none.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/none.go new file mode 100644 index 00000000..554e7eab --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/none.go @@ -0,0 +1,38 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package discover + +// None is a null discoverer that returns an empty list of devices and +// mounts. +type None struct{} + +var _ Discover = (*None)(nil) + +// Devices returns an empty list of devices +func (e None) Devices() ([]Device, error) { + return nil, nil +} + +// Mounts returns an empty list of mounts +func (e None) Mounts() ([]Mount, error) { + return nil, nil +} + +// Hooks returns an empty list of hooks +func (e None) Hooks() ([]Hook, error) { + return nil, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/nvswitch.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/nvswitch.go new file mode 100644 index 00000000..fb956d11 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/nvswitch.go @@ -0,0 +1,33 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + +// NewNvSwitchDiscoverer creates a discoverer for NVSWITCH devices. +func NewNvSwitchDiscoverer(logger logger.Interface, devRoot string) (Discover, error) { + devices := NewCharDeviceDiscoverer( + logger, + devRoot, + []string{ + "/dev/nvidia-nvswitchctl", + "/dev/nvidia-nvswitch*", + }, + ) + + return devices, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/symlinks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/symlinks.go new file mode 100644 index 00000000..0119de0d --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/discover/symlinks.go @@ -0,0 +1,108 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package discover + +import ( + "fmt" + "path/filepath" +) + +type additionalSymlinks struct { + Discover + version string + nvidiaCDIHookPath string +} + +// WithDriverDotSoSymlinks decorates the provided discoverer. +// A hook is added that checks for specific driver symlinks that need to be created. +func WithDriverDotSoSymlinks(mounts Discover, version string, nvidiaCDIHookPath string) Discover { + if version == "" { + version = "*.*" + } + return &additionalSymlinks{ + Discover: mounts, + nvidiaCDIHookPath: nvidiaCDIHookPath, + version: version, + } +} + +// Hooks returns a hook to create the additional symlinks based on the mounts. +func (d *additionalSymlinks) Hooks() ([]Hook, error) { + mounts, err := d.Discover.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to get library mounts: %v", err) + } + hooks, err := d.Discover.Hooks() + if err != nil { + return nil, fmt.Errorf("failed to get hooks: %v", err) + } + + var links []string + processedPaths := make(map[string]bool) + processedLinks := make(map[string]bool) + for _, mount := range mounts { + if processedPaths[mount.Path] { + continue + } + processedPaths[mount.Path] = true + + for _, link := range d.getLinksForMount(mount.Path) { + if processedLinks[link] { + continue + } + processedLinks[link] = true + links = append(links, link) + } + } + + if len(links) == 0 { + return hooks, nil + } + + hook := CreateCreateSymlinkHook(d.nvidiaCDIHookPath, links).(Hook) + return append(hooks, hook), nil +} + +// getLinksForMount maps the path to created links if any. +func (d additionalSymlinks) getLinksForMount(path string) []string { + dir, filename := filepath.Split(path) + switch { + case d.isDriverLibrary("libcuda.so", filename): + // XXX Many applications wrongly assume that libcuda.so exists (e.g. with dlopen). + // create libcuda.so -> libcuda.so.1 symlink + link := fmt.Sprintf("%s::%s", "libcuda.so.1", filepath.Join(dir, "libcuda.so")) + return []string{link} + case d.isDriverLibrary("libGLX_nvidia.so", filename): + // XXX GLVND requires this symlink for indirect GLX support. + // create libGLX_indirect.so.0 -> libGLX_nvidia.so.VERSION symlink + link := fmt.Sprintf("%s::%s", filename, filepath.Join(dir, "libGLX_indirect.so.0")) + return []string{link} + case d.isDriverLibrary("libnvidia-opticalflow.so", filename): + // XXX Fix missing symlink for libnvidia-opticalflow.so. + // create libnvidia-opticalflow.so -> libnvidia-opticalflow.so.1 symlink + link := fmt.Sprintf("%s::%s", "libnvidia-opticalflow.so.1", filepath.Join(dir, "libnvidia-opticalflow.so")) + return []string{link} + } + return nil +} + +// isDriverLibrary checks whether the specified filename is a specific driver library. +func (d additionalSymlinks) isDriverLibrary(libraryName string, filename string) bool { + pattern := libraryName + "." + d.version + match, _ := filepath.Match(pattern, filename) + return match +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/api.go new file mode 100644 index 00000000..ed70bb4f --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/api.go @@ -0,0 +1,55 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dxcore + +// dxcore stores a reference the dxcore dynamic library +var dxcore *context + +// Init initializes the dxcore dynamic library +func Init() error { + c, err := initContext() + if err != nil { + return err + } + dxcore = c + return nil +} + +// Shutdown closes the dxcore dynamic library +func Shutdown() error { + if dxcore != nil && dxcore.initialized != 0 { + dxcore.deinitContext() + } + return nil +} + +// GetDriverStorePaths returns the list of driver store paths +func GetDriverStorePaths() []string { + var paths []string + selected := make(map[string]bool) + + for i := 0; i < dxcore.getAdapterCount(); i++ { + path := dxcore.getAdapter(i).getDriverStorePath() + if selected[path] { + continue + } + selected[path] = true + paths = append(paths, path) + } + + return paths +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.c b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.c new file mode 100644 index 00000000..a7c9a6b7 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.c @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + */ + +#include +#include + +#include "dxcore.h" + +// We define log_write as an empty macro to allow dxcore to remain unchanged. +#define log_write(...) + +// We define the following macros to allow dxcore to remain largely unchanged. +#define log_info(msg) log_write('I', __FILE__, __LINE__, msg) +#define log_warn(msg) log_write('W', __FILE__, __LINE__, msg) +#define log_err(msg) log_write('E', __FILE__, __LINE__, msg) +#define log_infof(fmt, ...) log_write('I', __FILE__, __LINE__, fmt, __VA_ARGS__) +#define log_warnf(fmt, ...) log_write('W', __FILE__, __LINE__, fmt, __VA_ARGS__) +#define log_errf(fmt, ...) log_write('E', __FILE__, __LINE__, fmt, __VA_ARGS__) + + +#define DXCORE_MAX_PATH 260 + +/* + * List of components we expect to find in the driver store that we need to mount + */ +static const char * const dxcore_nvidia_driver_store_components[] = { + "libcuda.so.1.1", /* Core library for cuda support */ + "libcuda_loader.so", /* Core library for cuda support on WSL */ + "libnvidia-ptxjitcompiler.so.1", /* Core library for PTX Jit support */ + "libnvidia-ml.so.1", /* Core library for nvml */ + "libnvidia-ml_loader.so", /* Core library for nvml on WSL */ + "nvidia-smi", /* nvidia-smi binary*/ + "nvcubins.bin", /* Binary containing GPU code for cuda */ +}; + + +/* + * List of functions and structures we need to communicate with libdxcore. + * Documentation on these functions can be found on docs.microsoft.com in d3dkmthk. + */ + +struct dxcore_enumAdapters2; +struct dxcore_enumAdapters3; +struct dxcore_queryAdapterInfo; + +typedef int(*pfnDxcoreEnumAdapters2)(struct dxcore_enumAdapters2* pParams); +typedef int(*pfnDxcoreEnumAdapters3)(struct dxcore_enumAdapters3* pParams); +typedef int(*pfnDxcoreQueryAdapterInfo)(struct dxcore_queryAdapterInfo* pParams); + +struct dxcore_lib { + void* hDxcoreLib; + pfnDxcoreEnumAdapters2 pDxcoreEnumAdapters2; + pfnDxcoreEnumAdapters3 pDxcoreEnumAdapters3; + pfnDxcoreQueryAdapterInfo pDxcoreQueryAdapterInfo; +}; + +struct dxcore_adapterInfo +{ + unsigned int hAdapter; + struct dxcore_luid AdapterLuid; + unsigned int NumOfSources; + unsigned int bPresentMoveRegionsPreferred; +}; + +struct dxcore_enumAdapters2 +{ + unsigned int NumAdapters; + struct dxcore_adapterInfo *pAdapters; +}; + +#define ENUMADAPTER3_FILTER_COMPUTE_ONLY (0x0000000000000001) + +struct dxcore_enumAdapters3 +{ + unsigned long long Filter; + unsigned int NumAdapters; + struct dxcore_adapterInfo *pAdapters; +}; + +enum dxcore_kmtqueryAdapterInfoType +{ + DXCORE_QUERYDRIVERVERSION = 13, + DXCORE_QUERYREGISTRY = 48, +}; + +enum dxcore_queryregistry_type { + DXCORE_QUERYREGISTRY_DRIVERSTOREPATH = 2, + DXCORE_QUERYREGISTRY_DRIVERIMAGEPATH = 3, +}; + +enum dxcore_queryregistry_status { + DXCORE_QUERYREGISTRY_STATUS_SUCCESS = 0, + DXCORE_QUERYREGISTRY_STATUS_BUFFER_OVERFLOW = 1, + DXCORE_QUERYREGISTRY_STATUS_FAIL = 2, +}; + +struct dxcore_queryregistry_info { + enum dxcore_queryregistry_type QueryType; + unsigned int QueryFlags; + wchar_t ValueName[DXCORE_MAX_PATH]; + unsigned int ValueType; + unsigned int PhysicalAdapterIndex; + unsigned int OutputValueSize; + enum dxcore_queryregistry_status Status; + union { + unsigned long long OutputQword; + wchar_t Output; + }; +}; + +struct dxcore_queryAdapterInfo +{ + unsigned int hAdapter; + enum dxcore_kmtqueryAdapterInfoType Type; + void *pPrivateDriverData; + unsigned int PrivateDriverDataSize; +}; + +static int dxcore_query_adapter_info_helper(struct dxcore_lib* pLib, + unsigned int hAdapter, + enum dxcore_kmtqueryAdapterInfoType type, + void* pPrivateDriverDate, + unsigned int privateDriverDataSize) +{ + struct dxcore_queryAdapterInfo queryAdapterInfo = { 0 }; + + queryAdapterInfo.hAdapter = hAdapter; + queryAdapterInfo.Type = type; + queryAdapterInfo.pPrivateDriverData = pPrivateDriverDate; + queryAdapterInfo.PrivateDriverDataSize = privateDriverDataSize; + + return pLib->pDxcoreQueryAdapterInfo(&queryAdapterInfo); +} + +static int dxcore_query_adapter_wddm_version(struct dxcore_lib* pLib, unsigned int hAdapter, unsigned int* version) +{ + return dxcore_query_adapter_info_helper(pLib, + hAdapter, + DXCORE_QUERYDRIVERVERSION, + (void*)version, + sizeof(*version)); +} + +static int dxcore_query_adapter_driverstore(struct dxcore_lib* pLib, unsigned int hAdapter, char** ppDriverStorePath) +{ + struct dxcore_queryregistry_info params = {0}; + struct dxcore_queryregistry_info* pValue = NULL; + wchar_t* pOutput; + size_t outputSizeInBytes; + size_t outputSize; + + params.QueryType = DXCORE_QUERYREGISTRY_DRIVERSTOREPATH; + + if (dxcore_query_adapter_info_helper(pLib, + hAdapter, + DXCORE_QUERYREGISTRY, + (void*)¶ms, + sizeof(params))) + { + log_err("Failed to query driver store path size for the WDDM Adapter"); + return (-1); + } + + if (params.OutputValueSize > DXCORE_MAX_PATH * sizeof(wchar_t)) { + log_err("The driver store path size returned by dxcore is not valid"); + return (-1); + } + + outputSizeInBytes = (size_t)params.OutputValueSize; + outputSize = outputSizeInBytes / sizeof(wchar_t); + + pValue = calloc(sizeof(struct dxcore_queryregistry_info) + outputSizeInBytes + sizeof(wchar_t), 1); + if (!pValue) { + log_err("Out of memory while allocating temp buffer to query adapter info"); + return (-1); + } + + pValue->QueryType = DXCORE_QUERYREGISTRY_DRIVERSTOREPATH; + pValue->OutputValueSize = (unsigned int)outputSizeInBytes; + + if (dxcore_query_adapter_info_helper(pLib, + hAdapter, + DXCORE_QUERYREGISTRY, + (void*)pValue, + (unsigned int)(sizeof(struct dxcore_queryregistry_info) + outputSizeInBytes))) + { + log_err("Failed to query driver store path data for the WDDM Adapter"); + free(pValue); + return (-1); + } + pOutput = (wchar_t*)(&pValue->Output); + + // Make sure no matter what happened the wchar_t string is null terminated + pOutput[outputSize] = L'\0'; + + // Convert the output into a regular c string + *ppDriverStorePath = (char*)calloc(outputSize + 1, sizeof(char)); + if (!*ppDriverStorePath) { + log_err("Out of memory while allocating the buffer for the driver store path"); + free(pValue); + return (-1); + } + wcstombs(*ppDriverStorePath, pOutput, outputSize); + + free(pValue); + + return 0; +} + +static void dxcore_add_adapter(struct dxcore_context* pCtx, struct dxcore_lib* pLib, struct dxcore_adapterInfo *pAdapterInfo) +{ + unsigned int wddmVersion = 0; + char* driverStorePath = NULL; + + log_infof("Creating a new WDDM Adapter for hAdapter:%x luid:%llx", pAdapterInfo->hAdapter, *((unsigned long long*)&pAdapterInfo->AdapterLuid)); + + if (dxcore_query_adapter_wddm_version(pLib, pAdapterInfo->hAdapter, &wddmVersion)) { + log_err("Failed to query the WDDM version for the specified adapter. Skipping it."); + return; + } + + if (wddmVersion < 2700) { + log_err("Found a WDDM adapter running a driver with pre-WDDM 2.7 . Skipping it."); + return; + } + + if (dxcore_query_adapter_driverstore(pLib, pAdapterInfo->hAdapter, &driverStorePath)) { + log_err("Failed to query driver store path for the WDDM Adapter . Skipping it."); + return; + } + + // We got all the info we needed. Adding it to the tracking structure. + { + struct dxcore_adapter* newList; + newList = realloc(pCtx->adapterList, sizeof(struct dxcore_adapter) * (pCtx->adapterCount + 1)); + if (!newList) { + log_err("Out of memory when trying to add a new WDDM Adapter to the list of valid adapters"); + free(driverStorePath); + return; + } + + pCtx->adapterList = newList; + + pCtx->adapterList[pCtx->adapterCount].hAdapter = pAdapterInfo->hAdapter; + pCtx->adapterList[pCtx->adapterCount].pDriverStorePath = driverStorePath; + pCtx->adapterList[pCtx->adapterCount].wddmVersion = wddmVersion; + pCtx->adapterCount++; + } + + log_infof("Adding new adapter via dxcore hAdapter:%x luid:%llx wddm version:%d", pAdapterInfo->hAdapter, *((unsigned long long*)&pAdapterInfo->AdapterLuid), wddmVersion); +} + +static int dxcore_enum_adapters3(struct dxcore_context* pCtx, struct dxcore_lib* pLib) +{ + struct dxcore_enumAdapters3 params = {0}; + unsigned int adapterIndex = 0; + + // Include compute-only in addition to display+compute adapters + params.Filter = ENUMADAPTER3_FILTER_COMPUTE_ONLY; + params.NumAdapters = 0; + params.pAdapters = NULL; + + if (pLib->pDxcoreEnumAdapters3(¶ms)) { + log_err("Failed to enumerate adapters via enumAdapers3"); + return 1; + } + + params.pAdapters = malloc(sizeof(struct dxcore_adapterInfo) * params.NumAdapters); + if (pLib->pDxcoreEnumAdapters3(¶ms)) { + free(params.pAdapters); + log_err("Failed to enumerate adapters via enumAdapers3"); + return 1; + } + + for (adapterIndex = 0; adapterIndex < params.NumAdapters; adapterIndex++) { + dxcore_add_adapter(pCtx, pLib, ¶ms.pAdapters[adapterIndex]); + } + + free(params.pAdapters); + return 0; +} + +static int dxcore_enum_adapters2(struct dxcore_context* pCtx, struct dxcore_lib* pLib) +{ + struct dxcore_enumAdapters2 params = {0}; + unsigned int adapterIndex = 0; + + params.NumAdapters = 0; + params.pAdapters = NULL; + + if (pLib->pDxcoreEnumAdapters2(¶ms)) { + log_err("Failed to enumerate adapters via enumAdapters2"); + return 1; + } + + params.pAdapters = malloc(sizeof(struct dxcore_adapterInfo) * params.NumAdapters); + if (pLib->pDxcoreEnumAdapters2(¶ms)) { + free(params.pAdapters); + log_err("Failed to enumerate adapters via enumAdapters2"); + return 1; + } + + for (adapterIndex = 0; adapterIndex < params.NumAdapters; adapterIndex++) { + dxcore_add_adapter(pCtx, pLib, ¶ms.pAdapters[adapterIndex]); + } + + free(params.pAdapters); + return 0; +} + +static void dxcore_enum_adapters(struct dxcore_context* pCtx, struct dxcore_lib* pLib) +{ + int status; + if (pLib->pDxcoreEnumAdapters3) { + status = dxcore_enum_adapters3(pCtx, pLib); + if (status == 0) { + return; + } + } + + // Fall back to EnumAdapters2 if the OS doesn't support EnumAdapters3 + if (pLib->pDxcoreEnumAdapters2) { + status = dxcore_enum_adapters2(pCtx, pLib); + if (status == 0) { + return; + } + } + log_err("Failed to enumerate adapters via dxcore"); +} + +int dxcore_init_context(struct dxcore_context* pCtx) +{ + struct dxcore_lib lib = {0}; + + pCtx->initialized = 0; + pCtx->adapterCount = 0; + pCtx->adapterList = NULL; + + lib.hDxcoreLib = dlopen("libdxcore.so", RTLD_LAZY); + if (!lib.hDxcoreLib) { + goto error; + } + + lib.pDxcoreEnumAdapters2 = (pfnDxcoreEnumAdapters2)dlsym(lib.hDxcoreLib, "D3DKMTEnumAdapters2"); + lib.pDxcoreEnumAdapters3 = (pfnDxcoreEnumAdapters3)dlsym(lib.hDxcoreLib, "D3DKMTEnumAdapters3"); + if (!lib.pDxcoreEnumAdapters2 && !lib.pDxcoreEnumAdapters3) { + log_err("dxcore library is present but the symbols D3DKMTEnumAdapters2 and D3DKMTEnumAdapters3 are missing"); + goto error; + } + + lib.pDxcoreQueryAdapterInfo = (pfnDxcoreQueryAdapterInfo)dlsym(lib.hDxcoreLib, "D3DKMTQueryAdapterInfo"); + if (!lib.pDxcoreQueryAdapterInfo) { + log_err("dxcore library is present but the symbol D3DKMTQueryAdapterInfo is missing"); + goto error; + } + + dxcore_enum_adapters(pCtx, &lib); + + log_info("dxcore layer initialized successfully"); + pCtx->initialized = 1; + + dlclose(lib.hDxcoreLib); + + return 0; + +error: + dxcore_deinit_context(pCtx); + + if (lib.hDxcoreLib) + dlclose(lib.hDxcoreLib); + + return (-1); +} + +static void dxcore_deinit_adapter(struct dxcore_adapter* pAdapter) +{ + if (!pAdapter) + return; + + free(pAdapter->pDriverStorePath); +} + +void dxcore_deinit_context(struct dxcore_context* pCtx) +{ + unsigned int adapterIndex = 0; + + if (!pCtx) + return; + + for (adapterIndex = 0; adapterIndex < pCtx->adapterCount; adapterIndex++) { + dxcore_deinit_adapter(&pCtx->adapterList[adapterIndex]); + } + + free(pCtx->adapterList); + + pCtx->initialized = 0; +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.go new file mode 100644 index 00000000..cbac0141 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.go @@ -0,0 +1,61 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dxcore + +/* +#cgo linux LDFLAGS: -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files +#cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup + +#include +*/ +import "C" +import ( + "fmt" + "unsafe" +) + +type context C.struct_dxcore_context +type adapter C.struct_dxcore_adapter + +// initContext initializes the dxcore context and populates the list of adapters. +func initContext() (*context, error) { + cContext := C.struct_dxcore_context{} + if C.dxcore_init_context(&cContext) != 0 { + return nil, fmt.Errorf("failed to initialize dxcore context") + } + c := (*context)(&cContext) + return c, nil +} + +// deinitContext deinitializes the dxcore context and frees the list of adapters. +func (c context) deinitContext() { + cContext := C.struct_dxcore_context(c) + C.dxcore_deinit_context(&cContext) +} + +func (c context) getAdapterCount() int { + return int(c.adapterCount) +} + +func (c context) getAdapter(index int) adapter { + arrayPointer := (*[1 << 30]C.struct_dxcore_adapter)(unsafe.Pointer(c.adapterList)) + return adapter(arrayPointer[index]) +} + +func (a adapter) getDriverStorePath() string { + return C.GoString(a.pDriverStorePath) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.h b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.h new file mode 100644 index 00000000..9c044fee --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore/dxcore.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. + */ + +#ifndef HEADER_DXCORE_H_ +#define HEADER_DXCORE_H_ + +#define MAX_DXCORE_DRIVERSTORE_LIBRAIRIES (16) + +struct dxcore_luid +{ + unsigned int lowPart; + int highPart; +}; + +struct dxcore_adapter +{ + unsigned int hAdapter; + unsigned int wddmVersion; + char* pDriverStorePath; + unsigned int driverStoreComponentCount; + const char* pDriverStoreComponents[MAX_DXCORE_DRIVERSTORE_LIBRAIRIES]; + struct dxcore_context *pContext; +}; + +struct dxcore_context +{ + unsigned int adapterCount; + struct dxcore_adapter *adapterList; + + int initialized; +}; + + + +int dxcore_init_context(struct dxcore_context* pDxcore_context); +void dxcore_deinit_context(struct dxcore_context* pDxcore_context); + +#endif // HEADER_DXCORE_H_ diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/device.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/device.go new file mode 100644 index 00000000..d04df153 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/device.go @@ -0,0 +1,61 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package edits + +import ( + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" +) + +type device discover.Device + +// toEdits converts a discovered device to CDI Container Edits. +func (d device) toEdits() (*cdi.ContainerEdits, error) { + deviceNode, err := d.toSpec() + if err != nil { + return nil, err + } + + e := cdi.ContainerEdits{ + ContainerEdits: &specs.ContainerEdits{ + DeviceNodes: []*specs.DeviceNode{deviceNode}, + }, + } + return &e, nil +} + +// toSpec converts a discovered Device to a CDI Spec Device. Note +// that missing info is filled in when edits are applied by querying the Device node. +func (d device) toSpec() (*specs.DeviceNode, error) { + // The HostPath field was added in the v0.5.0 CDI specification. + // The cdi package uses strict unmarshalling when loading specs from file causing failures for + // unexpected fields. + // Since the behaviour for HostPath == "" and HostPath == Path are equivalent, we clear HostPath + // if it is equal to Path to ensure compatibility with the widest range of specs. + hostPath := d.HostPath + if hostPath == d.Path { + hostPath = "" + } + s := specs.DeviceNode{ + HostPath: hostPath, + Path: d.Path, + } + + return &s, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/edits.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/edits.go new file mode 100644 index 00000000..029e7885 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/edits.go @@ -0,0 +1,116 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package edits + +import ( + "fmt" + + ociSpecs "github.com/opencontainers/runtime-spec/specs-go" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/oci" +) + +type edits struct { + cdi.ContainerEdits + logger logger.Interface +} + +// NewSpecEdits creates a SpecModifier that defines the required OCI spec edits (as CDI ContainerEdits) from the specified +// discoverer. +func NewSpecEdits(logger logger.Interface, d discover.Discover) (oci.SpecModifier, error) { + c, err := FromDiscoverer(d) + if err != nil { + return nil, fmt.Errorf("error constructing container edits: %v", err) + } + e := edits{ + ContainerEdits: *c, + logger: logger, + } + + return &e, nil +} + +// FromDiscoverer creates CDI container edits for the specified discoverer. +func FromDiscoverer(d discover.Discover) (*cdi.ContainerEdits, error) { + devices, err := d.Devices() + if err != nil { + return nil, fmt.Errorf("failed to discover devices: %v", err) + } + + mounts, err := d.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to discover mounts: %v", err) + } + + hooks, err := d.Hooks() + if err != nil { + return nil, fmt.Errorf("failed to discover hooks: %v", err) + } + + c := NewContainerEdits() + for _, d := range devices { + edits, err := device(d).toEdits() + if err != nil { + return nil, fmt.Errorf("failed to created container edits for device: %v", err) + } + c.Append(edits) + } + + for _, m := range mounts { + c.Append(mount(m).toEdits()) + } + + for _, h := range hooks { + c.Append(hook(h).toEdits()) + } + + return c, nil +} + +// NewContainerEdits is a utility function to create a CDI ContainerEdits struct. +func NewContainerEdits() *cdi.ContainerEdits { + c := cdi.ContainerEdits{ + ContainerEdits: &specs.ContainerEdits{}, + } + return &c +} + +// Modify applies the defined edits to the incoming OCI spec +func (e *edits) Modify(spec *ociSpecs.Spec) error { + if e == nil || e.ContainerEdits.ContainerEdits == nil { + return nil + } + + e.logger.Info("Mounts:") + for _, mount := range e.Mounts { + e.logger.Infof("Mounting %v at %v", mount.HostPath, mount.ContainerPath) + } + e.logger.Infof("Devices:") + for _, device := range e.DeviceNodes { + e.logger.Infof("Injecting %v", device.Path) + } + e.logger.Infof("Hooks:") + for _, hook := range e.Hooks { + e.logger.Infof("Injecting %v %v", hook.Path, hook.Args) + } + + return e.Apply(spec) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/hook.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/hook.go new file mode 100644 index 00000000..919a07ab --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/hook.go @@ -0,0 +1,53 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package edits + +import ( + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" +) + +type hook discover.Hook + +// toEdits converts a discovered hook to CDI Container Edits. +func (d hook) toEdits() *cdi.ContainerEdits { + e := cdi.ContainerEdits{ + ContainerEdits: &specs.ContainerEdits{ + Hooks: []*specs.Hook{d.toSpec()}, + }, + } + return &e +} + +// toSpec converts a discovered Hook to a CDI Spec Hook. Note +// that missing info is filled in when edits are applied by querying the Hook node. +func (d hook) toSpec() *specs.Hook { + env := d.Env + if env == nil { + env = []string{"NVIDIA_CTK_DEBUG=false"} + } + s := specs.Hook{ + HookName: d.Lifecycle, + Path: d.Path, + Args: d.Args, + Env: env, + } + + return &s +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/mount.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/mount.go new file mode 100644 index 00000000..a588ec04 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/edits/mount.go @@ -0,0 +1,48 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package edits + +import ( + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" +) + +type mount discover.Mount + +// toEdits converts a discovered mount to CDI Container Edits. +func (d mount) toEdits() *cdi.ContainerEdits { + e := cdi.ContainerEdits{ + ContainerEdits: &specs.ContainerEdits{ + Mounts: []*specs.Mount{d.toSpec()}, + }, + } + return &e +} + +// toSpec converts a discovered Mount to a CDI Spec Mount. Note +// that missing info is filled in when edits are applied by querying the Mount node. +func (d mount) toSpec() *specs.Mount { + s := specs.Mount{ + HostPath: d.HostPath, + ContainerPath: d.Path, + Options: d.Options, + } + + return &s +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm/drm_devices.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm/drm_devices.go new file mode 100644 index 00000000..3b8204bc --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm/drm_devices.go @@ -0,0 +1,39 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package drm + +import ( + "fmt" + "path/filepath" +) + +// GetDeviceNodesByBusID returns the DRM devices associated with the specified PCI bus ID +func GetDeviceNodesByBusID(busID string) ([]string, error) { + drmRoot := filepath.Join("/sys/bus/pci/devices", busID, "drm") + matches, err := filepath.Glob(fmt.Sprintf("%s/*", drmRoot)) + if err != nil { + return nil, err + } + + var drmDeviceNodes []string + for _, m := range matches { + drmDeviceNode := filepath.Join("/dev/dri", filepath.Base(m)) + drmDeviceNodes = append(drmDeviceNodes, drmDeviceNode) + } + + return drmDeviceNodes, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/proc/information_files.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/proc/information_files.go new file mode 100644 index 00000000..f84b76a6 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/info/proc/information_files.go @@ -0,0 +1,89 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package proc + +import ( + "bufio" + "fmt" + "io" + "os" + "path/filepath" + "strings" +) + +// GPUInfoField represents the field name for information specified in a GPU's information file +type GPUInfoField string + +// The following constants define the fields of interest from the GPU information file +const ( + GPUInfoModel = GPUInfoField("Model") + GPUInfoGPUUUID = GPUInfoField("GPU UUID") + GPUInfoBusLocation = GPUInfoField("Bus Location") + GPUInfoDeviceMinor = GPUInfoField("Device Minor") +) + +// GPUInfo stores the information for a GPU as determined from its associated information file +type GPUInfo map[GPUInfoField]string + +// GetInformationFilePaths returns the list of information files associated with NVIDIA GPUs. +func GetInformationFilePaths(root string) ([]string, error) { + return filepath.Glob(filepath.Join(root, "/proc/driver/nvidia/gpus/*/information")) +} + +// ParseGPUInformationFile parses the specified GPU information file and constructs a GPUInfo structure +func ParseGPUInformationFile(path string) (GPUInfo, error) { + infoFile, err := os.Open(path) + if err != nil { + return nil, fmt.Errorf("failed to open %v: %v", path, err) + } + defer infoFile.Close() + + return gpuInfoFrom(infoFile), nil +} + +// gpuInfoFrom parses a GPUInfo struct from the specified reader +// An information file has the following structure: +// $ cat /proc/driver/nvidia/gpus/0000\:06\:00.0/information +// Model: Tesla V100-SXM2-16GB +// IRQ: 408 +// GPU UUID: GPU-edfee158-11c1-52b8-0517-92f30e7fac88 +// Video BIOS: 88.00.41.00.01 +// Bus Type: PCIe +// DMA Size: 47 bits +// DMA Mask: 0x7fffffffffff +// Bus Location: 0000:06:00.0 +// Device Minor: 0 +// GPU Excluded: No +func gpuInfoFrom(reader io.Reader) GPUInfo { + info := make(GPUInfo) + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + line := scanner.Text() + + parts := strings.SplitN(line, ":", 2) + if len(parts) != 2 { + continue + } + + field := GPUInfoField(parts[0]) + value := strings.TrimSpace(parts[1]) + + info[field] = value + } + + return info +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache.go new file mode 100644 index 00000000..823b0fbd --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache.go @@ -0,0 +1,266 @@ +/* +# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +// Adapted from https://github.com/rai-project/ldcache + +package ldcache + +import ( + "bytes" + "encoding/binary" + "errors" + "os" + "path/filepath" + "syscall" + "unsafe" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +const ldcachePath = "/etc/ld.so.cache" + +const ( + magicString1 = "ld.so-1.7.0" + magicString2 = "glibc-ld.so.cache" + magicVersion = "1.1" +) + +const ( + flagTypeMask = 0x00ff + flagTypeELF = 0x0001 + + flagArchMask = 0xff00 + flagArchI386 = 0x0000 + flagArchX8664 = 0x0300 + flagArchX32 = 0x0800 + flagArchPpc64le = 0x0500 + + // flagArch_ARM_LIBHF is the flag value for 32-bit ARM libs using hard-float. + flagArch_ARM_LIBHF = 0x0900 + // flagArch_AARCH64_LIB64 is the flag value for 64-bit ARM libs. + flagArch_AARCH64_LIB64 = 0x0a00 +) + +var errInvalidCache = errors.New("invalid ld.so.cache file") + +type header1 struct { + Magic [len(magicString1) + 1]byte // include null delimiter + NLibs uint32 +} + +type entry1 struct { + Flags int32 + Key, Value uint32 +} + +type header2 struct { + Magic [len(magicString2)]byte + Version [len(magicVersion)]byte + NLibs uint32 + TableSize uint32 + _ [3]uint32 // unused + _ uint64 // force 8 byte alignment +} + +type entry2 struct { + Flags int32 + Key, Value uint32 + OSVersion uint32 + HWCap uint64 +} + +// LDCache represents the interface for performing lookups into the LDCache +// +//go:generate moq -rm -out ldcache_mock.go . LDCache +type LDCache interface { + List() ([]string, []string) +} + +type ldcache struct { + *bytes.Reader + + data, libs []byte + header header2 + entries []entry2 + + root string + logger logger.Interface +} + +// New creates a new LDCache with the specified logger and root. +func New(logger logger.Interface, root string) (LDCache, error) { + path := filepath.Join(root, ldcachePath) + + logger.Debugf("Opening ld.conf at %v", path) + f, err := os.Open(path) + if err != nil { + return nil, err + } + defer f.Close() + + fi, err := f.Stat() + if err != nil { + return nil, err + } + d, err := syscall.Mmap(int(f.Fd()), 0, int(fi.Size()), + syscall.PROT_READ, syscall.MAP_PRIVATE) + if err != nil { + return nil, err + } + + cache := &ldcache{ + data: d, + Reader: bytes.NewReader(d), + root: root, + logger: logger, + } + return cache, cache.parse() +} + +func (c *ldcache) Close() error { + return syscall.Munmap(c.data) +} + +func (c *ldcache) Magic() string { + return string(c.header.Magic[:]) +} + +func (c *ldcache) Version() string { + return string(c.header.Version[:]) +} + +func strn(b []byte, n int) string { + return string(b[:n]) +} + +func (c *ldcache) parse() error { + var header header1 + + // Check for the old format (< glibc-2.2) + if c.Len() <= int(unsafe.Sizeof(header)) { + return errInvalidCache + } + if strn(c.data, len(magicString1)) == magicString1 { + if err := binary.Read(c, binary.LittleEndian, &header); err != nil { + return err + } + n := int64(header.NLibs) * int64(unsafe.Sizeof(entry1{})) + offset, err := c.Seek(n, 1) // skip old entries + if err != nil { + return err + } + n = (-offset) & int64(unsafe.Alignof(c.header)-1) + _, err = c.Seek(n, 1) // skip padding + if err != nil { + return err + } + } + + c.libs = c.data[c.Size()-int64(c.Len()):] // kv offsets start here + if err := binary.Read(c, binary.LittleEndian, &c.header); err != nil { + return err + } + if c.Magic() != magicString2 || c.Version() != magicVersion { + return errInvalidCache + } + c.entries = make([]entry2, c.header.NLibs) + if err := binary.Read(c, binary.LittleEndian, &c.entries); err != nil { + return err + } + return nil +} + +type entry struct { + libname string + bits int + value string +} + +// getEntries returns the entires of the ldcache in a go-friendly struct. +func (c *ldcache) getEntries() []entry { + var entries []entry + for _, e := range c.entries { + bits := 0 + if ((e.Flags & flagTypeMask) & flagTypeELF) == 0 { + continue + } + switch e.Flags & flagArchMask { + case flagArchX8664: + fallthrough + case flagArch_AARCH64_LIB64: + fallthrough + case flagArchPpc64le: + bits = 64 + case flagArchX32: + fallthrough + case flagArch_ARM_LIBHF: + fallthrough + case flagArchI386: + bits = 32 + default: + continue + } + if e.Key > uint32(len(c.libs)) || e.Value > uint32(len(c.libs)) { + continue + } + lib := bytesToString(c.libs[e.Key:]) + if lib == "" { + c.logger.Debugf("Skipping invalid lib") + continue + } + value := bytesToString(c.libs[e.Value:]) + if value == "" { + c.logger.Debugf("Skipping invalid value for lib %v", lib) + continue + } + e := entry{ + libname: lib, + bits: bits, + value: value, + } + entries = append(entries, e) + } + return entries +} + +// List creates a list of libraries in the ldcache. +// The 32-bit and 64-bit libraries are returned separately. +func (c *ldcache) List() ([]string, []string) { + paths := make(map[int][]string) + processed := make(map[string]bool) + + for _, e := range c.getEntries() { + path := filepath.Join(c.root, e.value) + if processed[path] { + continue + } + paths[e.bits] = append(paths[e.bits], path) + processed[path] = true + } + + return paths[32], paths[64] +} + +// bytesToString converts a byte slice to a string. +// This assumes that the byte slice is null-terminated +func bytesToString(value []byte) string { + n := bytes.IndexByte(value, 0) + if n < 0 { + return "" + } + + return strn(value, n) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache_mock.go new file mode 100644 index 00000000..5aa53235 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache/ldcache_mock.go @@ -0,0 +1,67 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package ldcache + +import ( + "sync" +) + +// Ensure, that LDCacheMock does implement LDCache. +// If this is not the case, regenerate this file with moq. +var _ LDCache = &LDCacheMock{} + +// LDCacheMock is a mock implementation of LDCache. +// +// func TestSomethingThatUsesLDCache(t *testing.T) { +// +// // make and configure a mocked LDCache +// mockedLDCache := &LDCacheMock{ +// ListFunc: func() ([]string, []string) { +// panic("mock out the List method") +// }, +// } +// +// // use mockedLDCache in code that requires LDCache +// // and then make assertions. +// +// } +type LDCacheMock struct { + // ListFunc mocks the List method. + ListFunc func() ([]string, []string) + + // calls tracks calls to the methods. + calls struct { + // List holds details about calls to the List method. + List []struct { + } + } + lockList sync.RWMutex +} + +// List calls ListFunc. +func (mock *LDCacheMock) List() ([]string, []string) { + if mock.ListFunc == nil { + panic("LDCacheMock.ListFunc: method is nil but LDCache.List was just called") + } + callInfo := struct { + }{} + mock.lockList.Lock() + mock.calls.List = append(mock.calls.List, callInfo) + mock.lockList.Unlock() + return mock.ListFunc() +} + +// ListCalls gets all the calls that were made to List. +// Check the length with: +// +// len(mockedLDCache.ListCalls()) +func (mock *LDCacheMock) ListCalls() []struct { +} { + var calls []struct { + } + mock.lockList.RLock() + calls = mock.calls.List + mock.lockList.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/api.go new file mode 100644 index 00000000..750c64c6 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/api.go @@ -0,0 +1,28 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package logger + +// Interface defines the API for the logger package +type Interface interface { + Debugf(string, ...interface{}) + Errorf(string, ...interface{}) + Info(...interface{}) + Infof(string, ...interface{}) + Warning(...interface{}) + Warningf(string, ...interface{}) + Tracef(string, ...interface{}) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/lib.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/lib.go new file mode 100644 index 00000000..ddb227bf --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/logger/lib.go @@ -0,0 +1,50 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package logger + +import "github.com/sirupsen/logrus" + +// New returns a new logger +func New() Interface { + return logrus.StandardLogger() +} + +// NullLogger is a logger that does nothing +type NullLogger struct{} + +var _ Interface = (*NullLogger)(nil) + +// Debugf is a no-op for the null logger +func (l *NullLogger) Debugf(string, ...interface{}) {} + +// Errorf is a no-op for the null logger +func (l *NullLogger) Errorf(string, ...interface{}) {} + +// Info is a no-op for the null logger +func (l *NullLogger) Info(...interface{}) {} + +// Infof is a no-op for the null logger +func (l *NullLogger) Infof(string, ...interface{}) {} + +// Warning is a no-op for the null logger +func (l *NullLogger) Warning(...interface{}) {} + +// Warningf is a no-op for the null logger +func (l *NullLogger) Warningf(string, ...interface{}) {} + +// Tracef is a no-op for the null logger +func (l *NullLogger) Tracef(string, ...interface{}) {} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda/cuda.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda/cuda.go new file mode 100644 index 00000000..68c4db35 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda/cuda.go @@ -0,0 +1,39 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package cuda + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +type cudaLocator struct { + lookup.Locator +} + +// New creates a new CUDA library locator. +func New(libraries lookup.Locator) lookup.Locator { + c := cudaLocator{ + Locator: libraries, + } + return &c +} + +// Locate returns the path to the libcuda.so.RMVERSION file. +// libcuda.so is prefixed to the specified pattern. +func (l *cudaLocator) Locate(pattern string) ([]string, error) { + return l.Locator.Locate("libcuda.so" + pattern) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/device.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/device.go new file mode 100644 index 00000000..8ec6c4c9 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/device.go @@ -0,0 +1,50 @@ +/** +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import ( + "fmt" + "os" +) + +const ( + devRoot = "/dev" +) + +// NewCharDeviceLocator creates a Locator that can be used to find char devices at the specified root. A logger is +// also specified. +func NewCharDeviceLocator(opts ...Option) Locator { + opts = append(opts, + WithSearchPaths("", devRoot), + WithFilter(assertCharDevice), + ) + return NewFileLocator( + opts..., + ) +} + +// assertCharDevice checks whether the specified path is a char device and returns an error if this is not the case. +func assertCharDevice(filename string) error { + info, err := os.Lstat(filename) + if err != nil { + return fmt.Errorf("error getting info: %v", err) + } + if info.Mode()&os.ModeCharDevice == 0 { + return fmt.Errorf("%v is not a char device", filename) + } + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/dir.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/dir.go new file mode 100644 index 00000000..edf42b56 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/dir.go @@ -0,0 +1,46 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package lookup + +import ( + "fmt" + "os" +) + +// NewDirectoryLocator creates a Locator that can be used to find directories at the specified root. +func NewDirectoryLocator(opts ...Option) Locator { + return NewFileLocator( + append( + opts, + WithFilter(assertDirectory), + )..., + ) +} + +// assertDirectory checks wither the specified path is a directory. +func assertDirectory(filename string) error { + info, err := os.Stat(filename) + if err != nil { + return fmt.Errorf("error getting info for %v: %v", filename, err) + } + + if !info.IsDir() { + return fmt.Errorf("specified path '%v' is not a directory", filename) + } + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/executable.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/executable.go new file mode 100644 index 00000000..b94e850a --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/executable.go @@ -0,0 +1,87 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package lookup + +import ( + "fmt" + "os" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +type executable struct { + file +} + +// NewExecutableLocator creates a locator to fine executable files in the path. A logger can also be specified. +func NewExecutableLocator(logger logger.Interface, root string) Locator { + paths := GetPaths(root) + + return newExecutableLocator(logger, root, paths...) +} + +func newExecutableLocator(logger logger.Interface, root string, paths ...string) *executable { + f := newFileLocator( + WithLogger(logger), + WithRoot(root), + WithSearchPaths(paths...), + WithFilter(assertExecutable), + WithCount(1), + ) + + l := executable{ + file: *f, + } + + return &l +} + +var _ Locator = (*executable)(nil) + +// Locate finds executable files with the specified pattern in the path. +// If a relative or absolute path is specified, the prefix paths are not considered. +func (p executable) Locate(pattern string) ([]string, error) { + // For absolute paths we ensure that it is executable + if strings.Contains(pattern, "/") { + err := assertExecutable(pattern) + if err != nil { + return nil, fmt.Errorf("absolute path %v is not an executable file: %v", pattern, err) + } + return []string{pattern}, nil + } + + return p.file.Locate(pattern) +} + +// assertExecutable checks whether the specified path is an execuable file. +func assertExecutable(filename string) error { + err := assertFile(filename) + if err != nil { + return err + } + info, err := os.Stat(filename) + if err != nil { + return err + } + + if info.Mode()&0111 == 0 { + return fmt.Errorf("specified file '%v' is not executable", filename) + } + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/file.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/file.go new file mode 100644 index 00000000..8f330273 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/file.go @@ -0,0 +1,205 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package lookup + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +// file can be used to locate file (or file-like elements) at a specified set of +// prefixes. The validity of a file is determined by a filter function. +type file struct { + builder + prefixes []string +} + +// builder defines the builder for a file locator. +type builder struct { + logger logger.Interface + root string + searchPaths []string + filter func(string) error + count int + isOptional bool +} + +// Option defines a function for passing builder to the NewFileLocator() call +type Option func(*builder) + +// WithRoot sets the root for the file locator +func WithRoot(root string) Option { + return func(f *builder) { + f.root = root + } +} + +// WithLogger sets the logger for the file locator +func WithLogger(logger logger.Interface) Option { + return func(f *builder) { + f.logger = logger + } +} + +// WithSearchPaths sets the search paths for the file locator. +func WithSearchPaths(paths ...string) Option { + return func(f *builder) { + f.searchPaths = paths + } +} + +// WithFilter sets the filter for the file locator +// The filter is called for each candidate file and candidates that return nil are considered. +func WithFilter(assert func(string) error) Option { + return func(f *builder) { + f.filter = assert + } +} + +// WithCount sets the maximum number of candidates to discover +func WithCount(count int) Option { + return func(f *builder) { + f.count = count + } +} + +// WithOptional sets the optional flag for the file locator +// If the optional flag is set, the locator will not return an error if the file is not found. +func WithOptional(optional bool) Option { + return func(f *builder) { + f.isOptional = optional + } +} + +func newBuilder(opts ...Option) *builder { + o := &builder{} + for _, opt := range opts { + opt(o) + } + if o.logger == nil { + o.logger = logger.New() + } + if o.filter == nil { + o.filter = assertFile + } + return o +} + +func (o builder) build() *file { + f := file{ + builder: o, + // Since the `Locate` implementations rely on the root already being specified we update + // the prefixes to include the root. + prefixes: getSearchPrefixes(o.root, o.searchPaths...), + } + return &f +} + +// NewFileLocator creates a Locator that can be used to find files with the specified builder. +func NewFileLocator(opts ...Option) Locator { + return newFileLocator(opts...) +} + +func newFileLocator(opts ...Option) *file { + return newBuilder(opts...).build() +} + +// getSearchPrefixes generates a list of unique paths to be searched by a file locator. +// +// For each of the unique prefixes

specified, the path

is searched, where is the +// specified root. If no prefixes are specified, is returned as the only search prefix. +// +// Note that an empty root is equivalent to searching relative to the current working directory, and +// if the root filesystem should be searched instead, root should be specified as "/" explicitly. +// +// Also, a prefix of "" forces the root to be included in returned set of paths. This means that if +// the root in addition to another prefix must be searched the function should be called with: +// +// getSearchPrefixes("/root", "", "another/path") +// +// and will result in the search paths []{"/root", "/root/another/path"} being returned. +func getSearchPrefixes(root string, prefixes ...string) []string { + seen := make(map[string]bool) + var uniquePrefixes []string + for _, p := range prefixes { + if seen[p] { + continue + } + seen[p] = true + uniquePrefixes = append(uniquePrefixes, filepath.Join(root, p)) + } + + if len(uniquePrefixes) == 0 { + uniquePrefixes = append(uniquePrefixes, root) + } + + return uniquePrefixes +} + +var _ Locator = (*file)(nil) + +// Locate attempts to find files with names matching the specified pattern. +// All prefixes are searched and any matching candidates are returned. If no matches are found, an error is returned. +func (p file) Locate(pattern string) ([]string, error) { + var filenames []string + + p.logger.Debugf("Locating %q in %v", pattern, p.prefixes) +visit: + for _, prefix := range p.prefixes { + pathPattern := filepath.Join(prefix, pattern) + candidates, err := filepath.Glob(pathPattern) + if err != nil { + p.logger.Debugf("Checking pattern '%v' failed: %v", pathPattern, err) + } + + for _, candidate := range candidates { + p.logger.Debugf("Checking candidate '%v'", candidate) + err := p.filter(candidate) + if err != nil { + p.logger.Debugf("Candidate '%v' does not meet requirements: %v", candidate, err) + continue + } + filenames = append(filenames, candidate) + if p.count > 0 && len(filenames) == p.count { + p.logger.Debugf("Found %d candidates; ignoring further candidates", len(filenames)) + break visit + } + } + } + + if !p.isOptional && len(filenames) == 0 { + return nil, fmt.Errorf("pattern %v %w", pattern, ErrNotFound) + } + return filenames, nil +} + +// assertFile checks whether the specified path is a regular file +func assertFile(filename string) error { + info, err := os.Stat(filename) + if err != nil { + return fmt.Errorf("error getting info for %v: %v", filename, err) + } + + if info.IsDir() { + return fmt.Errorf("specified path '%v' is a directory", filename) + } + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/ldcache.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/ldcache.go new file mode 100644 index 00000000..677dafaa --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/ldcache.go @@ -0,0 +1,118 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import ( + "fmt" + "path/filepath" + "slices" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache" +) + +type ldcacheLocator struct { + *builder + resolvesTo map[string]string +} + +var _ Locator = (*ldcacheLocator)(nil) + +func NewLdcacheLocator(opts ...Option) Locator { + b := newBuilder(opts...) + + cache, err := ldcache.New(b.logger, b.root) + if err != nil { + b.logger.Warningf("Failed to load ldcache: %v", err) + if b.isOptional { + return &null{} + } + return ¬Found{} + } + + chain := NewSymlinkChainLocator(WithOptional(true)) + + resolvesTo := make(map[string]string) + _, libs64 := cache.List() + for _, library := range libs64 { + if _, processed := resolvesTo[library]; processed { + continue + } + candidates, err := chain.Locate(library) + if err != nil { + b.logger.Errorf("error processing library %s from ldcache: %v", library, err) + continue + } + + if len(candidates) == 0 { + resolvesTo[library] = library + continue + } + + // candidates represents a symlink chain. + // The first element represents the start of the chain and the last + // element the final target. + target := candidates[len(candidates)-1] + for _, candidate := range candidates { + resolvesTo[candidate] = target + } + } + + return &ldcacheLocator{ + builder: b, + resolvesTo: resolvesTo, + } +} + +// Locate finds the specified libraryname. +// If the input is a library name, the ldcache is searched otherwise the +// provided path is resolved as a symlink. +func (l ldcacheLocator) Locate(libname string) ([]string, error) { + var matcher func(string, string) bool + + if filepath.IsAbs(libname) { + matcher = func(p string, c string) bool { + m, _ := filepath.Match(filepath.Join(l.root, p), c) + return m + } + } else { + matcher = func(p string, c string) bool { + m, _ := filepath.Match(p, filepath.Base(c)) + return m + } + } + + var matches []string + seen := make(map[string]bool) + for name, target := range l.resolvesTo { + if !matcher(libname, name) { + continue + } + if seen[target] { + continue + } + seen[target] = true + matches = append(matches, target) + } + + slices.Sort(matches) + + if len(matches) == 0 && !l.isOptional { + return nil, fmt.Errorf("%s: %w", libname, ErrNotFound) + } + + return matches, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/library.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/library.go new file mode 100644 index 00000000..6c403d08 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/library.go @@ -0,0 +1,55 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package lookup + +// NewLibraryLocator creates a library locator using the specified options. +func NewLibraryLocator(opts ...Option) Locator { + b := newBuilder(opts...) + + // If search paths are already specified, we return a locator for the specified search paths. + if len(b.searchPaths) > 0 { + return NewSymlinkLocator( + WithLogger(b.logger), + WithSearchPaths(b.searchPaths...), + WithRoot("/"), + ) + } + + opts = append(opts, + WithSearchPaths([]string{ + "/", + "/usr/lib64", + "/usr/lib/x86_64-linux-gnu", + "/usr/lib/aarch64-linux-gnu", + "/usr/lib/x86_64-linux-gnu/nvidia/current", + "/usr/lib/aarch64-linux-gnu/nvidia/current", + "/lib64", + "/lib/x86_64-linux-gnu", + "/lib/aarch64-linux-gnu", + "/lib/x86_64-linux-gnu/nvidia/current", + "/lib/aarch64-linux-gnu/nvidia/current", + }...), + ) + // We construct a symlink locator for expected library locations. + symlinkLocator := NewSymlinkLocator(opts...) + + l := First( + symlinkLocator, + NewLdcacheLocator(opts...), + ) + return l +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator.go new file mode 100644 index 00000000..73ade232 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator.go @@ -0,0 +1,29 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package lookup + +import "errors" + +//go:generate moq -stub -out locator_mock.go . Locator + +// Locator defines the interface for locating files on a system. +type Locator interface { + Locate(string) ([]string, error) +} + +// ErrNotFound indicates that a specified pattern or file could not be found. +var ErrNotFound = errors.New("not found") diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator_mock.go new file mode 100644 index 00000000..10a73aa3 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/locator_mock.go @@ -0,0 +1,78 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package lookup + +import ( + "sync" +) + +// Ensure, that LocatorMock does implement Locator. +// If this is not the case, regenerate this file with moq. +var _ Locator = &LocatorMock{} + +// LocatorMock is a mock implementation of Locator. +// +// func TestSomethingThatUsesLocator(t *testing.T) { +// +// // make and configure a mocked Locator +// mockedLocator := &LocatorMock{ +// LocateFunc: func(s string) ([]string, error) { +// panic("mock out the Locate method") +// }, +// } +// +// // use mockedLocator in code that requires Locator +// // and then make assertions. +// +// } +type LocatorMock struct { + // LocateFunc mocks the Locate method. + LocateFunc func(s string) ([]string, error) + + // calls tracks calls to the methods. + calls struct { + // Locate holds details about calls to the Locate method. + Locate []struct { + // S is the s argument value. + S string + } + } + lockLocate sync.RWMutex +} + +// Locate calls LocateFunc. +func (mock *LocatorMock) Locate(s string) ([]string, error) { + callInfo := struct { + S string + }{ + S: s, + } + mock.lockLocate.Lock() + mock.calls.Locate = append(mock.calls.Locate, callInfo) + mock.lockLocate.Unlock() + if mock.LocateFunc == nil { + var ( + stringsOut []string + errOut error + ) + return stringsOut, errOut + } + return mock.LocateFunc(s) +} + +// LocateCalls gets all the calls that were made to Locate. +// Check the length with: +// +// len(mockedLocator.LocateCalls()) +func (mock *LocatorMock) LocateCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockLocate.RLock() + calls = mock.calls.Locate + mock.lockLocate.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/merge.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/merge.go new file mode 100644 index 00000000..fa20b512 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/merge.go @@ -0,0 +1,53 @@ +/** +# Copyright 2023 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import "errors" + +type first []Locator + +// First returns a locator that returns the first non-empty match +func First(locators ...Locator) Locator { + var f first + for _, l := range locators { + if l == nil { + continue + } + f = append(f, l) + } + return f +} + +// Locate returns the results for the first locator that returns a non-empty non-error result. +func (f first) Locate(pattern string) ([]string, error) { + var allErrors []error + for _, l := range f { + if l == nil { + continue + } + candidates, err := l.Locate(pattern) + if err != nil { + allErrors = append(allErrors, err) + continue + } + if len(candidates) > 0 { + return candidates, nil + } + } + + return nil, errors.Join(allErrors...) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/null.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/null.go new file mode 100644 index 00000000..938e481b --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/null.go @@ -0,0 +1,36 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import "fmt" + +// A null locator always returns an empty response. +type null struct { +} + +// Locate always returns empty for a null locator. +func (l *null) Locate(string) ([]string, error) { + return nil, nil +} + +// A notFound locator always returns an ErrNotFound error. +type notFound struct { +} + +func (l *notFound) Locate(s string) ([]string, error) { + return nil, fmt.Errorf("%s: %w", s, ErrNotFound) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/path.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/path.go new file mode 100644 index 00000000..ce692f8c --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/path.go @@ -0,0 +1,69 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import ( + "os" + "path" + "path/filepath" + "strings" +) + +const ( + envPath = "PATH" +) + +var ( + defaultPATH = []string{"/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"} +) + +// GetPaths returns a list of paths for a specified root. These are constructed from the +// PATH environment variable, a default path list, and the supplied root. +func GetPaths(root string) []string { + dirs := filepath.SplitList(os.Getenv(envPath)) + + inDirs := make(map[string]bool) + for _, d := range dirs { + inDirs[d] = true + } + + // directories from the environment have higher precedence + for _, d := range defaultPATH { + if inDirs[d] { + // We don't add paths that are already included + continue + } + dirs = append(dirs, d) + } + + if root != "" && root != "/" { + rootDirs := []string{} + for _, dir := range dirs { + rootDirs = append(rootDirs, path.Join(root, dir)) + } + // directories with the root prefix have higher precedence + dirs = append(rootDirs, dirs...) + } + + return dirs +} + +// GetPath returns a colon-separated path value that can be used to set the PATH +// environment variable +func GetPath(root string) string { + return strings.Join(GetPaths(root), ":") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/options.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/options.go new file mode 100644 index 00000000..6bffe3d8 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/options.go @@ -0,0 +1,45 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package root + +import "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + +type Option func(*Driver) + +func WithLogger(logger logger.Interface) Option { + return func(d *Driver) { + d.logger = logger + } +} + +func WithDriverRoot(root string) Option { + return func(d *Driver) { + d.Root = root + } +} + +func WithLibrarySearchPaths(paths ...string) Option { + return func(d *Driver) { + d.librarySearchPaths = paths + } +} + +func WithConfigSearchPaths(paths ...string) Option { + return func(d *Driver) { + d.configSearchPaths = paths + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/root.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/root.go new file mode 100644 index 00000000..d0c83701 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root/root.go @@ -0,0 +1,127 @@ +/** +# Copyright 2023 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package root + +import ( + "os" + "path/filepath" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +// Driver represents a filesystem in which a set of drivers or devices is defined. +type Driver struct { + logger logger.Interface + // Root represents the root from the perspective of the driver libraries and binaries. + Root string + // librarySearchPaths specifies explicit search paths for discovering libraries. + librarySearchPaths []string + // configSearchPaths specified explicit search paths for discovering driver config files. + configSearchPaths []string +} + +// New creates a new Driver root using the specified options. +func New(opts ...Option) *Driver { + d := &Driver{} + for _, opt := range opts { + opt(d) + } + if d.logger == nil { + d.logger = logger.New() + } + return d +} + +// RelativeToRoot returns the specified path relative to the driver root. +func (r *Driver) RelativeToRoot(path string) string { + if r.Root == "" || r.Root == "/" { + return path + } + if !filepath.IsAbs(path) { + return path + } + + return strings.TrimPrefix(path, r.Root) +} + +// Files returns a Locator for arbitrary driver files. +func (r *Driver) Files(opts ...lookup.Option) lookup.Locator { + return lookup.NewFileLocator( + append(opts, + lookup.WithLogger(r.logger), + lookup.WithRoot(r.Root), + )..., + ) +} + +// Libraries returns a Locator for driver libraries. +func (r *Driver) Libraries() lookup.Locator { + return lookup.NewLibraryLocator( + lookup.WithLogger(r.logger), + lookup.WithRoot(r.Root), + lookup.WithSearchPaths(normalizeSearchPaths(r.librarySearchPaths...)...), + ) +} + +// Configs returns a locator for driver configs. +// If configSearchPaths is specified, these paths are used as absolute paths, +// otherwise, /etc and /usr/share are searched. +func (r *Driver) Configs() lookup.Locator { + return lookup.NewFileLocator(r.configSearchOptions()...) +} + +func (r *Driver) configSearchOptions() []lookup.Option { + if len(r.configSearchPaths) > 0 { + return []lookup.Option{ + lookup.WithLogger(r.logger), + lookup.WithRoot("/"), + lookup.WithSearchPaths(normalizeSearchPaths(r.configSearchPaths...)...), + } + } + searchPaths := []string{"/etc"} + searchPaths = append(searchPaths, xdgDataDirs()...) + return []lookup.Option{ + lookup.WithLogger(r.logger), + lookup.WithRoot(r.Root), + lookup.WithSearchPaths(searchPaths...), + } +} + +// normalizeSearchPaths takes a list of paths and normalized these. +// Each of the elements in the list is expanded if it is a path list and the +// resultant list is returned. +// This allows, for example, for the contents of `PATH` or `LD_LIBRARY_PATH` to +// be passed as a search path directly. +func normalizeSearchPaths(paths ...string) []string { + var normalized []string + for _, path := range paths { + normalized = append(normalized, filepath.SplitList(path)...) + } + return normalized +} + +// xdgDataDirs finds the paths as specified in the environment variable XDG_DATA_DIRS. +// See https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html. +func xdgDataDirs() []string { + if dirs, exists := os.LookupEnv("XDG_DATA_DIRS"); exists && dirs != "" { + return normalizeSearchPaths(dirs) + } + + return []string{"/usr/local/share", "/usr/share"} +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks.go new file mode 100644 index 00000000..c9bab069 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks.go @@ -0,0 +1,118 @@ +/** +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package lookup + +import ( + "fmt" + "path/filepath" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks" +) + +type symlinkChain struct { + file +} + +type symlink struct { + file +} + +// NewSymlinkChainLocator creats a locator that can be used for locating files through symlinks. +func NewSymlinkChainLocator(opts ...Option) Locator { + f := newFileLocator(opts...) + l := symlinkChain{ + file: *f, + } + + return &l +} + +// NewSymlinkLocator creats a locator that can be used for locating files through symlinks. +func NewSymlinkLocator(opts ...Option) Locator { + f := newFileLocator(opts...) + l := symlink{ + file: *f, + } + + return &l +} + +// Locate finds the specified pattern at the specified root. +// If the file is a symlink, the link is followed and all candidates to the final target are returned. +func (p symlinkChain) Locate(pattern string) ([]string, error) { + candidates, err := p.file.Locate(pattern) + if err != nil { + return nil, err + } + if len(candidates) == 0 { + return candidates, nil + } + + var filenames []string + found := make(map[string]bool) + for len(candidates) > 0 { + candidate := candidates[0] + candidates = candidates[:len(candidates)-1] + if found[candidate] { + continue + } + found[candidate] = true + filenames = append(filenames, candidate) + + target, err := symlinks.Resolve(candidate) + if err != nil { + return nil, fmt.Errorf("error resolving symlink: %v", err) + } + + if !filepath.IsAbs(target) { + target, err = filepath.Abs(filepath.Join(filepath.Dir(candidate), target)) + if err != nil { + return nil, fmt.Errorf("failed to construct absolute path: %v", err) + } + } + + p.logger.Debugf("Resolved link: '%v' => '%v'", candidate, target) + if !found[target] { + candidates = append(candidates, target) + } + } + return filenames, nil +} + +// Locate finds the specified pattern at the specified root. +// If the file is a symlink, the link is resolved and the target returned. +func (p symlink) Locate(pattern string) ([]string, error) { + candidates, err := p.file.Locate(pattern) + if err != nil { + return nil, err + } + + var targets []string + seen := make(map[string]bool) + for _, candidate := range candidates { + target, err := filepath.EvalSymlinks(candidate) + if err != nil { + return nil, fmt.Errorf("failed to resolve link: %w", err) + } + if seen[target] { + continue + } + seen[target] = true + targets = append(targets, target) + } + return targets, err +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks/symlink.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks/symlink.go new file mode 100644 index 00000000..f9151a2f --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks/symlink.go @@ -0,0 +1,50 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package symlinks + +import ( + "fmt" + "os" +) + +// Resolve returns the link target of the specified filename or the filename if it is not a link. +func Resolve(filename string) (string, error) { + info, err := os.Lstat(filename) + if err != nil { + return filename, fmt.Errorf("failed to get file info: %w", err) + } + if info.Mode()&os.ModeSymlink == 0 { + return filename, nil + } + + return os.Readlink(filename) +} + +// ForceCreate creates a specified symlink. +// If a file (or empty directory) exists at the path it is removed. +func ForceCreate(target string, link string) error { + _, err := os.Lstat(link) + if err != nil && !os.IsNotExist(err) { + return fmt.Errorf("failed to get file info: %w", err) + } + if !os.IsNotExist(err) { + if err := os.Remove(link); err != nil { + return fmt.Errorf("failed to remove existing file: %w", err) + } + } + return os.Symlink(target, link) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps/nvcaps.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps/nvcaps.go new file mode 100644 index 00000000..48d98ccf --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps/nvcaps.go @@ -0,0 +1,166 @@ +/* +# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package nvcaps + +import ( + "bufio" + "fmt" + "io" + "log" + "os" + "path/filepath" + "strconv" + "strings" +) + +const ( + nvidiaProcDriverPath = "/proc/driver/nvidia" + nvidiaCapabilitiesPath = nvidiaProcDriverPath + "/capabilities" + + nvcapsProcDriverPath = "/proc/driver/nvidia-caps" + nvcapsMigMinorsPath = nvcapsProcDriverPath + "/mig-minors" + nvcapsDevicePath = "/dev/nvidia-caps" +) + +// MigMinor represents the minor number of a MIG device +type MigMinor int + +// MigCap represents the path to a MIG cap file +type MigCap string + +// MigCaps stores a map of MIG cap file paths to MIG minors +type MigCaps map[MigCap]MigMinor + +// NewGPUInstanceCap creates a MigCap for the specified MIG GPU instance. +// A GPU instance is uniquely defined by the GPU minor number and GI instance ID. +func NewGPUInstanceCap(gpu, gi int) MigCap { + return MigCap(fmt.Sprintf("gpu%d/gi%d/access", gpu, gi)) +} + +// NewComputeInstanceCap creates a MigCap for the specified MIG Compute instance. +// A GPU instance is uniquely defined by the GPU minor number, GI instance ID, and CI instance ID. +func NewComputeInstanceCap(gpu, gi, ci int) MigCap { + return MigCap(fmt.Sprintf("gpu%d/gi%d/ci%d/access", gpu, gi, ci)) +} + +// GetCapDevicePath returns the path to the cap device for the specified cap. +// An error is returned if the cap is invalid. +func (m MigCaps) GetCapDevicePath(cap MigCap) (string, error) { + minor, exists := m[cap] + if !exists { + return "", fmt.Errorf("invalid MIG capability path %v", cap) + } + return minor.DevicePath(), nil +} + +// NewMigCaps creates a MigCaps structure based on the contents of the MIG minors file. +func NewMigCaps() (MigCaps, error) { + // Open nvcapsMigMinorsPath for walking. + // If the nvcapsMigMinorsPath does not exist, then we are not on a MIG + // capable machine, so there is nothing to do. + // The format of this file is discussed in: + // https://docs.nvidia.com/datacenter/tesla/mig-user-guide/index.html#unique_1576522674 + minorsFile, err := os.Open(nvcapsMigMinorsPath) + if os.IsNotExist(err) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("error opening MIG minors file: %v", err) + } + defer minorsFile.Close() + + return processMinorsFile(minorsFile), nil +} + +func processMinorsFile(minorsFile io.Reader) MigCaps { + // Walk each line of nvcapsMigMinorsPath and construct a mapping of nvidia + // capabilities path to device minor for that capability + migCaps := make(MigCaps) + scanner := bufio.NewScanner(minorsFile) + for scanner.Scan() { + cap, minor, err := processMigMinorsLine(scanner.Text()) + if err != nil { + log.Printf("Skipping line in MIG minors file: %v", err) + continue + } + migCaps[cap] = minor + } + return migCaps +} + +func processMigMinorsLine(line string) (MigCap, MigMinor, error) { + parts := strings.Split(line, " ") + if len(parts) != 2 { + return "", 0, fmt.Errorf("error processing line: %v", line) + } + + migCap := MigCap(parts[0]) + if !migCap.isValid() { + return "", 0, fmt.Errorf("invalid MIG minors line: '%v'", line) + } + + minor, err := strconv.Atoi(parts[1]) + if err != nil { + return "", 0, fmt.Errorf("error reading MIG minor from '%v': %v", line, err) + } + + return migCap, MigMinor(minor), nil +} + +func (m MigCap) isValid() bool { + cap := string(m) + switch cap { + case "config", "monitor": + return true + default: + var gpu int + var gi int + var ci int + // Look for a CI access file + n, _ := fmt.Sscanf(cap, "gpu%d/gi%d/ci%d/access", &gpu, &gi, &ci) + if n == 3 { + return true + } + // Look for a GI access file + n, _ = fmt.Sscanf(cap, "gpu%d/gi%d/access %d", &gpu, &gi) + if n == 2 { + return true + } + } + return false +} + +// ProcPath returns the proc path associated with the MIG capability +func (m MigCap) ProcPath() string { + id := string(m) + + var path string + switch id { + case "config", "monitor": + path = "mig/" + id + default: + parts := strings.SplitN(id, "/", 2) + path = strings.Join([]string{parts[0], "mig", parts[1]}, "/") + } + return filepath.Join(nvidiaCapabilitiesPath, path) +} + +// DevicePath returns the path for the nvidia-caps device with the specified +// minor number +func (m MigMinor) DevicePath() string { + return fmt.Sprintf(nvcapsDevicePath+"/nvidia-cap%d", m) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/api.go new file mode 100644 index 00000000..6275a5c2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/api.go @@ -0,0 +1,45 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +// libraryOptions hold the parameters than can be set by a LibraryOption +type libraryOptions struct { + path string + flags int +} + +// LibraryOption represents a functional option to configure the underlying nvsandboxutils library +type LibraryOption func(*libraryOptions) + +// WithLibraryPath provides an option to set the library name to be used by the nvsandboxutils library. +func WithLibraryPath(path string) LibraryOption { + return func(o *libraryOptions) { + o.path = path + } +} + +// SetLibraryOptions applies the specified options to the nvsandboxutils library. +// If this is called when a library is already loaded, an error is raised. +func SetLibraryOptions(opts ...LibraryOption) error { + libnvsandboxutils.Lock() + defer libnvsandboxutils.Unlock() + if libnvsandboxutils.refcount != 0 { + return errLibraryAlreadyLoaded + } + libnvsandboxutils.init(opts...) + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers.h b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers.h new file mode 100644 index 00000000..23b3c256 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers.h @@ -0,0 +1,25 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +#include "nvsandboxutils.h" +#include +#pragma once + +#define __CGOGEN 1 + diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers_static.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers_static.go new file mode 100644 index 00000000..5924d622 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/cgo_helpers_static.go @@ -0,0 +1,38 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +var cgoAllocsUnknown = new(struct{}) + +func clen(n []byte) int { + for i := 0; i < len(n); i++ { + if n[i] == 0 { + return i + } + } + return len(n) +} + +// Creates an int8 array of fixed input length to store the Go string. +// TODO: Add error check if input string has a length greater than INPUT_LENGTH +func convertStringToFixedArray(str string) [INPUT_LENGTH]int8 { + var output [INPUT_LENGTH]int8 + for i, s := range str { + output[i] = int8(s) + } + return output +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/const.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/const.go new file mode 100644 index 00000000..9e8cdf3f --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/const.go @@ -0,0 +1,156 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +package nvsandboxutils + +/* +#cgo linux LDFLAGS: -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files +#cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup +#include "nvsandboxutils.h" +#include +#include "cgo_helpers.h" +*/ +import "C" + +const ( + // INPUT_LENGTH as defined in nvsandboxutils/nvsandboxutils.h + INPUT_LENGTH = 256 + // MAX_FILE_PATH as defined in nvsandboxutils/nvsandboxutils.h + MAX_FILE_PATH = 256 + // MAX_NAME_LENGTH as defined in nvsandboxutils/nvsandboxutils.h + MAX_NAME_LENGTH = 256 +) + +// Ret as declared in nvsandboxutils/nvsandboxutils.h +type Ret int32 + +// Ret enumeration from nvsandboxutils/nvsandboxutils.h +const ( + SUCCESS Ret = iota + ERROR_UNINITIALIZED Ret = 1 + ERROR_NOT_SUPPORTED Ret = 2 + ERROR_INVALID_ARG Ret = 3 + ERROR_INSUFFICIENT_SIZE Ret = 4 + ERROR_VERSION_NOT_SUPPORTED Ret = 5 + ERROR_LIBRARY_LOAD Ret = 6 + ERROR_FUNCTION_NOT_FOUND Ret = 7 + ERROR_DEVICE_NOT_FOUND Ret = 8 + ERROR_NVML_LIB_CALL Ret = 9 + ERROR_OUT_OF_MEMORY Ret = 10 + ERROR_FILEPATH_NOT_FOUND Ret = 11 + ERROR_UNKNOWN Ret = 65535 +) + +// LogLevel as declared in nvsandboxutils/nvsandboxutils.h +type LogLevel int32 + +// LogLevel enumeration from nvsandboxutils/nvsandboxutils.h +const ( + LOG_LEVEL_FATAL LogLevel = iota + LOG_LEVEL_ERROR LogLevel = 1 + LOG_LEVEL_WARN LogLevel = 2 + LOG_LEVEL_DEBUG LogLevel = 3 + LOG_LEVEL_INFO LogLevel = 4 + LOG_LEVEL_NONE LogLevel = 65535 +) + +// RootfsInputType as declared in nvsandboxutils/nvsandboxutils.h +type RootfsInputType int32 + +// RootfsInputType enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_ROOTFS_DEFAULT RootfsInputType = iota + NV_ROOTFS_PATH RootfsInputType = 1 + NV_ROOTFS_PID RootfsInputType = 2 +) + +// FileType as declared in nvsandboxutils/nvsandboxutils.h +type FileType int32 + +// FileType enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_DEV FileType = iota + NV_PROC FileType = 1 + NV_SYS FileType = 2 +) + +// FileSystemSubType as declared in nvsandboxutils/nvsandboxutils.h +type FileSystemSubType int32 + +// FileSystemSubType enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_DEV_NVIDIA FileSystemSubType = iota + NV_DEV_DRI_CARD FileSystemSubType = 1 + NV_DEV_DRI_RENDERD FileSystemSubType = 2 + NV_DEV_DRI_CARD_SYMLINK FileSystemSubType = 3 + NV_DEV_DRI_RENDERD_SYMLINK FileSystemSubType = 4 + NV_DEV_NVIDIA_UVM FileSystemSubType = 5 + NV_DEV_NVIDIA_UVM_TOOLS FileSystemSubType = 6 + NV_DEV_NVIDIA_MODESET FileSystemSubType = 7 + NV_DEV_NVIDIA_CTL FileSystemSubType = 8 + NV_DEV_GDRDRV FileSystemSubType = 9 + NV_DEV_NVIDIA_CAPS_NVIDIA_CAP FileSystemSubType = 10 + NV_PROC_DRIVER_NVIDIA_GPUS_PCIBUSID FileSystemSubType = 11 + NV_PROC_DRIVER_NVIDIA_GPUS FileSystemSubType = 12 + NV_PROC_NVIDIA_PARAMS FileSystemSubType = 13 + NV_PROC_NVIDIA_CAPS_MIG_MINORS FileSystemSubType = 14 + NV_PROC_DRIVER_NVIDIA_CAPABILITIES_GPU FileSystemSubType = 15 + NV_PROC_DRIVER_NVIDIA_CAPABILITIES FileSystemSubType = 16 + NV_PROC_DRIVER_NVIDIA_CAPABILITIIES_GPU_MIG_CI_ACCESS FileSystemSubType = 17 + NV_SYS_MODULE_NVIDIA_DRIVER_PCIBUSID FileSystemSubType = 18 + NV_SYS_MODULE_NVIDIA_DRIVER FileSystemSubType = 19 + NV_NUM_SUBTYPE FileSystemSubType = 20 +) + +// FileModule as declared in nvsandboxutils/nvsandboxutils.h +type FileModule int32 + +// FileModule enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_GPU FileModule = iota + NV_MIG FileModule = 1 + NV_DRIVER_NVIDIA FileModule = 2 + NV_DRIVER_NVIDIA_UVM FileModule = 3 + NV_DRIVER_NVIDIA_MODESET FileModule = 4 + NV_DRIVER_GDRDRV FileModule = 5 + NV_SYSTEM FileModule = 6 +) + +// FileFlag as declared in nvsandboxutils/nvsandboxutils.h +type FileFlag int32 + +// FileFlag enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_FILE_FLAG_HINT FileFlag = 1 + NV_FILE_FLAG_MASKOUT FileFlag = 2 + NV_FILE_FLAG_CONTENT FileFlag = 4 + NV_FILE_FLAG_DEPRECTATED FileFlag = 8 + NV_FILE_FLAG_CANDIDATES FileFlag = 16 +) + +// GpuInputType as declared in nvsandboxutils/nvsandboxutils.h +type GpuInputType int32 + +// GpuInputType enumeration from nvsandboxutils/nvsandboxutils.h +const ( + NV_GPU_INPUT_GPU_UUID GpuInputType = iota + NV_GPU_INPUT_MIG_UUID GpuInputType = 1 + NV_GPU_INPUT_PCI_ID GpuInputType = 2 + NV_GPU_INPUT_PCI_INDEX GpuInputType = 3 +) diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/doc.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/doc.go new file mode 100644 index 00000000..231c68c2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/doc.go @@ -0,0 +1,23 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +/* +Package NVSANDBOXUTILS bindings +*/ +package nvsandboxutils diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/dynamicLibrary_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/dynamicLibrary_mock.go new file mode 100644 index 00000000..a22e5669 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/dynamicLibrary_mock.go @@ -0,0 +1,157 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package nvsandboxutils + +import ( + "sync" +) + +// Ensure, that dynamicLibraryMock does implement dynamicLibrary. +// If this is not the case, regenerate this file with moq. +var _ dynamicLibrary = &dynamicLibraryMock{} + +// dynamicLibraryMock is a mock implementation of dynamicLibrary. +// +// func TestSomethingThatUsesdynamicLibrary(t *testing.T) { +// +// // make and configure a mocked dynamicLibrary +// mockeddynamicLibrary := &dynamicLibraryMock{ +// CloseFunc: func() error { +// panic("mock out the Close method") +// }, +// LookupFunc: func(s string) error { +// panic("mock out the Lookup method") +// }, +// OpenFunc: func() error { +// panic("mock out the Open method") +// }, +// } +// +// // use mockeddynamicLibrary in code that requires dynamicLibrary +// // and then make assertions. +// +// } +type dynamicLibraryMock struct { + // CloseFunc mocks the Close method. + CloseFunc func() error + + // LookupFunc mocks the Lookup method. + LookupFunc func(s string) error + + // OpenFunc mocks the Open method. + OpenFunc func() error + + // calls tracks calls to the methods. + calls struct { + // Close holds details about calls to the Close method. + Close []struct { + } + // Lookup holds details about calls to the Lookup method. + Lookup []struct { + // S is the s argument value. + S string + } + // Open holds details about calls to the Open method. + Open []struct { + } + } + lockClose sync.RWMutex + lockLookup sync.RWMutex + lockOpen sync.RWMutex +} + +// Close calls CloseFunc. +func (mock *dynamicLibraryMock) Close() error { + callInfo := struct { + }{} + mock.lockClose.Lock() + mock.calls.Close = append(mock.calls.Close, callInfo) + mock.lockClose.Unlock() + if mock.CloseFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.CloseFunc() +} + +// CloseCalls gets all the calls that were made to Close. +// Check the length with: +// +// len(mockeddynamicLibrary.CloseCalls()) +func (mock *dynamicLibraryMock) CloseCalls() []struct { +} { + var calls []struct { + } + mock.lockClose.RLock() + calls = mock.calls.Close + mock.lockClose.RUnlock() + return calls +} + +// Lookup calls LookupFunc. +func (mock *dynamicLibraryMock) Lookup(s string) error { + callInfo := struct { + S string + }{ + S: s, + } + mock.lockLookup.Lock() + mock.calls.Lookup = append(mock.calls.Lookup, callInfo) + mock.lockLookup.Unlock() + if mock.LookupFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.LookupFunc(s) +} + +// LookupCalls gets all the calls that were made to Lookup. +// Check the length with: +// +// len(mockeddynamicLibrary.LookupCalls()) +func (mock *dynamicLibraryMock) LookupCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockLookup.RLock() + calls = mock.calls.Lookup + mock.lockLookup.RUnlock() + return calls +} + +// Open calls OpenFunc. +func (mock *dynamicLibraryMock) Open() error { + callInfo := struct { + }{} + mock.lockOpen.Lock() + mock.calls.Open = append(mock.calls.Open, callInfo) + mock.lockOpen.Unlock() + if mock.OpenFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.OpenFunc() +} + +// OpenCalls gets all the calls that were made to Open. +// Check the length with: +// +// len(mockeddynamicLibrary.OpenCalls()) +func (mock *dynamicLibraryMock) OpenCalls() []struct { +} { + var calls []struct { + } + mock.lockOpen.RLock() + calls = mock.calls.Open + mock.lockOpen.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/gpu-resources.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/gpu-resources.go new file mode 100644 index 00000000..19dec07e --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/gpu-resources.go @@ -0,0 +1,67 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +import ( + "strings" + "unsafe" +) + +import "C" + +type GpuResource struct { + Version uint32 +} + +type GpuFileInfo struct { + Path string + Type FileType + SubType FileSystemSubType + Module FileModule + Flags FileFlag +} + +func (l *library) GetGpuResource(uuid string) ([]GpuFileInfo, Ret) { + deviceType := NV_GPU_INPUT_GPU_UUID + if strings.HasPrefix(uuid, "MIG-") { + deviceType = NV_GPU_INPUT_MIG_UUID + } + + request := GpuRes{ + Version: 1, + InputType: uint32(deviceType), + Input: convertStringToFixedArray(uuid), + } + + ret := nvSandboxUtilsGetGpuResource(&request) + if ret != SUCCESS { + return nil, ret + } + + var fileInfos []GpuFileInfo + for fileInfo := request.Files; fileInfo != nil; fileInfo = fileInfo.Next { + fi := GpuFileInfo{ + Path: C.GoString((*C.char)(unsafe.Pointer(fileInfo.FilePath))), + Type: FileType(fileInfo.FileType), + SubType: FileSystemSubType(fileInfo.FileSubType), + Module: FileModule(fileInfo.Module), + Flags: FileFlag(fileInfo.Flags), + } + fileInfos = append(fileInfos, fi) + } + return fileInfos, SUCCESS +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/impl.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/impl.go new file mode 100644 index 00000000..0f6948a2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/impl.go @@ -0,0 +1,64 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +import "C" + +func (l *library) Init(path string) Ret { + if err := l.load(); err != nil { + return ERROR_LIBRARY_LOAD + } + + input := InitInput{ + Version: 1, + Type: uint32(NV_ROOTFS_PATH), + Value: convertStringToFixedArray(path), + } + + return nvSandboxUtilsInit(&input) +} + +func (l *library) Shutdown() Ret { + ret := nvSandboxUtilsShutdown() + if ret != SUCCESS { + return ret + } + + err := l.close() + if err != nil { + return ERROR_UNKNOWN + } + + return ret +} + +// TODO: Is this length specified in the header file? +const VERSION_LENGTH = 100 + +func (l *library) GetDriverVersion() (string, Ret) { + Version := make([]byte, VERSION_LENGTH) + ret := nvSandboxUtilsGetDriverVersion(&Version[0], VERSION_LENGTH) + return string(Version[:clen(Version)]), ret +} + +func (l *library) GetFileContent(path string) (string, Ret) { + Content := make([]byte, MAX_FILE_PATH) + FilePath := []byte(path + string(byte(0))) + Size := uint32(MAX_FILE_PATH) + ret := nvSandboxUtilsGetFileContent(&FilePath[0], &Content[0], &Size) + return string(Content[:clen(Content)]), ret +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/lib.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/lib.go new file mode 100644 index 00000000..3a85ef89 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/lib.go @@ -0,0 +1,156 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +import ( + "errors" + "fmt" + "sync" + + "github.com/NVIDIA/go-nvml/pkg/dl" +) + +const ( + defaultNvSandboxUtilsLibraryName = "libnvidia-sandboxutils.so.1" + defaultNvSandboxUtilsLibraryLoadFlags = dl.RTLD_LAZY | dl.RTLD_GLOBAL +) + +var errLibraryNotLoaded = errors.New("library not loaded") +var errLibraryAlreadyLoaded = errors.New("library already loaded") + +// dynamicLibrary is an interface for abstacting the underlying library. +// This also allows for mocking and testing. + +//go:generate moq -rm -stub -out dynamicLibrary_mock.go . dynamicLibrary +type dynamicLibrary interface { + Lookup(string) error + Open() error + Close() error +} + +// library represents an nvsandboxutils library. +// This includes a reference to the underlying DynamicLibrary +type library struct { + sync.Mutex + path string + refcount refcount + dl dynamicLibrary +} + +// libnvsandboxutils is a global instance of the nvsandboxutils library. +var libnvsandboxutils = newLibrary() + +func New(opts ...LibraryOption) Interface { + return newLibrary(opts...) +} + +func newLibrary(opts ...LibraryOption) *library { + l := &library{} + l.init(opts...) + return l +} + +func (l *library) init(opts ...LibraryOption) { + o := libraryOptions{} + for _, opt := range opts { + opt(&o) + } + + if o.path == "" { + o.path = defaultNvSandboxUtilsLibraryName + } + if o.flags == 0 { + o.flags = defaultNvSandboxUtilsLibraryLoadFlags + } + + l.path = o.path + l.dl = dl.New(o.path, o.flags) +} + +// LookupSymbol checks whether the specified library symbol exists in the library. +// Note that this requires that the library be loaded. +func (l *library) LookupSymbol(name string) error { + if l == nil || l.refcount == 0 { + return fmt.Errorf("error looking up %s: %w", name, errLibraryNotLoaded) + } + return l.dl.Lookup(name) +} + +// load initializes the library and updates the versioned symbols. +// Multiple calls to an already loaded library will return without error. +func (l *library) load() (rerr error) { + l.Lock() + defer l.Unlock() + + defer func() { l.refcount.IncOnNoError(rerr) }() + if l.refcount > 0 { + return nil + } + + if err := l.dl.Open(); err != nil { + return fmt.Errorf("error opening %s: %w", l.path, err) + } + + // Update the errorStringFunc to point to nvsandboxutils.ErrorString + errorStringFunc = nvsanboxutilsErrorString + + // Update all versioned symbols + l.updateVersionedSymbols() + + return nil +} + +// close the underlying library and ensure that the global pointer to the +// library is set to nil to ensure that subsequent calls to open will reinitialize it. +// Multiple calls to an already closed nvsandboxutils library will return without error. +func (l *library) close() (rerr error) { + l.Lock() + defer l.Unlock() + + defer func() { l.refcount.DecOnNoError(rerr) }() + if l.refcount != 1 { + return nil + } + + if err := l.dl.Close(); err != nil { + return fmt.Errorf("error closing %s: %w", l.path, err) + } + + // Update the errorStringFunc to point to defaultErrorStringFunc + errorStringFunc = defaultErrorStringFunc + + return nil +} + +// Default all versioned APIs to v1 (to infer the types) +var ( +// Insert default versions for APIs here. +// Example: +// nvsandboxUtilsFunction = nvsandboxUtilsFunction_v1 +) + +// updateVersionedSymbols checks for versioned symbols in the loaded dynamic library. +// If newer versioned symbols exist, these replace the default `v1` symbols initialized above. +// When new versioned symbols are added, these would have to be initialized above and have +// corresponding checks and subsequent assignments added below. +func (l *library) updateVersionedSymbols() { + // Example: + // err := l.dl.Lookup("nvsandboxUtilsFunction_v2") + // if err == nil { + // nvsandboxUtilsFunction = nvsandboxUtilsFunction_v2 + // } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.go new file mode 100644 index 00000000..29544bc9 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.go @@ -0,0 +1,72 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// WARNING: THIS FILE WAS AUTOMATICALLY GENERATED. +// Code generated by https://git.io/c-for-go. DO NOT EDIT. + +package nvsandboxutils + +/* +#cgo linux LDFLAGS: -Wl,--export-dynamic -Wl,--unresolved-symbols=ignore-in-object-files +#cgo darwin LDFLAGS: -Wl,-undefined,dynamic_lookup +#include "nvsandboxutils.h" +#include +#include "cgo_helpers.h" +*/ +import "C" +import "unsafe" + +// nvSandboxUtilsInit function as declared in nvsandboxutils/nvsandboxutils.h +func nvSandboxUtilsInit(Input *InitInput) Ret { + cInput, _ := (*C.nvSandboxUtilsInitInput_t)(unsafe.Pointer(Input)), cgoAllocsUnknown + __ret := C.nvSandboxUtilsInit(cInput) + __v := (Ret)(__ret) + return __v +} + +// nvSandboxUtilsShutdown function as declared in nvsandboxutils/nvsandboxutils.h +func nvSandboxUtilsShutdown() Ret { + __ret := C.nvSandboxUtilsShutdown() + __v := (Ret)(__ret) + return __v +} + +// nvSandboxUtilsGetDriverVersion function as declared in nvsandboxutils/nvsandboxutils.h +func nvSandboxUtilsGetDriverVersion(Version *byte, Length uint32) Ret { + cVersion, _ := (*C.char)(unsafe.Pointer(Version)), cgoAllocsUnknown + cLength, _ := (C.uint)(Length), cgoAllocsUnknown + __ret := C.nvSandboxUtilsGetDriverVersion(cVersion, cLength) + __v := (Ret)(__ret) + return __v +} + +// nvSandboxUtilsGetGpuResource function as declared in nvsandboxutils/nvsandboxutils.h +func nvSandboxUtilsGetGpuResource(Request *GpuRes) Ret { + cRequest, _ := (*C.nvSandboxUtilsGpuRes_t)(unsafe.Pointer(Request)), cgoAllocsUnknown + __ret := C.nvSandboxUtilsGetGpuResource(cRequest) + __v := (Ret)(__ret) + return __v +} + +// nvSandboxUtilsGetFileContent function as declared in nvsandboxutils/nvsandboxutils.h +func nvSandboxUtilsGetFileContent(FilePath *byte, Content *byte, ContentSize *uint32) Ret { + cFilePath, _ := (*C.char)(unsafe.Pointer(FilePath)), cgoAllocsUnknown + cContent, _ := (*C.char)(unsafe.Pointer(Content)), cgoAllocsUnknown + cContentSize, _ := (*C.uint)(unsafe.Pointer(ContentSize)), cgoAllocsUnknown + __ret := C.nvSandboxUtilsGetFileContent(cFilePath, cContent, cContentSize) + __v := (Ret)(__ret) + return __v +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.h b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.h new file mode 100644 index 00000000..3c66e159 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/nvsandboxutils.h @@ -0,0 +1,298 @@ +/* + * SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef __NVSANDBOXUTILS_H__ +#define __NVSANDBOXUTILS_H__ + +#ifdef __cplusplus +extern "C" { +#endif + +#define INPUT_LENGTH 256 +#define MAX_FILE_PATH 256 +#define MAX_NAME_LENGTH 256 + +/***************************************************************************************************/ +/** @defgroup enums Enumerations + * @{ + */ +/***************************************************************************************************/ + +/** + * Return types + */ +typedef enum +{ + NVSANDBOXUTILS_SUCCESS = 0, //!< The operation was successful + NVSANDBOXUTILS_ERROR_UNINITIALIZED = 1, //!< The library wasn't successfully initialized + NVSANDBOXUTILS_ERROR_NOT_SUPPORTED = 2, //!< The requested operation is not supported on target device + NVSANDBOXUTILS_ERROR_INVALID_ARG = 3, //!< A supplied argument is invalid + NVSANDBOXUTILS_ERROR_INSUFFICIENT_SIZE = 4, //!< A supplied argument is not large enough + NVSANDBOXUTILS_ERROR_VERSION_NOT_SUPPORTED = 5, //!< Requested library version is not supported + NVSANDBOXUTILS_ERROR_LIBRARY_LOAD = 6, //!< The library load failed + NVSANDBOXUTILS_ERROR_FUNCTION_NOT_FOUND = 7, //!< Called function was not found + NVSANDBOXUTILS_ERROR_DEVICE_NOT_FOUND = 8, //!< Target device was not found + NVSANDBOXUTILS_ERROR_NVML_LIB_CALL = 9, //!< NVML library call failed + NVSANDBOXUTILS_ERROR_OUT_OF_MEMORY = 10, //!< There is insufficient memory + NVSANDBOXUTILS_ERROR_FILEPATH_NOT_FOUND = 11, //!< A supplied file path was not found + NVSANDBOXUTILS_ERROR_UNKNOWN = 0xFFFF, //!< Unknown error occurred +} nvSandboxUtilsRet_t; + +/** + * Return if there is an error + */ +#define RETURN_ON_SANDBOX_ERROR(result) \ + if ((result) != NVSANDBOXUTILS_SUCCESS) { \ + NVSANDBOXUTILS_ERROR_MSG("%s %d result=%d", __func__, __LINE__, result); \ + return result; \ + } + +/** + * Log levels + */ +typedef enum +{ + NVSANDBOXUTILS_LOG_LEVEL_FATAL = 0, //!< Log fatal errors + NVSANDBOXUTILS_LOG_LEVEL_ERROR = 1, //!< Log all errors + NVSANDBOXUTILS_LOG_LEVEL_WARN = 2, //!< Log all warnings + NVSANDBOXUTILS_LOG_LEVEL_DEBUG = 3, //!< Log all debug messages + NVSANDBOXUTILS_LOG_LEVEL_INFO = 4, //!< Log all info messages + NVSANDBOXUTILS_LOG_LEVEL_NONE = 0xFFFF, //!< Log none +} nvSandboxUtilsLogLevel_t; + +/** + * Input rootfs to help access files inside the driver container + */ +typedef enum +{ + NV_ROOTFS_DEFAULT, //!< Default no rootfs + NV_ROOTFS_PATH, //!< /run/nvidia/driver + NV_ROOTFS_PID, //!< /proc/PID/mountinfo +} nvSandboxUtilsRootfsInputType_t; + +/** + * File type + */ +typedef enum +{ + NV_DEV, //!< /dev file system + NV_PROC, //!< /proc file system + NV_SYS, //!< /sys file system +} nvSandboxUtilsFileType_t; + +/** + * File subtype + */ +typedef enum +{ + NV_DEV_NVIDIA, //!< /dev/nvidia0 + NV_DEV_DRI_CARD, //!< /dev/dri/card1 + NV_DEV_DRI_RENDERD, //!< /dev/dri/renderD128 + NV_DEV_DRI_CARD_SYMLINK, //!< /dev/dri/by-path/pci-0000:41:00.0-card + NV_DEV_DRI_RENDERD_SYMLINK, //!< /dev/dri/by-path/pci-0000:41:00.0-render + NV_DEV_NVIDIA_UVM, //!< /dev/nvidia-uvm + NV_DEV_NVIDIA_UVM_TOOLS, //!< /dev/nvidia-uvm-tools + NV_DEV_NVIDIA_MODESET, //!< /dev/nvidia-uvm-modeset + NV_DEV_NVIDIA_CTL, //!< /dev/nvidiactl + NV_DEV_GDRDRV, //!< /dev/gdrdrv + NV_DEV_NVIDIA_CAPS_NVIDIA_CAP, //!< /dev/nvidia-caps/nvidia-cap22 + NV_PROC_DRIVER_NVIDIA_GPUS_PCIBUSID, //!< /proc/driver/nvidia/gpus/0000:2d:00.0 + NV_PROC_DRIVER_NVIDIA_GPUS, //!< /proc/driver/nvidia/gpus (for mask out) + NV_PROC_NVIDIA_PARAMS, //!< /proc/driver/nvidia/params + NV_PROC_NVIDIA_CAPS_MIG_MINORS, //!< /proc/driver/nvidia-caps/mig-minors + NV_PROC_DRIVER_NVIDIA_CAPABILITIES_GPU, //!< /proc/driver/nvidia/capabilities/gpu0 + NV_PROC_DRIVER_NVIDIA_CAPABILITIES, //!< /proc/driver/nvidia/capabilities (for mask out) + NV_PROC_DRIVER_NVIDIA_CAPABILITIIES_GPU_MIG_CI_ACCESS, //!< proc/driver/nvidia/capabilities/gpu0/mig/gi2/ci0/access + NV_SYS_MODULE_NVIDIA_DRIVER_PCIBUSID, //!< /sys/module/nvidia/drivers/pci:nvidia/0000:2d:00.0 + NV_SYS_MODULE_NVIDIA_DRIVER, //!< /sys/module/nvidia/drivers/pci:nvidia (for mask out) + NV_NUM_SUBTYPE, // always at the end. +} nvSandboxUtilsFileSystemSubType_t; + +/** + * File module + */ +typedef enum +{ + NV_GPU, //!< Target device + NV_MIG, //!< Target device- MIG + NV_DRIVER_NVIDIA, //!< NVIDIA kernel driver + NV_DRIVER_NVIDIA_UVM, //!< NVIDIA kernel driver-UVM + NV_DRIVER_NVIDIA_MODESET, //!< NVIDIA kernel driver-modeset + NV_DRIVER_GDRDRV, //!< GDRDRV driver + NV_SYSTEM, //!< System module +} nvSandboxUtilsFileModule_t; + +/** + * Flag to provide additional details about the file + */ +typedef enum +{ + NV_FILE_FLAG_HINT = (1 << 0), //!< Default no hint + NV_FILE_FLAG_MASKOUT = (1 << 1), //!< For /proc/driver/nvidia/gpus + NV_FILE_FLAG_CONTENT = (1 << 2), //!< For /proc/driver/nvidia/params + //!< For SYMLINK + //!< Use \p nvSandboxUtilsGetFileContent to get name of the linked file + NV_FILE_FLAG_DEPRECTATED = (1 << 3), //!< For all the FIRMWARE GSP file + NV_FILE_FLAG_CANDIDATES = (1 << 4), //!< For libcuda.so +} nvSandboxUtilsFileFlag_t; + +/** + * Input type of the target device + */ +typedef enum +{ + NV_GPU_INPUT_GPU_UUID, //!< GPU UUID + NV_GPU_INPUT_MIG_UUID, //!< MIG UUID + NV_GPU_INPUT_PCI_ID, //!< PCIe DBDF ID + NV_GPU_INPUT_PCI_INDEX, //!< PCIe bus order (0 points to the GPU that has lowest PCIe BDF) +} nvSandboxUtilsGpuInputType_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup dataTypes Structures and Unions + * @{ + */ +/***************************************************************************************************/ + +/** + * Initalization input v1 + */ +typedef struct +{ + unsigned int version; //!< Version for the structure + nvSandboxUtilsRootfsInputType_t type; //!< One of \p nvSandboxUtilsRootfsInputType_t + char value[INPUT_LENGTH]; //!< String representation of input +} nvSandboxUtilsInitInput_v1_t; + +typedef nvSandboxUtilsInitInput_v1_t nvSandboxUtilsInitInput_t; + +/** + * File system information + */ +typedef struct nvSandboxUtilsGpuFileInfo_v1_t +{ + struct nvSandboxUtilsGpuFileInfo_v1_t *next; //!< Pointer to the next node in the linked list + nvSandboxUtilsFileType_t fileType; //!< One of \p nvSandboxUtilsFileType_t + nvSandboxUtilsFileSystemSubType_t fileSubType; //!< One of \p nvSandboxUtilsFileSystemSubType_t + nvSandboxUtilsFileModule_t module; //!< One of \p nvSandboxUtilsFileModule_t + nvSandboxUtilsFileFlag_t flags; //!< One of \p nvSandboxUtilsFileFlag_t + char *filePath; //!< Relative file path to rootfs +}nvSandboxUtilsGpuFileInfo_v1_t; + +/** + * GPU resource request v1 + */ +typedef struct +{ + unsigned int version; //!< Version for the structure + nvSandboxUtilsGpuInputType_t inputType; //!< One of \p nvSandboxUtilsGpuInputType_t + char input[INPUT_LENGTH]; //!< String representation of input + nvSandboxUtilsGpuFileInfo_v1_t *files; //!< Linked list of \ref nvSandboxUtilsGpuFileInfo_v1_t +} nvSandboxUtilsGpuRes_v1_t; + +typedef nvSandboxUtilsGpuRes_v1_t nvSandboxUtilsGpuRes_t; + +/** @} */ + +/***************************************************************************************************/ +/** @defgroup funcs Functions + * @{ + */ +/***************************************************************************************************/ + +/* ************************************************* + * Initialize library + * ************************************************* + */ +/** + * Prepare library resources before library API can be used. + * This initialization will not fail if one of the initialization prerequisites fails. + * @param input Reference to the called-supplied input struct that has initialization fields + * + * @returns @ref NVSANDBOXUTILS_SUCCESS on success + * @returns @ref NVSANDBOXUTILS_ERROR_INVALID_ARG if \p input->value isn't a valid rootfs path + * @returns @ref NVSANDBOXUTILS_ERROR_VERSION_NOT_SUPPORTED if \p input->version isn't supported by the library + * @returns @ref NVSANDBOXUTILS_ERROR_FILEPATH_NOT_FOUND if any of the required file paths are not found during initialization + * @returns @ref NVSANDBOXUTILS_ERROR_OUT_OF_MEMORY if there is insufficient system memory during initialization + * @returns @ref NVSANDBOXUTILS_ERROR_LIBRARY_LOAD on any error during loading the library + */ +nvSandboxUtilsRet_t nvSandboxUtilsInit(nvSandboxUtilsInitInput_t *input); + +/* ************************************************* + * Shutdown library + * ************************************************* + */ +/** + * Clean up library resources created by init call + * + * @returns @ref NVSANDBOXUTILS_SUCCESS on success + */ +nvSandboxUtilsRet_t nvSandboxUtilsShutdown(void); + +/* ************************************************* + * Get NVIDIA RM driver version + * ************************************************* + */ +/** + * Get NVIDIA RM driver version + * @param version Reference to caller-supplied buffer to return driver version string + * @param length The maximum allowed length of the string returned in \p version + * + * @returns @ref NVSANDBOXUTILS_SUCCESS on success + * @returns @ref NVSANDBOXUTILS_ERROR_INVALID_ARG if \p version is NULL + * @returns @ref NVSANDBOXUTILS_ERROR_NVML_LIB_CALL on any error during driver version query from NVML + */ +nvSandboxUtilsRet_t nvSandboxUtilsGetDriverVersion(char *version, unsigned int length); + +/* ************************************************* + * Get /dev, /proc, /sys file system information + * ************************************************* + */ +/** + * Get /dev, /proc, /sys file system information + * @param request Reference to caller-supplied request struct to return the file system information + * + * @returns @ref NVSANDBOXUTILS_SUCCESS on success + * @returns @ref NVSANDBOXUTILS_ERROR_INVALID_ARG if \p request->input doesn't match any device + * @returns @ref NVSANDBOXUTILS_ERROR_VERSION_NOT_SUPPORTED if \p request->version isn't supported by the library + */ +nvSandboxUtilsRet_t nvSandboxUtilsGetGpuResource(nvSandboxUtilsGpuRes_t *request); + +/* ************************************************* + * Get content of given file path + * ************************************************* + */ +/** + * Get file content of input file path + * @param filePath Reference to the file path + * @param content Reference to the caller-supplied buffer to return the file content + * @param contentSize Reference to the maximum allowed size of content. It is updated to the actual size of the content on return + * + * @returns @ref NVSANDBOXUTILS_SUCCESS on success + * @returns @ref NVSANDBOXUTILS_ERROR_INVALID_ARG if \p filePath or \p content is NULL + * @returns @ref NVSANDBOXUTILS_ERROR_INSUFFICIENT_SIZE if \p contentSize is too small + * @returns @ref NVSANDBOXUTILS_ERROR_FILEPATH_NOT_FOUND on an error while obtaining the content for the file path + */ +nvSandboxUtilsRet_t nvSandboxUtilsGetFileContent(char *filePath, char *content, unsigned int *contentSize); + +/** @} */ + +#ifdef __cplusplus +} +#endif +#endif // __NVSANDBOXUTILS_H__ diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/refcount.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/refcount.go new file mode 100644 index 00000000..f93107b0 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/refcount.go @@ -0,0 +1,31 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +type refcount int + +func (r *refcount) IncOnNoError(err error) { + if err == nil { + (*r)++ + } +} + +func (r *refcount) DecOnNoError(err error) { + if err == nil && (*r) > 0 { + (*r)-- + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/return.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/return.go new file mode 100644 index 00000000..90d4ed84 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/return.go @@ -0,0 +1,74 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvsandboxutils + +import ( + "fmt" +) + +// nvsandboxutils.ErrorString() +func (l *library) ErrorString(r Ret) string { + return r.Error() +} + +// String returns the string representation of a Ret. +func (r Ret) String() string { + return r.Error() +} + +// Error returns the string representation of a Ret. +func (r Ret) Error() string { + return errorStringFunc(r) +} + +// Assigned to nvsandboxutils.ErrorString if the system nvsandboxutils library is in use. +var errorStringFunc = defaultErrorStringFunc + +// nvsanboxutilsErrorString is an alias for the default error string function. +var nvsanboxutilsErrorString = defaultErrorStringFunc + +// defaultErrorStringFunc provides a basic nvsandboxutils.ErrorString implementation. +// This allows the nvsandboxutils.ErrorString function to be used even if the nvsandboxutils library +// is not loaded. +var defaultErrorStringFunc = func(r Ret) string { + switch r { + case SUCCESS: + return "SUCCESS" + case ERROR_UNINITIALIZED: + return "ERROR_UNINITIALIZED" + case ERROR_NOT_SUPPORTED: + return "ERROR_NOT_SUPPORTED" + case ERROR_INVALID_ARG: + return "ERROR_INVALID_ARG" + case ERROR_INSUFFICIENT_SIZE: + return "ERROR_INSUFFICIENT_SIZE" + case ERROR_VERSION_NOT_SUPPORTED: + return "ERROR_VERSION_NOT_SUPPORTED" + case ERROR_LIBRARY_LOAD: + return "ERROR_LIBRARY_LOAD" + case ERROR_FUNCTION_NOT_FOUND: + return "ERROR_FUNCTION_NOT_FOUND" + case ERROR_DEVICE_NOT_FOUND: + return "ERROR_DEVICE_NOT_FOUND" + case ERROR_NVML_LIB_CALL: + return "ERROR_NVML_LIB_CALL" + case ERROR_UNKNOWN: + return "ERROR_UNKNOWN" + default: + return fmt.Sprintf("unknown return value: %d", r) + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/types_gen.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/types_gen.go new file mode 100644 index 00000000..90a00ed6 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/types_gen.go @@ -0,0 +1,39 @@ +// Code generated by cmd/cgo -godefs; DO NOT EDIT. +// cgo -godefs types.go + +package nvsandboxutils + +type InitInput_v1 struct { + Version uint32 + Type uint32 + Value [256]int8 +} + +type InitInput struct { + Version uint32 + Type uint32 + Value [256]int8 +} + +type GpuFileInfo_v1 struct { + Next *GpuFileInfo_v1 + FileType uint32 + FileSubType uint32 + Module uint32 + Flags uint32 + FilePath *int8 +} + +type GpuRes_v1 struct { + Version uint32 + InputType uint32 + Input [256]int8 + Files *GpuFileInfo_v1 +} + +type GpuRes struct { + Version uint32 + InputType uint32 + Input [256]int8 + Files *GpuFileInfo_v1 +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/zz_generated.api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/zz_generated.api.go new file mode 100644 index 00000000..1cc2b01a --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils/zz_generated.api.go @@ -0,0 +1,43 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +// Generated Code; DO NOT EDIT. + +package nvsandboxutils + +// The variables below represent package level methods from the library type. +var ( + ErrorString = libnvsandboxutils.ErrorString + GetDriverVersion = libnvsandboxutils.GetDriverVersion + GetFileContent = libnvsandboxutils.GetFileContent + GetGpuResource = libnvsandboxutils.GetGpuResource + Init = libnvsandboxutils.Init + LookupSymbol = libnvsandboxutils.LookupSymbol + Shutdown = libnvsandboxutils.Shutdown +) + +// Interface represents the interface for the library type. +// +//go:generate moq -out mock/interface.go -pkg mock . Interface:Interface +type Interface interface { + ErrorString(Ret) string + GetDriverVersion() (string, Ret) + GetFileContent(string) (string, Ret) + GetGpuResource(string) ([]GpuFileInfo, Ret) + Init(string) Ret + LookupSymbol(string) error + Shutdown() Ret +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/args.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/args.go new file mode 100644 index 00000000..de85d9cc --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/args.go @@ -0,0 +1,115 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + "path/filepath" + "strings" +) + +const ( + specFileName = "config.json" +) + +// GetBundleDir returns the bundle directory or default depending on the +// supplied command line arguments. +func GetBundleDir(args []string) (string, error) { + bundleDir, err := GetBundleDirFromArgs(args) + if err != nil { + return "", fmt.Errorf("error getting bundle dir from args: %v", err) + } + + return bundleDir, nil +} + +// GetBundleDirFromArgs checks the specified slice of strings (argv) for a 'bundle' flag as allowed by runc. +// The following are supported: +// --bundle{{SEP}}BUNDLE_PATH +// -bundle{{SEP}}BUNDLE_PATH +// -b{{SEP}}BUNDLE_PATH +// where {{SEP}} is either ' ' or '=' +func GetBundleDirFromArgs(args []string) (string, error) { + var bundleDir string + + for i := 0; i < len(args); i++ { + param := args[i] + + parts := strings.SplitN(param, "=", 2) + if !IsBundleFlag(parts[0]) { + continue + } + + // The flag has the format --bundle=/path + if len(parts) == 2 { + bundleDir = parts[1] + continue + } + + // The flag has the format --bundle /path + if i+1 < len(args) { + bundleDir = args[i+1] + i++ + continue + } + + // --bundle / -b was the last element of args + return "", fmt.Errorf("bundle option requires an argument") + } + + return bundleDir, nil +} + +// GetSpecFilePath returns the expected path to the OCI specification file for the given +// bundle directory. +func GetSpecFilePath(bundleDir string) string { + specFilePath := filepath.Join(bundleDir, specFileName) + return specFilePath +} + +// IsBundleFlag is a helper function that checks wither the specified argument represents +// a bundle flag (--bundle or -b) +func IsBundleFlag(arg string) bool { + if !strings.HasPrefix(arg, "-") { + return false + } + + trimmed := strings.TrimLeft(arg, "-") + return trimmed == "b" || trimmed == "bundle" +} + +// HasCreateSubcommand checks the supplied arguments for a 'create' subcommand +func HasCreateSubcommand(args []string) bool { + var previousWasBundle bool + for _, a := range args { + // We check for '--bundle create' explicitly to ensure that we + // don't inadvertently trigger a modification if the bundle directory + // is specified as `create` + if !previousWasBundle && IsBundleFlag(a) { + previousWasBundle = true + continue + } + + if !previousWasBundle && a == "create" { + return true + } + + previousWasBundle = false + } + + return false +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime.go new file mode 100644 index 00000000..2ea71cb2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime.go @@ -0,0 +1,26 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +// Runtime is an interface for a runtime shim. The Exec method accepts a list +// of command line arguments, and returns an error / nil. +// +//go:generate moq -rm -stub -out runtime_mock.go . Runtime +type Runtime interface { + Exec([]string) error + String() string +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_low_level.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_low_level.go new file mode 100644 index 00000000..65ae8b21 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_low_level.go @@ -0,0 +1,55 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +// NewLowLevelRuntime creates a Runtime that wraps a low-level runtime executable. +// The executable specified is taken from the list of supplied candidates, with the first match +// present in the PATH being selected. A logger is also specified. +func NewLowLevelRuntime(logger logger.Interface, candidates []string) (Runtime, error) { + runtimePath, err := findRuntime(logger, candidates) + if err != nil { + return nil, fmt.Errorf("error locating runtime: %v", err) + } + return NewRuntimeForPath(logger, runtimePath) +} + +// findRuntime checks elements in a list of supplied candidates for a matching executable in the PATH. +// The absolute path to the first match is returned. +func findRuntime(logger logger.Interface, candidates []string) (string, error) { + if len(candidates) == 0 { + return "", fmt.Errorf("at least one runtime candidate must be specified") + } + + locator := lookup.NewExecutableLocator(logger, "/") + for _, candidate := range candidates { + logger.Tracef("Looking for runtime binary '%v'", candidate) + targets, err := locator.Locate(candidate) + if err == nil && len(targets) > 0 { + logger.Tracef("Found runtime binary '%v'", targets) + return targets[0], nil + } + } + + return "", fmt.Errorf("no runtime binary found from candidate list: %v", candidates) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_mock.go new file mode 100644 index 00000000..147035d4 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_mock.go @@ -0,0 +1,117 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package oci + +import ( + "sync" +) + +// Ensure, that RuntimeMock does implement Runtime. +// If this is not the case, regenerate this file with moq. +var _ Runtime = &RuntimeMock{} + +// RuntimeMock is a mock implementation of Runtime. +// +// func TestSomethingThatUsesRuntime(t *testing.T) { +// +// // make and configure a mocked Runtime +// mockedRuntime := &RuntimeMock{ +// ExecFunc: func(strings []string) error { +// panic("mock out the Exec method") +// }, +// StringFunc: func() string { +// panic("mock out the String method") +// }, +// } +// +// // use mockedRuntime in code that requires Runtime +// // and then make assertions. +// +// } +type RuntimeMock struct { + // ExecFunc mocks the Exec method. + ExecFunc func(strings []string) error + + // StringFunc mocks the String method. + StringFunc func() string + + // calls tracks calls to the methods. + calls struct { + // Exec holds details about calls to the Exec method. + Exec []struct { + // Strings is the strings argument value. + Strings []string + } + // String holds details about calls to the String method. + String []struct { + } + } + lockExec sync.RWMutex + lockString sync.RWMutex +} + +// Exec calls ExecFunc. +func (mock *RuntimeMock) Exec(strings []string) error { + callInfo := struct { + Strings []string + }{ + Strings: strings, + } + mock.lockExec.Lock() + mock.calls.Exec = append(mock.calls.Exec, callInfo) + mock.lockExec.Unlock() + if mock.ExecFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.ExecFunc(strings) +} + +// ExecCalls gets all the calls that were made to Exec. +// Check the length with: +// +// len(mockedRuntime.ExecCalls()) +func (mock *RuntimeMock) ExecCalls() []struct { + Strings []string +} { + var calls []struct { + Strings []string + } + mock.lockExec.RLock() + calls = mock.calls.Exec + mock.lockExec.RUnlock() + return calls +} + +// String calls StringFunc. +func (mock *RuntimeMock) String() string { + callInfo := struct { + }{} + mock.lockString.Lock() + mock.calls.String = append(mock.calls.String, callInfo) + mock.lockString.Unlock() + if mock.StringFunc == nil { + var ( + sOut string + ) + return sOut + } + return mock.StringFunc() +} + +// StringCalls gets all the calls that were made to String. +// Check the length with: +// +// len(mockedRuntime.StringCalls()) +func (mock *RuntimeMock) StringCalls() []struct { +} { + var calls []struct { + } + mock.lockString.RLock() + calls = mock.calls.String + mock.lockString.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_modifier.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_modifier.go new file mode 100644 index 00000000..50ca42fb --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_modifier.go @@ -0,0 +1,89 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +type modifyingRuntimeWrapper struct { + logger logger.Interface + runtime Runtime + ociSpec Spec + modifier SpecModifier +} + +var _ Runtime = (*modifyingRuntimeWrapper)(nil) + +// NewModifyingRuntimeWrapper creates a runtime wrapper that applies the specified modifier to the OCI specification +// before invoking the wrapped runtime. If the modifier is nil, the input runtime is returned. +func NewModifyingRuntimeWrapper(logger logger.Interface, runtime Runtime, spec Spec, modifier SpecModifier) Runtime { + if modifier == nil { + logger.Tracef("Using low-level runtime with no modification") + return runtime + } + + rt := modifyingRuntimeWrapper{ + logger: logger, + runtime: runtime, + ociSpec: spec, + modifier: modifier, + } + return &rt +} + +// Exec checks whether a modification of the OCI specification is required and modifies it accordingly before exec-ing +// into the wrapped runtime. +func (r *modifyingRuntimeWrapper) Exec(args []string) error { + if HasCreateSubcommand(args) { + r.logger.Debugf("Create command detected; applying OCI specification modifications") + err := r.modify() + if err != nil { + return fmt.Errorf("could not apply required modification to OCI specification: %w", err) + } + r.logger.Debugf("Applied required modification to OCI specification") + } + + r.logger.Debugf("Forwarding command to runtime %v", r.runtime.String()) + return r.runtime.Exec(args) +} + +// modify loads, modifies, and flushes the OCI specification using the defined Modifier +func (r *modifyingRuntimeWrapper) modify() error { + _, err := r.ociSpec.Load() + if err != nil { + return fmt.Errorf("error loading OCI specification for modification: %v", err) + } + + err = r.ociSpec.Modify(r.modifier) + if err != nil { + return fmt.Errorf("error modifying OCI spec: %v", err) + } + + err = r.ociSpec.Flush() + if err != nil { + return fmt.Errorf("error writing modified OCI specification: %v", err) + } + return nil +} + +// String returns a string representation of the runtime. +func (r *modifyingRuntimeWrapper) String() string { + return fmt.Sprintf("modify on-create and forward to %s", r.runtime.String()) +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_path.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_path.go new file mode 100644 index 00000000..8c15a107 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_path.go @@ -0,0 +1,70 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + "os" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +// pathRuntime wraps the path that a binary and defines the semantics for how to exec into it. +// This can be used to wrap an OCI-compliant low-level runtime binary, allowing it to be used through the +// Runtime internface. +type pathRuntime struct { + logger logger.Interface + path string + execRuntime Runtime +} + +var _ Runtime = (*pathRuntime)(nil) + +// NewRuntimeForPath creates a Runtime for the specified logger and path +func NewRuntimeForPath(logger logger.Interface, path string) (Runtime, error) { + info, err := os.Stat(path) + if err != nil { + return nil, fmt.Errorf("invalid path '%v': %v", path, err) + } + if info.IsDir() || info.Mode()&0111 == 0 { + return nil, fmt.Errorf("specified path '%v' is not an executable file", path) + } + + shim := pathRuntime{ + logger: logger, + path: path, + execRuntime: syscallExec{}, + } + + return &shim, nil +} + +// Exec exces into the binary at the path from the pathRuntime struct, passing it the supplied arguments +// after ensuring that the first argument is the path of the target binary. +func (s pathRuntime) Exec(args []string) error { + runtimeArgs := []string{s.path} + if len(args) > 1 { + runtimeArgs = append(runtimeArgs, args[1:]...) + } + + return s.execRuntime.Exec(runtimeArgs) +} + +// String returns the path to the specified runtime as the string representation. +func (s pathRuntime) String() string { + return s.path +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_syscall_exec.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_syscall_exec.go new file mode 100644 index 00000000..349edf86 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/runtime_syscall_exec.go @@ -0,0 +1,43 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + "os" + "syscall" +) + +type syscallExec struct{} + +var _ Runtime = (*syscallExec)(nil) + +func (r syscallExec) Exec(args []string) error { + //nolint:gosec // TODO: Can we harden this so that there is less risk of command injection + err := syscall.Exec(args[0], args, os.Environ()) + if err != nil { + return fmt.Errorf("could not exec '%v': %v", args[0], err) + } + + // syscall.Exec is not expected to return. This is an error state regardless of whether + // err is nil or not. + return fmt.Errorf("unexpected return from exec '%v'", args[0]) +} + +func (r syscallExec) String() string { + return "exec" +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec.go new file mode 100644 index 00000000..e95ea1cf --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec.go @@ -0,0 +1,59 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "fmt" + + "github.com/opencontainers/runtime-spec/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +// SpecModifier defines an interface for modifying a (raw) OCI spec +type SpecModifier interface { + // Modify is a method that accepts a pointer to an OCI Spec and returns an + // error. The intention is that the function would modify the spec in-place. + Modify(*specs.Spec) error +} + +// Spec defines the operations to be performed on an OCI specification +// +//go:generate moq -stub -out spec_mock.go . Spec +type Spec interface { + Load() (*specs.Spec, error) + Flush() error + Modify(SpecModifier) error + LookupEnv(string) (string, bool) +} + +// NewSpec creates fileSpec based on the command line arguments passed to the +// application using the specified logger. +func NewSpec(logger logger.Interface, args []string) (Spec, error) { + bundleDir, err := GetBundleDir(args) + if err != nil { + return nil, fmt.Errorf("error getting bundle directory: %v", err) + } + logger.Debugf("Using bundle directory: %v", bundleDir) + + ociSpecPath := GetSpecFilePath(bundleDir) + logger.Infof("Using OCI specification file path: %v", ociSpecPath) + + ociSpec := NewFileSpec(ociSpecPath) + + return ociSpec, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_file.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_file.go new file mode 100644 index 00000000..8784ae92 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_file.go @@ -0,0 +1,111 @@ +/* +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +*/ + +package oci + +import ( + "encoding/json" + "fmt" + "io" + "os" + + "github.com/opencontainers/runtime-spec/specs-go" +) + +type fileSpec struct { + memorySpec + path string +} + +var _ Spec = (*fileSpec)(nil) + +// NewFileSpec creates an object that encapsulates a file-backed OCI spec. +// This can be used to read from the file, modify the spec, and write to the +// same file. +func NewFileSpec(filepath string) Spec { + oci := fileSpec{ + path: filepath, + } + + return &oci +} + +// Load reads the contents of an OCI spec from file to be referenced internally. +// The file is opened "read-only" +func (s *fileSpec) Load() (*specs.Spec, error) { + specFile, err := os.Open(s.path) + if err != nil { + return nil, fmt.Errorf("error opening OCI specification file: %v", err) + } + defer specFile.Close() + + spec, err := LoadFrom(specFile) + if err != nil { + return nil, fmt.Errorf("error loading OCI specification from file: %v", err) + } + s.Spec = spec + return s.Spec, nil +} + +// LoadFrom reads the contents of the OCI spec from the specified io.Reader. +func LoadFrom(reader io.Reader) (*specs.Spec, error) { + decoder := json.NewDecoder(reader) + + var spec specs.Spec + + err := decoder.Decode(&spec) + if err != nil { + return nil, fmt.Errorf("error reading OCI specification: %v", err) + } + + return &spec, nil +} + +// Modify applies the specified SpecModifier to the stored OCI specification. +func (s *fileSpec) Modify(m SpecModifier) error { + return s.memorySpec.Modify(m) +} + +// Flush writes the stored OCI specification to the filepath specified by the path member. +// The file is truncated upon opening, overwriting any existing contents. +func (s fileSpec) Flush() error { + if s.Spec == nil { + return fmt.Errorf("no OCI specification loaded") + } + + specFile, err := os.Create(s.path) + if err != nil { + return fmt.Errorf("error opening OCI specification file: %v", err) + } + defer specFile.Close() + + return flushTo(s.Spec, specFile) +} + +// flushTo writes the stored OCI specification to the specified io.Writer. +func flushTo(spec *specs.Spec, writer io.Writer) error { + if spec == nil { + return nil + } + encoder := json.NewEncoder(writer) + + err := encoder.Encode(spec) + if err != nil { + return fmt.Errorf("error writing OCI specification: %v", err) + } + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_memory.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_memory.go new file mode 100644 index 00000000..478db5a2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_memory.go @@ -0,0 +1,83 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package oci + +import ( + "fmt" + "strings" + + "github.com/opencontainers/runtime-spec/specs-go" +) + +type memorySpec struct { + *specs.Spec +} + +// NewMemorySpec creates a Spec instance from the specified OCI spec +func NewMemorySpec(spec *specs.Spec) Spec { + s := memorySpec{ + Spec: spec, + } + + return &s +} + +// Load is a no-op for the memorySpec spec +func (s *memorySpec) Load() (*specs.Spec, error) { + return s.Spec, nil +} + +// Flush is a no-op for the memorySpec spec +func (s *memorySpec) Flush() error { + return nil +} + +// Modify applies the specified SpecModifier to the stored OCI specification. +func (s *memorySpec) Modify(m SpecModifier) error { + if s.Spec == nil { + return fmt.Errorf("cannot modify nil spec") + } + return m.Modify(s.Spec) +} + +// LookupEnv mirrors os.LookupEnv for the OCI specification. It +// retrieves the value of the environment variable named +// by the key. If the variable is present in the environment the +// value (which may be empty) is returned and the boolean is true. +// Otherwise the returned value will be empty and the boolean will +// be false. +func (s memorySpec) LookupEnv(key string) (string, bool) { + if s.Spec == nil || s.Spec.Process == nil { + return "", false + } + + for _, env := range s.Spec.Process.Env { + if !strings.HasPrefix(env, key) { + continue + } + + parts := strings.SplitN(env, "=", 2) + if parts[0] == key { + if len(parts) < 2 { + return "", true + } + return parts[1], true + } + } + + return "", false +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_mock.go new file mode 100644 index 00000000..f004d69c --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/spec_mock.go @@ -0,0 +1,208 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package oci + +import ( + "sync" + + "github.com/opencontainers/runtime-spec/specs-go" +) + +// Ensure, that SpecMock does implement Spec. +// If this is not the case, regenerate this file with moq. +var _ Spec = &SpecMock{} + +// SpecMock is a mock implementation of Spec. +// +// func TestSomethingThatUsesSpec(t *testing.T) { +// +// // make and configure a mocked Spec +// mockedSpec := &SpecMock{ +// FlushFunc: func() error { +// panic("mock out the Flush method") +// }, +// LoadFunc: func() (*specs.Spec, error) { +// panic("mock out the Load method") +// }, +// LookupEnvFunc: func(s string) (string, bool) { +// panic("mock out the LookupEnv method") +// }, +// ModifyFunc: func(specModifier SpecModifier) error { +// panic("mock out the Modify method") +// }, +// } +// +// // use mockedSpec in code that requires Spec +// // and then make assertions. +// +// } +type SpecMock struct { + // FlushFunc mocks the Flush method. + FlushFunc func() error + + // LoadFunc mocks the Load method. + LoadFunc func() (*specs.Spec, error) + + // LookupEnvFunc mocks the LookupEnv method. + LookupEnvFunc func(s string) (string, bool) + + // ModifyFunc mocks the Modify method. + ModifyFunc func(specModifier SpecModifier) error + + // calls tracks calls to the methods. + calls struct { + // Flush holds details about calls to the Flush method. + Flush []struct { + } + // Load holds details about calls to the Load method. + Load []struct { + } + // LookupEnv holds details about calls to the LookupEnv method. + LookupEnv []struct { + // S is the s argument value. + S string + } + // Modify holds details about calls to the Modify method. + Modify []struct { + // SpecModifier is the specModifier argument value. + SpecModifier SpecModifier + } + } + lockFlush sync.RWMutex + lockLoad sync.RWMutex + lockLookupEnv sync.RWMutex + lockModify sync.RWMutex +} + +// Flush calls FlushFunc. +func (mock *SpecMock) Flush() error { + callInfo := struct { + }{} + mock.lockFlush.Lock() + mock.calls.Flush = append(mock.calls.Flush, callInfo) + mock.lockFlush.Unlock() + if mock.FlushFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.FlushFunc() +} + +// FlushCalls gets all the calls that were made to Flush. +// Check the length with: +// +// len(mockedSpec.FlushCalls()) +func (mock *SpecMock) FlushCalls() []struct { +} { + var calls []struct { + } + mock.lockFlush.RLock() + calls = mock.calls.Flush + mock.lockFlush.RUnlock() + return calls +} + +// Load calls LoadFunc. +func (mock *SpecMock) Load() (*specs.Spec, error) { + callInfo := struct { + }{} + mock.lockLoad.Lock() + mock.calls.Load = append(mock.calls.Load, callInfo) + mock.lockLoad.Unlock() + if mock.LoadFunc == nil { + var ( + specOut *specs.Spec + errOut error + ) + return specOut, errOut + } + return mock.LoadFunc() +} + +// LoadCalls gets all the calls that were made to Load. +// Check the length with: +// +// len(mockedSpec.LoadCalls()) +func (mock *SpecMock) LoadCalls() []struct { +} { + var calls []struct { + } + mock.lockLoad.RLock() + calls = mock.calls.Load + mock.lockLoad.RUnlock() + return calls +} + +// LookupEnv calls LookupEnvFunc. +func (mock *SpecMock) LookupEnv(s string) (string, bool) { + callInfo := struct { + S string + }{ + S: s, + } + mock.lockLookupEnv.Lock() + mock.calls.LookupEnv = append(mock.calls.LookupEnv, callInfo) + mock.lockLookupEnv.Unlock() + if mock.LookupEnvFunc == nil { + var ( + sOut string + bOut bool + ) + return sOut, bOut + } + return mock.LookupEnvFunc(s) +} + +// LookupEnvCalls gets all the calls that were made to LookupEnv. +// Check the length with: +// +// len(mockedSpec.LookupEnvCalls()) +func (mock *SpecMock) LookupEnvCalls() []struct { + S string +} { + var calls []struct { + S string + } + mock.lockLookupEnv.RLock() + calls = mock.calls.LookupEnv + mock.lockLookupEnv.RUnlock() + return calls +} + +// Modify calls ModifyFunc. +func (mock *SpecMock) Modify(specModifier SpecModifier) error { + callInfo := struct { + SpecModifier SpecModifier + }{ + SpecModifier: specModifier, + } + mock.lockModify.Lock() + mock.calls.Modify = append(mock.calls.Modify, callInfo) + mock.lockModify.Unlock() + if mock.ModifyFunc == nil { + var ( + errOut error + ) + return errOut + } + return mock.ModifyFunc(specModifier) +} + +// ModifyCalls gets all the calls that were made to Modify. +// Check the length with: +// +// len(mockedSpec.ModifyCalls()) +func (mock *SpecMock) ModifyCalls() []struct { + SpecModifier SpecModifier +} { + var calls []struct { + SpecModifier SpecModifier + } + mock.lockModify.RLock() + calls = mock.calls.Modify + mock.lockModify.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/state.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/state.go new file mode 100644 index 00000000..2bb4e6e5 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/oci/state.go @@ -0,0 +1,93 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package oci + +import ( + "encoding/json" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/opencontainers/runtime-spec/specs-go" +) + +// State stores an OCI container state. This includes the spec path and the environment +type State specs.State + +// LoadContainerState loads the container state from the specified filename. If the filename is empty or '-' the state is loaded from STDIN +func LoadContainerState(filename string) (*State, error) { + if filename == "" || filename == "-" { + return ReadContainerState(os.Stdin) + } + + inputFile, err := os.Open(filename) + if err != nil { + return nil, fmt.Errorf("failed to open file: %v", err) + } + defer inputFile.Close() + + return ReadContainerState(inputFile) +} + +// ReadContainerState reads the container state from the specified reader +func ReadContainerState(reader io.Reader) (*State, error) { + var s State + + d := json.NewDecoder(reader) + if err := d.Decode(&s); err != nil { + return nil, fmt.Errorf("failed to decode container state: %v", err) + } + + return &s, nil +} + +// LoadSpec loads the OCI spec associated with the container state +func (s *State) LoadSpec() (*specs.Spec, error) { + specFilePath := GetSpecFilePath(s.Bundle) + specFile, err := os.Open(specFilePath) + if err != nil { + return nil, fmt.Errorf("failed to open OCI spec file: %v", err) + } + defer specFile.Close() + + spec, err := LoadFrom(specFile) + if err != nil { + return nil, fmt.Errorf("failed to load OCI spec: %v", err) + } + return spec, nil +} + +// GetContainerRoot returns the root for the container from the associated spec. If the spec is not yet loaded, it is +// loaded and cached. +func (s *State) GetContainerRoot() (string, error) { + spec, err := s.LoadSpec() + if err != nil { + return "", err + } + + var containerRoot string + if spec.Root != nil { + containerRoot = spec.Root.Path + } + + if filepath.IsAbs(containerRoot) { + return containerRoot, nil + } + + return filepath.Join(s.Bundle, containerRoot), nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/by-path-hooks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/by-path-hooks.go new file mode 100644 index 00000000..cd38f5e7 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/by-path-hooks.go @@ -0,0 +1,117 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dgpu + +import ( + "fmt" + "os" + "path/filepath" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +// byPathHookDiscoverer discovers the entities required for injecting by-path DRM device links +type byPathHookDiscoverer struct { + logger logger.Interface + devRoot string + nvidiaCDIHookPath string + pciBusID string + deviceNodes discover.Discover +} + +var _ discover.Discover = (*byPathHookDiscoverer)(nil) + +// Devices returns the empty list for the by-path hook discoverer +func (d *byPathHookDiscoverer) Devices() ([]discover.Device, error) { + return nil, nil +} + +// Hooks returns the hooks for the GPU device. +// The following hooks are detected: +// 1. A hook to create /dev/dri/by-path symlinks +func (d *byPathHookDiscoverer) Hooks() ([]discover.Hook, error) { + links, err := d.deviceNodeLinks() + if err != nil { + return nil, fmt.Errorf("failed to discover DRA device links: %v", err) + } + if len(links) == 0 { + return nil, nil + } + + var args []string + for _, l := range links { + args = append(args, "--link", l) + } + + hook := discover.CreateNvidiaCDIHook( + d.nvidiaCDIHookPath, + "create-symlinks", + args..., + ) + + return []discover.Hook{hook}, nil +} + +// Mounts returns an empty slice for a full GPU +func (d *byPathHookDiscoverer) Mounts() ([]discover.Mount, error) { + return nil, nil +} + +func (d *byPathHookDiscoverer) deviceNodeLinks() ([]string, error) { + devices, err := d.deviceNodes.Devices() + if err != nil { + return nil, fmt.Errorf("failed to discover device nodes: %v", err) + } + + if len(devices) == 0 { + return nil, nil + } + + selectedDevices := make(map[string]bool) + for _, d := range devices { + selectedDevices[d.HostPath] = true + } + + candidates := []string{ + fmt.Sprintf("/dev/dri/by-path/pci-%s-card", d.pciBusID), + fmt.Sprintf("/dev/dri/by-path/pci-%s-render", d.pciBusID), + } + + var links []string + for _, c := range candidates { + linkPath := filepath.Join(d.devRoot, c) + device, err := os.Readlink(linkPath) + if err != nil { + d.logger.Warningf("Failed to evaluate symlink %v; ignoring", linkPath) + continue + } + + deviceNode := device + if !filepath.IsAbs(device) { + deviceNode = filepath.Join(filepath.Dir(linkPath), device) + } + if !selectedDevices[deviceNode] { + d.logger.Debugf("ignoring device symlink %v -> %v since %v is not mounted", linkPath, device, deviceNode) + continue + } + d.logger.Debugf("adding device symlink %v -> %v", linkPath, device) + links = append(links, fmt.Sprintf("%v::%v", device, linkPath)) + } + + return links, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/dgpu.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/dgpu.go new file mode 100644 index 00000000..de411bd6 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/dgpu.go @@ -0,0 +1,125 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dgpu + +import ( + "errors" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps" +) + +// NewForDevice creates a discoverer for the specified Device. +// nvsandboxutils is used for discovery if specified, otherwise NVML is used. +func NewForDevice(d device.Device, opts ...Option) (discover.Discover, error) { + o := new(opts...) + + var discoverers []discover.Discover + var errs error + nvsandboxutilsDiscoverer, err := o.newNvsandboxutilsDGPUDiscoverer(d) + if err != nil { + // TODO: Log a warning + errs = errors.Join(errs, err) + } else if nvsandboxutilsDiscoverer != nil { + discoverers = append(discoverers, nvsandboxutilsDiscoverer) + } + + nvmlDiscoverer, err := o.newNvmlDGPUDiscoverer(&toRequiredInfo{d}) + if err != nil { + // TODO: Log a warning + errs = errors.Join(errs, err) + } else if nvmlDiscoverer != nil { + discoverers = append(discoverers, nvmlDiscoverer) + } + + if len(discoverers) == 0 { + return nil, errs + } + + return discover.WithCache( + discover.FirstValid( + discoverers..., + ), + ), nil +} + +// NewForMigDevice creates a discoverer for the specified device and its associated MIG device. +// nvsandboxutils is used for discovery if specified, otherwise NVML is used. +func NewForMigDevice(d device.Device, mig device.MigDevice, opts ...Option) (discover.Discover, error) { + o := new(opts...) + o.isMigDevice = true + + var discoverers []discover.Discover + var errs error + nvsandboxutilsDiscoverer, err := o.newNvsandboxutilsDGPUDiscoverer(mig) + if err != nil { + // TODO: Log a warning + errs = errors.Join(errs, err) + } else if nvsandboxutilsDiscoverer != nil { + discoverers = append(discoverers, nvsandboxutilsDiscoverer) + } + + nvmlDiscoverer, err := o.newNvmlMigDiscoverer( + &toRequiredMigInfo{ + MigDevice: mig, + parent: &toRequiredInfo{d}, + }, + ) + if err != nil { + // TODO: Log a warning + errs = errors.Join(errs, err) + } else if nvmlDiscoverer != nil { + discoverers = append(discoverers, nvmlDiscoverer) + } + + if len(discoverers) == 0 { + return nil, errs + } + + return discover.WithCache( + discover.FirstValid( + discoverers..., + ), + ), nil + +} + +func new(opts ...Option) *options { + o := &options{} + for _, opt := range opts { + opt(o) + } + + if o.logger == nil { + o.logger = logger.New() + } + + if o.migCaps == nil { + migCaps, err := nvcaps.NewMigCaps() + if err != nil { + o.logger.Debugf("ignoring error getting MIG capability device paths: %v", err) + o.migCapsError = err + } else { + o.migCaps = migCaps + } + } + + return o +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvml.go new file mode 100644 index 00000000..f24f4d55 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvml.go @@ -0,0 +1,167 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dgpu + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps" +) + +type requiredInfo interface { + GetMinorNumber() (int, error) + GetPCIBusID() (string, error) + getDevNodePath() (string, error) +} + +func (o *options) newNvmlDGPUDiscoverer(d requiredInfo) (discover.Discover, error) { + path, err := d.getDevNodePath() + if err != nil { + return nil, fmt.Errorf("error getting device node path: %w", err) + } + + pciBusID, err := d.GetPCIBusID() + if err != nil { + return nil, fmt.Errorf("error getting PCI info for device: %w", err) + } + + drmDeviceNodes, err := drm.GetDeviceNodesByBusID(pciBusID) + if err != nil { + return nil, fmt.Errorf("failed to determine DRM devices for %v: %v", pciBusID, err) + } + + deviceNodePaths := append([]string{path}, drmDeviceNodes...) + + deviceNodes := discover.NewCharDeviceDiscoverer( + o.logger, + o.devRoot, + deviceNodePaths, + ) + + byPathHooks := &byPathHookDiscoverer{ + logger: o.logger, + devRoot: o.devRoot, + nvidiaCDIHookPath: o.nvidiaCDIHookPath, + pciBusID: pciBusID, + deviceNodes: deviceNodes, + } + + dd := discover.Merge( + deviceNodes, + byPathHooks, + ) + return dd, nil +} + +type requiredMigInfo interface { + getPlacementInfo() (int, int, int, error) + getDevNodePath() (string, error) +} + +func (o *options) newNvmlMigDiscoverer(d requiredMigInfo) (discover.Discover, error) { + if o.migCaps == nil || o.migCapsError != nil { + return nil, fmt.Errorf("error getting MIG capability device paths: %v", o.migCapsError) + } + + gpu, gi, ci, err := d.getPlacementInfo() + if err != nil { + return nil, fmt.Errorf("error getting placement info: %w", err) + } + + giCap := nvcaps.NewGPUInstanceCap(gpu, gi) + giCapDevicePath, err := o.migCaps.GetCapDevicePath(giCap) + if err != nil { + return nil, fmt.Errorf("failed to get GI cap device path: %v", err) + } + + ciCap := nvcaps.NewComputeInstanceCap(gpu, gi, ci) + ciCapDevicePath, err := o.migCaps.GetCapDevicePath(ciCap) + if err != nil { + return nil, fmt.Errorf("failed to get CI cap device path: %v", err) + } + + parentPath, err := d.getDevNodePath() + if err != nil { + return nil, err + } + + deviceNodes := discover.NewCharDeviceDiscoverer( + o.logger, + o.devRoot, + []string{ + parentPath, + giCapDevicePath, + ciCapDevicePath, + }, + ) + + return deviceNodes, nil +} + +type toRequiredInfo struct { + device.Device +} + +func (d *toRequiredInfo) GetMinorNumber() (int, error) { + minor, ret := d.Device.GetMinorNumber() + if ret != nvml.SUCCESS { + return 0, ret + } + return minor, nil +} + +func (d *toRequiredInfo) getDevNodePath() (string, error) { + minor, err := d.GetMinorNumber() + if err != nil { + return "", fmt.Errorf("error getting GPU device minor number: %w", err) + } + path := fmt.Sprintf("/dev/nvidia%d", minor) + return path, nil +} + +type toRequiredMigInfo struct { + device.MigDevice + parent requiredInfo +} + +func (d *toRequiredMigInfo) getPlacementInfo() (int, int, int, error) { + gpu, err := d.parent.GetMinorNumber() + if err != nil { + return 0, 0, 0, fmt.Errorf("error getting GPU minor: %w", err) + } + + gi, ret := d.GetGpuInstanceId() + if ret != nvml.SUCCESS { + return 0, 0, 0, fmt.Errorf("error getting GPU Instance ID: %v", ret) + } + + ci, ret := d.GetComputeInstanceId() + if ret != nvml.SUCCESS { + return 0, 0, 0, fmt.Errorf("error getting Compute Instance ID: %v", ret) + } + + return gpu, gi, ci, nil +} + +func (d *toRequiredMigInfo) getDevNodePath() (string, error) { + return d.parent.getDevNodePath() +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvsandboxutils.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvsandboxutils.go new file mode 100644 index 00000000..7022deab --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/nvsandboxutils.go @@ -0,0 +1,131 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dgpu + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils" +) + +type nvsandboxutilsDGPU struct { + lib nvsandboxutils.Interface + uuid string + devRoot string + isMig bool + nvidiaCDIHookPath string + deviceLinks []string +} + +var _ discover.Discover = (*nvsandboxutilsDGPU)(nil) + +type UUIDer interface { + GetUUID() (string, nvml.Return) +} + +func (o *options) newNvsandboxutilsDGPUDiscoverer(d UUIDer) (discover.Discover, error) { + if o.nvsandboxutilslib == nil { + return nil, nil + } + + uuid, nvmlRet := d.GetUUID() + if nvmlRet != nvml.SUCCESS { + return nil, fmt.Errorf("failed to get device UUID: %w", nvmlRet) + } + + nvd := nvsandboxutilsDGPU{ + lib: o.nvsandboxutilslib, + uuid: uuid, + devRoot: strings.TrimSuffix(filepath.Clean(o.devRoot), "/dev"), + isMig: o.isMigDevice, + nvidiaCDIHookPath: o.nvidiaCDIHookPath, + } + + return &nvd, nil +} + +func (d *nvsandboxutilsDGPU) Devices() ([]discover.Device, error) { + gpuFileInfos, ret := d.lib.GetGpuResource(d.uuid) + if ret != nvsandboxutils.SUCCESS { + return nil, fmt.Errorf("failed to get GPU resource: %w", ret) + } + + var devices []discover.Device + for _, info := range gpuFileInfos { + switch { + case info.SubType == nvsandboxutils.NV_DEV_DRI_CARD, info.SubType == nvsandboxutils.NV_DEV_DRI_RENDERD: + if d.isMig { + continue + } + fallthrough + case info.SubType == nvsandboxutils.NV_DEV_NVIDIA, info.SubType == nvsandboxutils.NV_DEV_NVIDIA_CAPS_NVIDIA_CAP: + containerPath := info.Path + if d.devRoot != "/" { + containerPath = strings.TrimPrefix(containerPath, d.devRoot) + } + + // TODO: Extend discover.Device with additional information. + device := discover.Device{ + HostPath: info.Path, + Path: containerPath, + } + devices = append(devices, device) + case info.SubType == nvsandboxutils.NV_DEV_DRI_CARD_SYMLINK, info.SubType == nvsandboxutils.NV_DEV_DRI_RENDERD_SYMLINK: + if d.isMig { + continue + } + if info.Flags == nvsandboxutils.NV_FILE_FLAG_CONTENT { + targetPath, ret := d.lib.GetFileContent(info.Path) + if ret != nvsandboxutils.SUCCESS { + return nil, fmt.Errorf("failed to get symlink: %w", ret) + } + d.deviceLinks = append(d.deviceLinks, fmt.Sprintf("%v::%v", targetPath, info.Path)) + } + } + } + + return devices, nil +} + +// Hooks returns a hook to create the by-path symlinks for the discovered devices. +func (d *nvsandboxutilsDGPU) Hooks() ([]discover.Hook, error) { + if len(d.deviceLinks) == 0 { + return nil, nil + } + + var args []string + for _, l := range d.deviceLinks { + args = append(args, "--link", l) + } + + hook := discover.CreateNvidiaCDIHook( + d.nvidiaCDIHookPath, + "create-symlinks", + args..., + ) + + return []discover.Hook{hook}, nil +} + +func (d *nvsandboxutilsDGPU) Mounts() ([]discover.Mount, error) { + return nil, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/options.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/options.go new file mode 100644 index 00000000..2fd1c01b --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu/options.go @@ -0,0 +1,74 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package dgpu + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils" +) + +type options struct { + logger logger.Interface + devRoot string + nvidiaCDIHookPath string + + isMigDevice bool + // migCaps stores the MIG capabilities for the system. + // If MIG is not available, this is nil. + migCaps nvcaps.MigCaps + migCapsError error + + nvsandboxutilslib nvsandboxutils.Interface +} + +type Option func(*options) + +// WithDevRoot sets the root where /dev is located. +func WithDevRoot(root string) Option { + return func(l *options) { + l.devRoot = root + } +} + +// WithLogger sets the logger for the library +func WithLogger(logger logger.Interface) Option { + return func(l *options) { + l.logger = logger + } +} + +// WithNVIDIACDIHookPath sets the path to the NVIDIA Container Toolkit CLI path for the library +func WithNVIDIACDIHookPath(path string) Option { + return func(l *options) { + l.nvidiaCDIHookPath = path + } +} + +// WithMIGCaps sets the MIG capabilities. +func WithMIGCaps(migCaps nvcaps.MigCaps) Option { + return func(l *options) { + l.migCaps = migCaps + } +} + +// WithNvsandboxuitilsLib sets the nvsandboxutils library implementation. +func WithNvsandboxuitilsLib(nvsandboxutilslib nvsandboxutils.Interface) Option { + return func(l *options) { + l.nvsandboxutilslib = nvsandboxutilslib + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv.go new file mode 100644 index 00000000..9af38d71 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv.go @@ -0,0 +1,118 @@ +/** +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package tegra + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" + "github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv" +) + +// newDiscovererFromCSVFiles creates a discoverer for the specified CSV files. A logger is also supplied. +// The constructed discoverer is comprised of a list, with each element in the list being associated with a +// single CSV files. +func (o tegraOptions) newDiscovererFromCSVFiles() (discover.Discover, error) { + if len(o.csvFiles) == 0 { + o.logger.Warningf("No CSV files specified") + return discover.None{}, nil + } + + targetsByType := getTargetsFromCSVFiles(o.logger, o.csvFiles) + + devices := discover.NewCharDeviceDiscoverer( + o.logger, + o.devRoot, + targetsByType[csv.MountSpecDev], + ) + + directories := discover.NewMounts( + o.logger, + lookup.NewDirectoryLocator(lookup.WithLogger(o.logger), lookup.WithRoot(o.driverRoot)), + o.driverRoot, + targetsByType[csv.MountSpecDir], + ) + + // We create a discoverer for mounted libraries and add additional .so + // symlinks for the driver. + libraries := discover.WithDriverDotSoSymlinks( + discover.NewMounts( + o.logger, + o.symlinkLocator, + o.driverRoot, + targetsByType[csv.MountSpecLib], + ), + "", + o.nvidiaCDIHookPath, + ) + + // We process the explicitly requested symlinks. + symlinkTargets := o.ignorePatterns.Apply(targetsByType[csv.MountSpecSym]...) + o.logger.Debugf("Filtered symlink targets: %v", symlinkTargets) + symlinks := discover.NewMounts( + o.logger, + o.symlinkLocator, + o.driverRoot, + symlinkTargets, + ) + createSymlinks := o.createCSVSymlinkHooks(symlinkTargets) + + d := discover.Merge( + devices, + directories, + libraries, + symlinks, + createSymlinks, + ) + + return d, nil +} + +// getTargetsFromCSVFiles returns the list of mount specs from the specified CSV files. +// These are aggregated by mount spec type. +// TODO: We use a function variable here to allow this to be overridden for testing. +// This should be properly mocked. +var getTargetsFromCSVFiles = func(logger logger.Interface, files []string) map[csv.MountSpecType][]string { + targetsByType := make(map[csv.MountSpecType][]string) + for _, filename := range files { + targets, err := loadCSVFile(logger, filename) + if err != nil { + logger.Warningf("Skipping CSV file %v: %v", filename, err) + continue + } + for _, t := range targets { + targetsByType[t.Type] = append(targetsByType[t.Type], t.Path) + } + } + return targetsByType +} + +// loadCSVFile loads the specified CSV file and returns the list of mount specs +func loadCSVFile(logger logger.Interface, filename string) ([]*csv.MountSpec, error) { + // Create a discoverer for each file-kind combination + targets, err := csv.NewCSVFileParser(logger, filename).Parse() + if err != nil { + return nil, fmt.Errorf("failed to parse CSV file: %v", err) + } + if len(targets) == 0 { + return nil, fmt.Errorf("CSV file is empty") + } + + return targets, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/csv.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/csv.go new file mode 100644 index 00000000..c4f6f495 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/csv.go @@ -0,0 +1,147 @@ +/** +# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package csv + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "path/filepath" + "strings" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +const ( + // DefaultMountSpecPath is default location of CSV files that define the modifications required to the OCI spec + DefaultMountSpecPath = "/etc/nvidia-container-runtime/host-files-for-container.d" +) + +// DefaultFileList returns the list of CSV files that are used by default. +func DefaultFileList() []string { + files := []string{ + "devices.csv", + "drivers.csv", + "l4t.csv", + } + + var paths []string + for _, file := range files { + paths = append(paths, filepath.Join(DefaultMountSpecPath, file)) + } + + return paths +} + +// GetFileList returns the (non-recursive) list of CSV files in the specified +// folder +func GetFileList(root string) ([]string, error) { + contents, err := os.ReadDir(root) + if err != nil && errors.Is(err, os.ErrNotExist) { + return nil, nil + } else if err != nil { + return nil, fmt.Errorf("failed to read the contents of %v: %v", root, err) + } + + var csvFilePaths []string + for _, c := range contents { + if c.IsDir() { + continue + } + if c.Name() == ".csv" { + continue + } + ext := strings.ToLower(filepath.Ext(c.Name())) + if ext != ".csv" { + continue + } + + csvFilePaths = append(csvFilePaths, filepath.Join(root, c.Name())) + } + + return csvFilePaths, nil +} + +// BaseFilesOnly filters out non-base CSV files from the list of CSV files. +func BaseFilesOnly(filenames []string) []string { + filter := map[string]bool{ + "l4t.csv": true, + "drivers.csv": true, + "devices.csv": true, + } + + var selected []string + for _, file := range filenames { + base := filepath.Base(file) + if filter[base] { + selected = append(selected, file) + } + } + + return selected +} + +// Parser specifies an interface for parsing MountSpecs +type Parser interface { + Parse() ([]*MountSpec, error) +} + +type csv struct { + logger logger.Interface + filename string +} + +// NewCSVFileParser creates a new parser for reading MountSpecs from the specified CSV file +func NewCSVFileParser(logger logger.Interface, filename string) Parser { + p := csv{ + logger: logger, + filename: filename, + } + + return &p +} + +// Parse parses the csv file and returns a list of MountSpecs in the file +func (p csv) Parse() ([]*MountSpec, error) { + reader, err := os.Open(p.filename) + if err != nil { + return nil, fmt.Errorf("failed to open %v for reading: %v", p.filename, err) + } + defer reader.Close() + + return p.parseFromReader(reader), nil +} + +// parseFromReader parses the specified file and returns a list of required jetson mounts +func (p csv) parseFromReader(reader io.Reader) []*MountSpec { + var targets []*MountSpec + + scanner := bufio.NewScanner(reader) + for scanner.Scan() { + line := scanner.Text() + target, err := NewMountSpecFromLine(line) + if err != nil { + p.logger.Debugf("Skipping invalid mount spec '%v': %v", line, err) + continue + } + targets = append(targets, target) + } + + return targets +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/mount_spec.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/mount_spec.go new file mode 100644 index 00000000..3ab5f9bf --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv/mount_spec.go @@ -0,0 +1,74 @@ +/** +# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package csv + +import ( + "fmt" + "strings" +) + +// MountSpecType defines the mount types allowed in a CSV file +type MountSpecType string + +const ( + // MountSpecDev is used for character devices + MountSpecDev = MountSpecType("dev") + // MountSpecDir is used for directories + MountSpecDir = MountSpecType("dir") + // MountSpecLib is used for libraries or regular files + MountSpecLib = MountSpecType("lib") + // MountSpecSym is used for symlinks. + MountSpecSym = MountSpecType("sym") +) + +// MountSpec represents a Jetson mount consisting of a type and a path. +type MountSpec struct { + Type MountSpecType + Path string +} + +// NewMountSpecFromLine parses the specified line and returns the MountSpec or an error if the line is malformed +func NewMountSpecFromLine(line string) (*MountSpec, error) { + parts := strings.SplitN(strings.TrimSpace(line), ",", 2) + if len(parts) < 2 { + return nil, fmt.Errorf("failed to parse line: %v", line) + } + mountType := strings.TrimSpace(parts[0]) + path := strings.TrimSpace(parts[1]) + + return NewMountSpec(mountType, path) +} + +// NewMountSpec creates a MountSpec with the specified type and path. An error is returned if the type is invalid. +func NewMountSpec(mountType string, path string) (*MountSpec, error) { + mt := MountSpecType(mountType) + switch mt { + case MountSpecDev, MountSpecLib, MountSpecSym, MountSpecDir: + default: + return nil, fmt.Errorf("unexpected mount type: %v", mt) + } + if path == "" { + return nil, fmt.Errorf("invalid path: %v", path) + } + + mount := MountSpec{ + Type: mt, + Path: path, + } + + return &mount, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/filter.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/filter.go new file mode 100644 index 00000000..03b18bf7 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/filter.go @@ -0,0 +1,49 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package tegra + +import ( + "path/filepath" + "strings" +) + +type ignoreMountSpecPatterns []string + +func (d ignoreMountSpecPatterns) Match(name string) bool { + for _, pattern := range d { + target := name + if strings.HasPrefix(pattern, "**/") { + target = filepath.Base(name) + pattern = strings.TrimPrefix(pattern, "**/") + } + if match, _ := filepath.Match(pattern, target); match { + return true + } + } + return false +} + +func (d ignoreMountSpecPatterns) Apply(input ...string) []string { + var filtered []string + for _, name := range input { + if d.Match(name) { + continue + } + filtered = append(filtered, name) + } + return filtered +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/symlinks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/symlinks.go new file mode 100644 index 00000000..cc677638 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/symlinks.go @@ -0,0 +1,96 @@ +/** +# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package tegra + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +type symlinkHook struct { + discover.None + logger logger.Interface + nvidiaCDIHookPath string + targets []string + + // The following can be overridden for testing + symlinkChainLocator lookup.Locator + resolveSymlink func(string) (string, error) +} + +// createCSVSymlinkHooks creates a discoverer for a hook that creates required symlinks in the container +func (o tegraOptions) createCSVSymlinkHooks(targets []string) discover.Discover { + return symlinkHook{ + logger: o.logger, + nvidiaCDIHookPath: o.nvidiaCDIHookPath, + targets: targets, + symlinkChainLocator: o.symlinkChainLocator, + resolveSymlink: o.resolveSymlink, + } +} + +// Hooks returns a hook to create the symlinks from the required CSV files +func (d symlinkHook) Hooks() ([]discover.Hook, error) { + return discover.CreateCreateSymlinkHook( + d.nvidiaCDIHookPath, + d.getCSVFileSymlinks(), + ).Hooks() +} + +// getSymlinkCandidates returns a list of symlinks that are candidates for being created. +func (d symlinkHook) getSymlinkCandidates() []string { + var candidates []string + for _, target := range d.targets { + reslovedSymlinkChain, err := d.symlinkChainLocator.Locate(target) + if err != nil { + d.logger.Warningf("Failed to locate symlink %v", target) + continue + } + candidates = append(candidates, reslovedSymlinkChain...) + } + return candidates +} + +func (d symlinkHook) getCSVFileSymlinks() []string { + var links []string + created := make(map[string]bool) + // candidates is a list of absolute paths to symlinks in a chain, or the final target of the chain. + for _, candidate := range d.getSymlinkCandidates() { + target, err := d.resolveSymlink(candidate) + if err != nil { + d.logger.Debugf("Skipping invalid link: %v", err) + continue + } else if target == candidate { + d.logger.Debugf("%v is not a symlink", candidate) + continue + } + + link := fmt.Sprintf("%v::%v", target, candidate) + if created[link] { + d.logger.Debugf("skipping duplicate link: %v", link) + continue + } + created[link] = true + + links = append(links, link) + } + + return links +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/tegra.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/tegra.go new file mode 100644 index 00000000..1031fc72 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/tegra.go @@ -0,0 +1,162 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package tegra + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks" +) + +type tegraOptions struct { + logger logger.Interface + csvFiles []string + driverRoot string + devRoot string + nvidiaCDIHookPath string + ldconfigPath string + librarySearchPaths []string + ignorePatterns ignoreMountSpecPatterns + + // The following can be overridden for testing + symlinkLocator lookup.Locator + symlinkChainLocator lookup.Locator + // TODO: This should be replaced by a regular mock + resolveSymlink func(string) (string, error) +} + +// Option defines a functional option for configuring a Tegra discoverer. +type Option func(*tegraOptions) + +// New creates a new tegra discoverer using the supplied options. +func New(opts ...Option) (discover.Discover, error) { + o := &tegraOptions{} + for _, opt := range opts { + opt(o) + } + + if o.devRoot == "" { + o.devRoot = o.driverRoot + } + + if o.symlinkLocator == nil { + o.symlinkLocator = lookup.NewSymlinkLocator( + lookup.WithLogger(o.logger), + lookup.WithRoot(o.driverRoot), + lookup.WithSearchPaths(append(o.librarySearchPaths, "/")...), + ) + } + + if o.symlinkChainLocator == nil { + o.symlinkChainLocator = lookup.NewSymlinkChainLocator( + lookup.WithLogger(o.logger), + lookup.WithRoot(o.driverRoot), + ) + } + + if o.resolveSymlink == nil { + o.resolveSymlink = symlinks.Resolve + } + + csvDiscoverer, err := o.newDiscovererFromCSVFiles() + if err != nil { + return nil, fmt.Errorf("failed to create CSV discoverer: %v", err) + } + + ldcacheUpdateHook, err := discover.NewLDCacheUpdateHook(o.logger, csvDiscoverer, o.nvidiaCDIHookPath, o.ldconfigPath) + if err != nil { + return nil, fmt.Errorf("failed to create ldcach update hook discoverer: %v", err) + } + + tegraSystemMounts := discover.NewMounts( + o.logger, + lookup.NewFileLocator(lookup.WithLogger(o.logger)), + "", + []string{ + "/etc/nv_tegra_release", + }, + ) + + d := discover.Merge( + csvDiscoverer, + // The ldcacheUpdateHook is added last to ensure that the created symlinks are included + ldcacheUpdateHook, + tegraSystemMounts, + ) + + return d, nil +} + +// WithLogger sets the logger for the discoverer. +func WithLogger(logger logger.Interface) Option { + return func(o *tegraOptions) { + o.logger = logger + } +} + +// WithDriverRoot sets the driver root for the discoverer. +func WithDriverRoot(driverRoot string) Option { + return func(o *tegraOptions) { + o.driverRoot = driverRoot + } +} + +// WithDevRoot sets the /dev root. +// If this is unset, the driver root is assumed. +func WithDevRoot(devRoot string) Option { + return func(o *tegraOptions) { + o.devRoot = devRoot + } +} + +// WithCSVFiles sets the CSV files for the discoverer. +func WithCSVFiles(csvFiles []string) Option { + return func(o *tegraOptions) { + o.csvFiles = csvFiles + } +} + +// WithNVIDIACDIHookPath sets the path to the nvidia-cdi-hook binary. +func WithNVIDIACDIHookPath(nvidiaCDIHookPath string) Option { + return func(o *tegraOptions) { + o.nvidiaCDIHookPath = nvidiaCDIHookPath + } +} + +// WithLdconfigPath sets the path to the ldconfig program +func WithLdconfigPath(ldconfigPath string) Option { + return func(o *tegraOptions) { + o.ldconfigPath = ldconfigPath + } +} + +// WithLibrarySearchPaths sets the library search paths for the discoverer. +func WithLibrarySearchPaths(librarySearchPaths ...string) Option { + return func(o *tegraOptions) { + o.librarySearchPaths = librarySearchPaths + } +} + +// WithIngorePatterns sets patterns to ignore in the CSV files +func WithIngorePatterns(ignorePatterns ...string) Option { + return func(o *tegraOptions) { + o.ignorePatterns = ignoreMountSpecPatterns(ignorePatterns) + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/api.go new file mode 100644 index 00000000..608928ef --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/api.go @@ -0,0 +1,65 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +const ( + // ModeAuto configures the CDI spec generator to automatically detect the system configuration + ModeAuto = "auto" + // ModeNvml configures the CDI spec generator to use the NVML library. + ModeNvml = "nvml" + // ModeWsl configures the CDI spec generator to generate a WSL spec. + ModeWsl = "wsl" + // ModeManagement configures the CDI spec generator to generate a management spec. + ModeManagement = "management" + // ModeGds configures the CDI spec generator to generate a GDS spec. + ModeGds = "gds" + // ModeMofed configures the CDI spec generator to generate a MOFED spec. + ModeMofed = "mofed" + // ModeCSV configures the CDI spec generator to generate a spec based on the contents of CSV + // mountspec files. + ModeCSV = "csv" +) + +// Interface defines the API for the nvcdi package +type Interface interface { + GetSpec() (spec.Interface, error) + GetCommonEdits() (*cdi.ContainerEdits, error) + GetAllDeviceSpecs() ([]specs.Device, error) + GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) + GetGPUDeviceSpecs(int, device.Device) ([]specs.Device, error) + GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) + GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) + GetDeviceSpecsByID(...string) ([]specs.Device, error) +} + +// A HookName refers to one of the predefined set of CDI hooks that may be +// included in the generated CDI specification. +type HookName string + +const ( + // HookEnableCudaCompat refers to the hook used to enable CUDA Forward Compatibility. + // This was added with v1.17.5 of the NVIDIA Container Toolkit. + HookEnableCudaCompat = HookName("enable-cuda-compat") +) diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/common-nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/common-nvml.go new file mode 100644 index 00000000..6e9661cb --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/common-nvml.go @@ -0,0 +1,56 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" +) + +// newCommonNVMLDiscoverer returns a discoverer for entities that are not associated with a specific CDI device. +// This includes driver libraries and meta devices, for example. +func (l *nvmllib) newCommonNVMLDiscoverer() (discover.Discover, error) { + metaDevices := discover.NewCharDeviceDiscoverer( + l.logger, + l.devRoot, + []string{ + "/dev/nvidia-modeset", + "/dev/nvidia-uvm-tools", + "/dev/nvidia-uvm", + "/dev/nvidiactl", + }, + ) + + graphicsMounts, err := discover.NewGraphicsMountsDiscoverer(l.logger, l.driver, l.nvidiaCDIHookPath) + if err != nil { + l.logger.Warningf("failed to create discoverer for graphics mounts: %v", err) + } + + driverFiles, err := l.NewDriverDiscoverer() + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for driver files: %v", err) + } + + d := discover.Merge( + metaDevices, + graphicsMounts, + driverFiles, + ) + + return d, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/device-wsl.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/device-wsl.go new file mode 100644 index 00000000..0f9e1ffd --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/device-wsl.go @@ -0,0 +1,37 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +const ( + dxgDeviceNode = "/dev/dxg" +) + +// newDXGDeviceDiscoverer returns a Discoverer for DXG devices under WSL2. +func newDXGDeviceDiscoverer(logger logger.Interface, devRoot string) discover.Discover { + deviceNodes := discover.NewCharDeviceDiscoverer( + logger, + devRoot, + []string{dxgDeviceNode}, + ) + + return deviceNodes +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-nvml.go new file mode 100644 index 00000000..f49f1129 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-nvml.go @@ -0,0 +1,240 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + "os" + "path/filepath" + "strings" + + "github.com/NVIDIA/go-nvml/pkg/nvml" + "golang.org/x/sys/unix" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root" +) + +// NewDriverDiscoverer creates a discoverer for the libraries and binaries associated with a driver installation. +// The supplied NVML Library is used to query the expected driver version. +func (l *nvmllib) NewDriverDiscoverer() (discover.Discover, error) { + if r := l.nvmllib.Init(); r != nvml.SUCCESS { + return nil, fmt.Errorf("failed to initialize NVML: %v", r) + } + defer func() { + if r := l.nvmllib.Shutdown(); r != nvml.SUCCESS { + l.logger.Warningf("failed to shutdown NVML: %v", r) + } + }() + + version, r := l.nvmllib.SystemGetDriverVersion() + if r != nvml.SUCCESS { + return nil, fmt.Errorf("failed to determine driver version: %v", r) + } + + return (*nvcdilib)(l).newDriverVersionDiscoverer(version) +} + +func (l *nvcdilib) newDriverVersionDiscoverer(version string) (discover.Discover, error) { + libraries, err := l.NewDriverLibraryDiscoverer(version) + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for driver libraries: %v", err) + } + + ipcs, err := discover.NewIPCDiscoverer(l.logger, l.driver.Root) + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for IPC sockets: %v", err) + } + + firmwares, err := NewDriverFirmwareDiscoverer(l.logger, l.driver.Root, version) + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for GSP firmware: %v", err) + } + + binaries := NewDriverBinariesDiscoverer(l.logger, l.driver.Root) + + d := discover.Merge( + libraries, + ipcs, + firmwares, + binaries, + ) + + return d, nil +} + +// NewDriverLibraryDiscoverer creates a discoverer for the libraries associated with the specified driver version. +func (l *nvcdilib) NewDriverLibraryDiscoverer(version string) (discover.Discover, error) { + libraryPaths, err := getVersionLibs(l.logger, l.driver, version) + if err != nil { + return nil, fmt.Errorf("failed to get libraries for driver version: %v", err) + } + + libraries := discover.NewMounts( + l.logger, + lookup.NewFileLocator( + lookup.WithLogger(l.logger), + lookup.WithRoot(l.driver.Root), + ), + l.driver.Root, + libraryPaths, + ) + + var discoverers []discover.Discover + + driverDotSoSymlinksDiscoverer := discover.WithDriverDotSoSymlinks( + libraries, + version, + l.nvidiaCDIHookPath, + ) + discoverers = append(discoverers, driverDotSoSymlinksDiscoverer) + + if l.HookIsSupported(HookEnableCudaCompat) { + // TODO: The following should use the version directly. + cudaCompatLibHookDiscoverer := discover.NewCUDACompatHookDiscoverer(l.logger, l.nvidiaCDIHookPath, l.driver) + discoverers = append(discoverers, cudaCompatLibHookDiscoverer) + } + + updateLDCache, _ := discover.NewLDCacheUpdateHook(l.logger, libraries, l.nvidiaCDIHookPath, l.ldconfigPath) + discoverers = append(discoverers, updateLDCache) + + d := discover.Merge(discoverers...) + + return d, nil +} + +func getUTSRelease() (string, error) { + utsname := &unix.Utsname{} + if err := unix.Uname(utsname); err != nil { + return "", err + } + return unix.ByteSliceToString(utsname.Release[:]), nil +} + +func getFirmwareSearchPaths(logger logger.Interface) ([]string, error) { + + var firmwarePaths []string + if p := getCustomFirmwareClassPath(logger); p != "" { + logger.Debugf("using custom firmware class path: %s", p) + firmwarePaths = append(firmwarePaths, p) + } + + utsRelease, err := getUTSRelease() + if err != nil { + return nil, fmt.Errorf("failed to get UTS_RELEASE: %v", err) + } + + standardPaths := []string{ + filepath.Join("/lib/firmware/updates/", utsRelease), + "/lib/firmware/updates/", + filepath.Join("/lib/firmware/", utsRelease), + "/lib/firmware/", + } + + return append(firmwarePaths, standardPaths...), nil +} + +// getCustomFirmwareClassPath returns the custom firmware class path if it exists. +func getCustomFirmwareClassPath(logger logger.Interface) string { + customFirmwareClassPath, err := os.ReadFile("/sys/module/firmware_class/parameters/path") + if err != nil { + logger.Warningf("failed to get custom firmware class path: %v", err) + return "" + } + + return strings.TrimSpace(string(customFirmwareClassPath)) +} + +// NewDriverFirmwareDiscoverer creates a discoverer for GSP firmware associated with the specified driver version. +func NewDriverFirmwareDiscoverer(logger logger.Interface, driverRoot string, version string) (discover.Discover, error) { + gspFirmwareSearchPaths, err := getFirmwareSearchPaths(logger) + if err != nil { + return nil, fmt.Errorf("failed to get firmware search paths: %v", err) + } + gspFirmwarePaths := filepath.Join("nvidia", version, "gsp*.bin") + return discover.NewMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithRoot(driverRoot), + lookup.WithSearchPaths(gspFirmwareSearchPaths...), + ), + driverRoot, + []string{gspFirmwarePaths}, + ), nil +} + +// NewDriverBinariesDiscoverer creates a discoverer for GSP firmware associated with the GPU driver. +func NewDriverBinariesDiscoverer(logger logger.Interface, driverRoot string) discover.Discover { + return discover.NewMounts( + logger, + lookup.NewExecutableLocator(logger, driverRoot), + driverRoot, + []string{ + "nvidia-smi", /* System management interface */ + "nvidia-debugdump", /* GPU coredump utility */ + "nvidia-persistenced", /* Persistence mode utility */ + "nvidia-cuda-mps-control", /* Multi process service CLI */ + "nvidia-cuda-mps-server", /* Multi process service server */ + "nvidia-imex", /* NVIDIA IMEX Daemon */ + "nvidia-imex-ctl", /* NVIDIA IMEX control */ + }, + ) +} + +// getVersionLibs checks the LDCache for libraries ending in the specified driver version. +// Although the ldcache at the specified driverRoot is queried, the paths are returned relative to this driverRoot. +// This allows the standard mount location logic to be used for resolving the mounts. +func getVersionLibs(logger logger.Interface, driver *root.Driver, version string) ([]string, error) { + logger.Infof("Using driver version %v", version) + + libCudaPaths, err := cuda.New( + driver.Libraries(), + ).Locate("." + version) + if err != nil { + return nil, fmt.Errorf("failed to locate libcuda.so.%v: %v", version, err) + } + libRoot := filepath.Dir(libCudaPaths[0]) + + libraries := lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithSearchPaths( + libRoot, + filepath.Join(libRoot, "vdpau"), + ), + lookup.WithOptional(true), + ) + + libs, err := libraries.Locate("*.so." + version) + if err != nil { + return nil, fmt.Errorf("failed to locate libraries for driver version %v: %v", version, err) + } + + if driver.Root == "/" || driver.Root == "" { + return libs, nil + } + + var relative []string + for _, l := range libs { + relative = append(relative, strings.TrimPrefix(l, driver.Root)) + } + + return relative, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-wsl.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-wsl.go new file mode 100644 index 00000000..d184d777 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/driver-wsl.go @@ -0,0 +1,141 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + "path/filepath" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup" +) + +var requiredDriverStoreFiles = []string{ + "libcuda.so.1.1", /* Core library for cuda support */ + "libcuda_loader.so", /* Core library for cuda support on WSL */ + "libnvidia-ptxjitcompiler.so.1", /* Core library for PTX Jit support */ + "libnvidia-ml.so.1", /* Core library for nvml */ + "libnvidia-ml_loader.so", /* Core library for nvml on WSL */ + "libdxcore.so", /* Core library for dxcore support */ + "libnvdxgdmal.so.1", /* dxgdmal library for cuda */ + "nvcubins.bin", /* Binary containing GPU code for cuda */ + "nvidia-smi", /* nvidia-smi binary*/ +} + +// newWSLDriverDiscoverer returns a Discoverer for WSL2 drivers. +func newWSLDriverDiscoverer(logger logger.Interface, driverRoot string, nvidiaCDIHookPath, ldconfigPath string) (discover.Discover, error) { + err := dxcore.Init() + if err != nil { + return nil, fmt.Errorf("failed to initialize dxcore: %v", err) + } + defer func() { + if err := dxcore.Shutdown(); err != nil { + logger.Warningf("failed to shutdown dxcore: %v", err) + } + }() + + driverStorePaths := dxcore.GetDriverStorePaths() + if len(driverStorePaths) == 0 { + return nil, fmt.Errorf("no driver store paths found") + } + logger.Infof("Using WSL driver store paths: %v", driverStorePaths) + + return newWSLDriverStoreDiscoverer(logger, driverRoot, nvidiaCDIHookPath, ldconfigPath, driverStorePaths) +} + +// newWSLDriverStoreDiscoverer returns a Discoverer for WSL2 drivers in the driver store associated with a dxcore adapter. +func newWSLDriverStoreDiscoverer(logger logger.Interface, driverRoot string, nvidiaCDIHookPath string, ldconfigPath string, driverStorePaths []string) (discover.Discover, error) { + var searchPaths []string + seen := make(map[string]bool) + for _, path := range driverStorePaths { + if seen[path] { + continue + } + searchPaths = append(searchPaths, path) + } + if len(searchPaths) > 1 { + logger.Warningf("Found multiple driver store paths: %v", searchPaths) + } + searchPaths = append(searchPaths, "/usr/lib/wsl/lib") + + libraries := discover.NewMounts( + logger, + lookup.NewFileLocator( + lookup.WithLogger(logger), + lookup.WithSearchPaths( + searchPaths..., + ), + lookup.WithCount(1), + ), + driverRoot, + requiredDriverStoreFiles, + ) + + symlinkHook := nvidiaSMISimlinkHook{ + logger: logger, + mountsFrom: libraries, + nvidiaCDIHookPath: nvidiaCDIHookPath, + } + + ldcacheHook, _ := discover.NewLDCacheUpdateHook(logger, libraries, nvidiaCDIHookPath, ldconfigPath) + + d := discover.Merge( + libraries, + symlinkHook, + ldcacheHook, + ) + + return d, nil +} + +type nvidiaSMISimlinkHook struct { + discover.None + logger logger.Interface + mountsFrom discover.Discover + nvidiaCDIHookPath string +} + +// Hooks returns a hook that creates a symlink to nvidia-smi in the driver store. +// On WSL2 the driver store location is used unchanged, for this reason we need +// to create a symlink from /usr/bin/nvidia-smi to the nvidia-smi binary in the +// driver store. +func (m nvidiaSMISimlinkHook) Hooks() ([]discover.Hook, error) { + mounts, err := m.mountsFrom.Mounts() + if err != nil { + return nil, fmt.Errorf("failed to discover mounts: %w", err) + } + + var target string + for _, mount := range mounts { + if filepath.Base(mount.Path) == "nvidia-smi" { + target = mount.Path + break + } + } + + if target == "" { + m.logger.Warningf("Failed to find nvidia-smi in mounts: %v", mounts) + return nil, nil + } + link := "/usr/bin/nvidia-smi" + links := []string{fmt.Sprintf("%s::%s", target, link)} + symlinkHook := discover.CreateCreateSymlinkHook(m.nvidiaCDIHookPath, links) + + return symlinkHook.Hooks() +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/full-gpu-nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/full-gpu-nvml.go new file mode 100644 index 00000000..003515ca --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/full-gpu-nvml.go @@ -0,0 +1,94 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu" +) + +// GetGPUDeviceSpecs returns the CDI device specs for the full GPU represented by 'device'. +func (l *nvmllib) GetGPUDeviceSpecs(i int, d device.Device) ([]specs.Device, error) { + edits, err := l.GetGPUDeviceEdits(d) + if err != nil { + return nil, fmt.Errorf("failed to get edits for device: %v", err) + } + + var deviceSpecs []specs.Device + names, err := l.deviceNamers.GetDeviceNames(i, convert{d}) + if err != nil { + return nil, fmt.Errorf("failed to get device name: %v", err) + } + for _, name := range names { + spec := specs.Device{ + Name: name, + ContainerEdits: *edits.ContainerEdits, + } + deviceSpecs = append(deviceSpecs, spec) + } + + return deviceSpecs, nil +} + +// GetGPUDeviceEdits returns the CDI edits for the full GPU represented by 'device'. +func (l *nvmllib) GetGPUDeviceEdits(d device.Device) (*cdi.ContainerEdits, error) { + device, err := l.newFullGPUDiscoverer(d) + if err != nil { + return nil, fmt.Errorf("failed to create device discoverer: %v", err) + } + + editsForDevice, err := edits.FromDiscoverer(device) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for device: %v", err) + } + + return editsForDevice, nil +} + +// newFullGPUDiscoverer creates a discoverer for the full GPU defined by the specified device. +func (l *nvmllib) newFullGPUDiscoverer(d device.Device) (discover.Discover, error) { + deviceNodes, err := dgpu.NewForDevice(d, + dgpu.WithDevRoot(l.devRoot), + dgpu.WithLogger(l.logger), + dgpu.WithNVIDIACDIHookPath(l.nvidiaCDIHookPath), + dgpu.WithNvsandboxuitilsLib(l.nvsandboxutilslib), + ) + if err != nil { + return nil, fmt.Errorf("failed to create device discoverer: %v", err) + } + + deviceFolderPermissionHooks := newDeviceFolderPermissionHookDiscoverer( + l.logger, + l.devRoot, + l.nvidiaCDIHookPath, + deviceNodes, + ) + + dd := discover.Merge( + deviceNodes, + deviceFolderPermissionHooks, + ) + + return dd, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/gds.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/gds.go new file mode 100644 index 00000000..915cb94a --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/gds.go @@ -0,0 +1,90 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type gdslib nvcdilib + +var _ Interface = (*gdslib)(nil) + +// GetAllDeviceSpecs returns the device specs for all available devices. +func (l *gdslib) GetAllDeviceSpecs() ([]specs.Device, error) { + discoverer, err := discover.NewGDSDiscoverer(l.logger, l.driverRoot, l.devRoot) + if err != nil { + return nil, fmt.Errorf("failed to create GPUDirect Storage discoverer: %v", err) + } + edits, err := edits.FromDiscoverer(discoverer) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for GPUDirect Storage: %v", err) + } + + deviceSpec := specs.Device{ + Name: "all", + ContainerEdits: *edits.ContainerEdits, + } + + return []specs.Device{deviceSpec}, nil +} + +// GetCommonEdits generates a CDI specification that can be used for ANY devices +func (l *gdslib) GetCommonEdits() (*cdi.ContainerEdits, error) { + return edits.FromDiscoverer(discover.None{}) +} + +// GetSpec is unsppported for the gdslib specs. +// gdslib is typically wrapped by a spec that implements GetSpec. +func (l *gdslib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("GetSpec is not supported") +} + +// GetGPUDeviceEdits is unsupported for the gdslib specs +func (l *gdslib) GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetGPUDeviceEdits is not supported") +} + +// GetGPUDeviceSpecs is unsupported for the gdslib specs +func (l *gdslib) GetGPUDeviceSpecs(int, device.Device) ([]specs.Device, error) { + return nil, fmt.Errorf("GetGPUDeviceSpecs is not supported") +} + +// GetMIGDeviceEdits is unsupported for the gdslib specs +func (l *gdslib) GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetMIGDeviceEdits is not supported") +} + +// GetMIGDeviceSpecs is unsupported for the gdslib specs +func (l *gdslib) GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) { + return nil, fmt.Errorf("GetMIGDeviceSpecs is not supported") +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +func (l *gdslib) GetDeviceSpecsByID(...string) ([]specs.Device, error) { + return nil, fmt.Errorf("GetDeviceSpecsByID is not supported") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/hooks.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/hooks.go new file mode 100644 index 00000000..a4620dc8 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/hooks.go @@ -0,0 +1,30 @@ +/** +# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +// disabledHooks allows individual hooks to be disabled. +type disabledHooks map[HookName]bool + +// HookIsSupported checks whether a hook of the specified name is supported. +// Hooks must be explicitly disabled, meaning that if no disabled hooks are +// all hooks are supported. +func (l *nvcdilib) HookIsSupported(h HookName) bool { + if len(l.disabledHooks) == 0 { + return true + } + return !l.disabledHooks[h] +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-csv.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-csv.go new file mode 100644 index 00000000..649b801a --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-csv.go @@ -0,0 +1,108 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type csvlib nvcdilib + +var _ Interface = (*csvlib)(nil) + +// GetSpec should not be called for wsllib +func (l *csvlib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("Unexpected call to csvlib.GetSpec()") +} + +// GetAllDeviceSpecs returns the device specs for all available devices. +func (l *csvlib) GetAllDeviceSpecs() ([]specs.Device, error) { + d, err := tegra.New( + tegra.WithLogger(l.logger), + tegra.WithDriverRoot(l.driverRoot), + tegra.WithDevRoot(l.devRoot), + tegra.WithNVIDIACDIHookPath(l.nvidiaCDIHookPath), + tegra.WithLdconfigPath(l.ldconfigPath), + tegra.WithCSVFiles(l.csvFiles), + tegra.WithLibrarySearchPaths(l.librarySearchPaths...), + tegra.WithIngorePatterns(l.csvIgnorePatterns...), + ) + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for CSV files: %v", err) + } + e, err := edits.FromDiscoverer(d) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for CSV files: %v", err) + } + + names, err := l.deviceNamers.GetDeviceNames(0, uuidIgnored{}) + if err != nil { + return nil, fmt.Errorf("failed to get device name: %v", err) + } + var deviceSpecs []specs.Device + for _, name := range names { + deviceSpec := specs.Device{ + Name: name, + ContainerEdits: *e.ContainerEdits, + } + deviceSpecs = append(deviceSpecs, deviceSpec) + } + + return deviceSpecs, nil +} + +// GetCommonEdits generates a CDI specification that can be used for ANY devices +func (l *csvlib) GetCommonEdits() (*cdi.ContainerEdits, error) { + d := discover.None{} + return edits.FromDiscoverer(d) +} + +// GetGPUDeviceEdits generates a CDI specification that can be used for GPU devices +func (l *csvlib) GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetGPUDeviceEdits is not supported for CSV files") +} + +// GetGPUDeviceSpecs returns the CDI device specs for the full GPU represented by 'device'. +func (l *csvlib) GetGPUDeviceSpecs(i int, d device.Device) ([]specs.Device, error) { + return nil, fmt.Errorf("GetGPUDeviceSpecs is not supported for CSV files") +} + +// GetMIGDeviceEdits generates a CDI specification that can be used for MIG devices +func (l *csvlib) GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetMIGDeviceEdits is not supported for CSV files") +} + +// GetMIGDeviceSpecs returns the CDI device specs for the full MIG represented by 'device'. +func (l *csvlib) GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) { + return nil, fmt.Errorf("GetMIGDeviceSpecs is not supported for CSV files") +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +func (l *csvlib) GetDeviceSpecsByID(...string) ([]specs.Device, error) { + return nil, fmt.Errorf("GetDeviceSpecsByID is not supported for CSV files") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-nvml.go new file mode 100644 index 00000000..01c22ff3 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-nvml.go @@ -0,0 +1,276 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + "strconv" + "strings" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "github.com/NVIDIA/go-nvml/pkg/nvml" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type nvmllib nvcdilib + +var _ Interface = (*nvmllib)(nil) + +// GetSpec should not be called for nvmllib +func (l *nvmllib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("Unexpected call to nvmllib.GetSpec()") +} + +// GetAllDeviceSpecs returns the device specs for all available devices. +func (l *nvmllib) GetAllDeviceSpecs() ([]specs.Device, error) { + var deviceSpecs []specs.Device + + if r := l.nvmllib.Init(); r != nvml.SUCCESS { + return nil, fmt.Errorf("failed to initialize NVML: %v", r) + } + defer func() { + if r := l.nvmllib.Shutdown(); r != nvml.SUCCESS { + l.logger.Warningf("failed to shutdown NVML: %v", r) + } + }() + + if l.nvsandboxutilslib != nil { + if r := l.nvsandboxutilslib.Init(l.driverRoot); r != nvsandboxutils.SUCCESS { + l.logger.Warningf("Failed to init nvsandboxutils: %v; ignoring", r) + l.nvsandboxutilslib = nil + } + defer func() { + if l.nvsandboxutilslib == nil { + return + } + _ = l.nvsandboxutilslib.Shutdown() + }() + } + + gpuDeviceSpecs, err := l.getGPUDeviceSpecs() + if err != nil { + return nil, err + } + deviceSpecs = append(deviceSpecs, gpuDeviceSpecs...) + + migDeviceSpecs, err := l.getMigDeviceSpecs() + if err != nil { + return nil, err + } + deviceSpecs = append(deviceSpecs, migDeviceSpecs...) + + return deviceSpecs, nil +} + +// GetCommonEdits generates a CDI specification that can be used for ANY devices +func (l *nvmllib) GetCommonEdits() (*cdi.ContainerEdits, error) { + common, err := l.newCommonNVMLDiscoverer() + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for common entities: %v", err) + } + + return edits.FromDiscoverer(common) +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +// Deprecated: Use GetDeviceSpecsBy instead. +func (l *nvmllib) GetDeviceSpecsByID(ids ...string) ([]specs.Device, error) { + var identifiers []device.Identifier + for _, id := range ids { + identifiers = append(identifiers, device.Identifier(id)) + } + return l.GetDeviceSpecsBy(identifiers...) +} + +// GetDeviceSpecsBy returns the device specs for devices with the specified identifiers. +func (l *nvmllib) GetDeviceSpecsBy(identifiers ...device.Identifier) ([]specs.Device, error) { + for _, id := range identifiers { + if id == "all" { + return l.GetAllDeviceSpecs() + } + } + + var deviceSpecs []specs.Device + + if r := l.nvmllib.Init(); r != nvml.SUCCESS { + return nil, fmt.Errorf("failed to initialize NVML: %w", r) + } + defer func() { + if r := l.nvmllib.Shutdown(); r != nvml.SUCCESS { + l.logger.Warningf("failed to shutdown NVML: %v", r) + } + }() + + if l.nvsandboxutilslib != nil { + if r := l.nvsandboxutilslib.Init(l.driverRoot); r != nvsandboxutils.SUCCESS { + l.logger.Warningf("Failed to init nvsandboxutils: %v; ignoring", r) + l.nvsandboxutilslib = nil + } + defer func() { + if l.nvsandboxutilslib == nil { + return + } + _ = l.nvsandboxutilslib.Shutdown() + }() + } + + nvmlDevices, err := l.getNVMLDevicesByID(identifiers...) + if err != nil { + return nil, fmt.Errorf("failed to get NVML device handles: %w", err) + } + + for i, nvmlDevice := range nvmlDevices { + deviceEdits, err := l.getEditsForDevice(nvmlDevice) + if err != nil { + return nil, fmt.Errorf("failed to get CDI device edits for identifier %q: %w", identifiers[i], err) + } + deviceSpec := specs.Device{ + Name: string(identifiers[i]), + ContainerEdits: *deviceEdits.ContainerEdits, + } + deviceSpecs = append(deviceSpecs, deviceSpec) + } + + return deviceSpecs, nil +} + +// TODO: move this to go-nvlib? +func (l *nvmllib) getNVMLDevicesByID(identifiers ...device.Identifier) ([]nvml.Device, error) { + var devices []nvml.Device + for _, id := range identifiers { + dev, err := l.getNVMLDeviceByID(id) + if err != nvml.SUCCESS { + return nil, fmt.Errorf("failed to get NVML device handle for identifier %q: %w", id, err) + } + devices = append(devices, dev) + } + return devices, nil +} + +func (l *nvmllib) getNVMLDeviceByID(id device.Identifier) (nvml.Device, error) { + var err error + + if id.IsUUID() { + return l.nvmllib.DeviceGetHandleByUUID(string(id)) + } + + if id.IsGpuIndex() { + if idx, err := strconv.Atoi(string(id)); err == nil { + return l.nvmllib.DeviceGetHandleByIndex(idx) + } + return nil, fmt.Errorf("failed to convert device index to an int: %w", err) + } + + if id.IsMigIndex() { + var gpuIdx, migIdx int + var parent nvml.Device + split := strings.SplitN(string(id), ":", 2) + if gpuIdx, err = strconv.Atoi(split[0]); err != nil { + return nil, fmt.Errorf("failed to convert device index to an int: %w", err) + } + if migIdx, err = strconv.Atoi(split[1]); err != nil { + return nil, fmt.Errorf("failed to convert device index to an int: %w", err) + } + if parent, err = l.nvmllib.DeviceGetHandleByIndex(gpuIdx); err != nvml.SUCCESS { + return nil, fmt.Errorf("failed to get parent device handle: %w", err) + } + return parent.GetMigDeviceHandleByIndex(migIdx) + } + + return nil, fmt.Errorf("identifier is not a valid UUID or index: %q", id) +} + +func (l *nvmllib) getEditsForDevice(nvmlDevice nvml.Device) (*cdi.ContainerEdits, error) { + mig, err := nvmlDevice.IsMigDeviceHandle() + if err != nvml.SUCCESS { + return nil, fmt.Errorf("failed to determine if device handle is a MIG device: %w", err) + } + if mig { + return l.getEditsForMIGDevice(nvmlDevice) + } + return l.getEditsForGPUDevice(nvmlDevice) +} + +func (l *nvmllib) getEditsForGPUDevice(nvmlDevice nvml.Device) (*cdi.ContainerEdits, error) { + nvlibDevice, err := l.devicelib.NewDevice(nvmlDevice) + if err != nil { + return nil, fmt.Errorf("failed to construct device: %w", err) + } + deviceEdits, err := l.GetGPUDeviceEdits(nvlibDevice) + if err != nil { + return nil, fmt.Errorf("failed to get GPU device edits: %w", err) + } + + return deviceEdits, nil +} + +func (l *nvmllib) getEditsForMIGDevice(nvmlDevice nvml.Device) (*cdi.ContainerEdits, error) { + nvmlParentDevice, ret := nvmlDevice.GetDeviceHandleFromMigDeviceHandle() + if ret != nvml.SUCCESS { + return nil, fmt.Errorf("failed to get parent device handle: %w", ret) + } + nvlibMigDevice, err := l.devicelib.NewMigDevice(nvmlDevice) + if err != nil { + return nil, fmt.Errorf("failed to construct device: %w", err) + } + nvlibParentDevice, err := l.devicelib.NewDevice(nvmlParentDevice) + if err != nil { + return nil, fmt.Errorf("failed to construct parent device: %w", err) + } + return l.GetMIGDeviceEdits(nvlibParentDevice, nvlibMigDevice) +} + +func (l *nvmllib) getGPUDeviceSpecs() ([]specs.Device, error) { + var deviceSpecs []specs.Device + err := l.devicelib.VisitDevices(func(i int, d device.Device) error { + specsForDevice, err := l.GetGPUDeviceSpecs(i, d) + if err != nil { + return err + } + deviceSpecs = append(deviceSpecs, specsForDevice...) + + return nil + }) + if err != nil { + return nil, fmt.Errorf("failed to generate CDI edits for GPU devices: %v", err) + } + return deviceSpecs, err +} + +func (l *nvmllib) getMigDeviceSpecs() ([]specs.Device, error) { + var deviceSpecs []specs.Device + err := l.devicelib.VisitMigDevices(func(i int, d device.Device, j int, mig device.MigDevice) error { + specsForDevice, err := l.GetMIGDeviceSpecs(i, d, j, mig) + if err != nil { + return err + } + deviceSpecs = append(deviceSpecs, specsForDevice...) + + return nil + }) + if err != nil { + return nil, fmt.Errorf("failed to generate CDI edits for GPU devices: %v", err) + } + return deviceSpecs, err +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-wsl.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-wsl.go new file mode 100644 index 00000000..1c96c538 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib-wsl.go @@ -0,0 +1,90 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type wsllib nvcdilib + +var _ Interface = (*wsllib)(nil) + +// GetSpec should not be called for wsllib +func (l *wsllib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("Unexpected call to wsllib.GetSpec()") +} + +// GetAllDeviceSpecs returns the device specs for all available devices. +func (l *wsllib) GetAllDeviceSpecs() ([]specs.Device, error) { + device := newDXGDeviceDiscoverer(l.logger, l.devRoot) + deviceEdits, err := edits.FromDiscoverer(device) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for DXG device: %v", err) + } + + deviceSpec := specs.Device{ + Name: "all", + ContainerEdits: *deviceEdits.ContainerEdits, + } + + return []specs.Device{deviceSpec}, nil +} + +// GetCommonEdits generates a CDI specification that can be used for ANY devices +func (l *wsllib) GetCommonEdits() (*cdi.ContainerEdits, error) { + driver, err := newWSLDriverDiscoverer(l.logger, l.driverRoot, l.nvidiaCDIHookPath, l.ldconfigPath) + if err != nil { + return nil, fmt.Errorf("failed to create discoverer for WSL driver: %v", err) + } + + return edits.FromDiscoverer(driver) +} + +// GetGPUDeviceEdits generates a CDI specification that can be used for GPU devices +func (l *wsllib) GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetGPUDeviceEdits is not supported on WSL") +} + +// GetGPUDeviceSpecs returns the CDI device specs for the full GPU represented by 'device'. +func (l *wsllib) GetGPUDeviceSpecs(i int, d device.Device) ([]specs.Device, error) { + return nil, fmt.Errorf("GetGPUDeviceSpecs is not supported on WSL") +} + +// GetMIGDeviceEdits generates a CDI specification that can be used for MIG devices +func (l *wsllib) GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetMIGDeviceEdits is not supported on WSL") +} + +// GetMIGDeviceSpecs returns the CDI device specs for the full MIG represented by 'device'. +func (l *wsllib) GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) { + return nil, fmt.Errorf("GetMIGDeviceSpecs is not supported on WSL") +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +func (l *wsllib) GetDeviceSpecsByID(...string) ([]specs.Device, error) { + return nil, fmt.Errorf("GetDeviceSpecsByID is not supported on WSL") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib.go new file mode 100644 index 00000000..ae22978c --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/lib.go @@ -0,0 +1,289 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "github.com/NVIDIA/go-nvlib/pkg/nvlib/info" + "github.com/NVIDIA/go-nvml/pkg/nvml" + "tags.cncf.io/container-device-interface/pkg/cdi" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/config/image" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils" + "github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform" +) + +type wrapper struct { + Interface + + vendor string + class string + + mergedDeviceOptions []transform.MergedDeviceOption +} + +type nvcdilib struct { + logger logger.Interface + nvmllib nvml.Interface + nvsandboxutilslib nvsandboxutils.Interface + mode string + devicelib device.Interface + deviceNamers DeviceNamers + driverRoot string + devRoot string + nvidiaCDIHookPath string + ldconfigPath string + configSearchPaths []string + librarySearchPaths []string + + csvFiles []string + csvIgnorePatterns []string + + vendor string + class string + + driver *root.Driver + infolib info.Interface + + mergedDeviceOptions []transform.MergedDeviceOption + + disabledHooks disabledHooks +} + +// New creates a new nvcdi library +func New(opts ...Option) (Interface, error) { + l := &nvcdilib{ + disabledHooks: make(disabledHooks), + } + for _, opt := range opts { + opt(l) + } + if l.mode == "" { + l.mode = ModeAuto + } + if l.logger == nil { + l.logger = logger.New() + } + if len(l.deviceNamers) == 0 { + indexNamer, _ := NewDeviceNamer(DeviceNameStrategyIndex) + l.deviceNamers = []DeviceNamer{indexNamer} + } + if l.nvidiaCDIHookPath == "" { + l.nvidiaCDIHookPath = "/usr/bin/nvidia-cdi-hook" + } + if l.driverRoot == "" { + l.driverRoot = "/" + } + if l.devRoot == "" { + l.devRoot = l.driverRoot + } + l.driver = root.New( + root.WithLogger(l.logger), + root.WithDriverRoot(l.driverRoot), + root.WithLibrarySearchPaths(l.librarySearchPaths...), + root.WithConfigSearchPaths(l.configSearchPaths...), + ) + if l.nvmllib == nil { + var nvmlOpts []nvml.LibraryOption + candidates, err := l.driver.Libraries().Locate("libnvidia-ml.so.1") + if err != nil { + l.logger.Warningf("Ignoring error in locating libnvidia-ml.so.1: %v", err) + } else { + libNvidiaMlPath := candidates[0] + l.logger.Infof("Using %v", libNvidiaMlPath) + nvmlOpts = append(nvmlOpts, nvml.WithLibraryPath(libNvidiaMlPath)) + } + l.nvmllib = nvml.New(nvmlOpts...) + } + // TODO: Repeated calls to nvsandboxutils.Init and Shutdown are causing + // segmentation violations. Here we disabled nvsandbox utils unless explicitly + // specified. + // This will be reenabled as soon as we have more visibility into why this is + // happening and a mechanism to detect and disable this if required. + // if l.nvsandboxutilslib == nil { + // var nvsandboxutilsOpts []nvsandboxutils.LibraryOption + // // Set the library path for libnvidia-sandboxutils + // candidates, err := l.driver.Libraries().Locate("libnvidia-sandboxutils.so.1") + // if err != nil { + // l.logger.Warningf("Ignoring error in locating libnvidia-sandboxutils.so.1: %v", err) + // } else { + // libNvidiaSandboxutilsPath := candidates[0] + // l.logger.Infof("Using %v", libNvidiaSandboxutilsPath) + // nvsandboxutilsOpts = append(nvsandboxutilsOpts, nvsandboxutils.WithLibraryPath(libNvidiaSandboxutilsPath)) + // } + // l.nvsandboxutilslib = nvsandboxutils.New(nvsandboxutilsOpts...) + // } + if l.devicelib == nil { + l.devicelib = device.New(l.nvmllib) + } + if l.infolib == nil { + l.infolib = info.New( + info.WithRoot(l.driverRoot), + info.WithLogger(l.logger), + info.WithNvmlLib(l.nvmllib), + info.WithDeviceLib(l.devicelib), + ) + } + + var lib Interface + switch l.resolveMode() { + case ModeCSV: + if len(l.csvFiles) == 0 { + l.csvFiles = csv.DefaultFileList() + } + lib = (*csvlib)(l) + case ModeManagement: + if l.vendor == "" { + l.vendor = "management.nvidia.com" + } + // Management containers in general do not require CUDA Forward compatibility. + l.disabledHooks[HookEnableCudaCompat] = true + lib = (*managementlib)(l) + case ModeNvml: + lib = (*nvmllib)(l) + case ModeWsl: + lib = (*wsllib)(l) + case ModeGds: + if l.class == "" { + l.class = "gds" + } + lib = (*gdslib)(l) + case ModeMofed: + if l.class == "" { + l.class = "mofed" + } + lib = (*mofedlib)(l) + default: + return nil, fmt.Errorf("unknown mode %q", l.mode) + } + + w := wrapper{ + Interface: lib, + vendor: l.vendor, + class: l.class, + mergedDeviceOptions: l.mergedDeviceOptions, + } + return &w, nil +} + +// GetSpec combines the device specs and common edits from the wrapped Interface to a single spec.Interface. +func (l *wrapper) GetSpec() (spec.Interface, error) { + deviceSpecs, err := l.GetAllDeviceSpecs() + if err != nil { + return nil, err + } + + edits, err := l.GetCommonEdits() + if err != nil { + return nil, err + } + + return spec.New( + spec.WithDeviceSpecs(deviceSpecs), + spec.WithEdits(*edits.ContainerEdits), + spec.WithVendor(l.vendor), + spec.WithClass(l.class), + spec.WithMergedDeviceOptions(l.mergedDeviceOptions...), + ) +} + +// GetCommonEdits returns the wrapped edits and adds additional edits on top. +func (m *wrapper) GetCommonEdits() (*cdi.ContainerEdits, error) { + edits, err := m.Interface.GetCommonEdits() + if err != nil { + return nil, err + } + edits.Env = append(edits.Env, image.EnvVarNvidiaVisibleDevices+"=void") + + return edits, nil +} + +// resolveMode resolves the mode for CDI spec generation based on the current system. +func (l *nvcdilib) resolveMode() (rmode string) { + if l.mode != ModeAuto { + return l.mode + } + defer func() { + l.logger.Infof("Auto-detected mode as '%v'", rmode) + }() + + platform := l.infolib.ResolvePlatform() + switch platform { + case info.PlatformNVML: + return ModeNvml + case info.PlatformTegra: + return ModeCSV + case info.PlatformWSL: + return ModeWsl + } + l.logger.Warningf("Unsupported platform detected: %v; assuming %v", platform, ModeNvml) + return ModeNvml +} + +// getCudaVersion returns the CUDA version of the current system. +func (l *nvcdilib) getCudaVersion() (string, error) { + version, err := l.getCudaVersionNvsandboxutils() + if err == nil { + return version, err + } + + // Fallback to NVML + return l.getCudaVersionNvml() +} + +func (l *nvcdilib) getCudaVersionNvml() (string, error) { + if hasNVML, reason := l.infolib.HasNvml(); !hasNVML { + return "", fmt.Errorf("nvml not detected: %v", reason) + } + if l.nvmllib == nil { + return "", fmt.Errorf("nvml library not initialized") + } + r := l.nvmllib.Init() + if r != nvml.SUCCESS { + return "", fmt.Errorf("failed to initialize nvml: %v", r) + } + defer func() { + if r := l.nvmllib.Shutdown(); r != nvml.SUCCESS { + l.logger.Warningf("failed to shutdown NVML: %v", r) + } + }() + + version, r := l.nvmllib.SystemGetDriverVersion() + if r != nvml.SUCCESS { + return "", fmt.Errorf("failed to get driver version: %v", r) + } + return version, nil +} + +func (l *nvcdilib) getCudaVersionNvsandboxutils() (string, error) { + if l.nvsandboxutilslib == nil { + return "", fmt.Errorf("libnvsandboxutils is not available") + } + + // Sandboxutils initialization should happen before this function is called + version, ret := l.nvsandboxutilslib.GetDriverVersion() + if ret != nvsandboxutils.SUCCESS { + return "", fmt.Errorf("%v", ret) + } + return version, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/management.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/management.go new file mode 100644 index 00000000..f0fa900e --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/management.go @@ -0,0 +1,212 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + "path/filepath" + "strings" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda" + "github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type managementlib nvcdilib + +var _ Interface = (*managementlib)(nil) + +// GetAllDeviceSpecs returns all device specs for use in managemnt containers. +// A single device with the name `all` is returned. +func (m *managementlib) GetAllDeviceSpecs() ([]specs.Device, error) { + devices, err := m.newManagementDeviceDiscoverer() + if err != nil { + return nil, fmt.Errorf("failed to create device discoverer: %v", err) + } + + edits, err := edits.FromDiscoverer(devices) + if err != nil { + return nil, fmt.Errorf("failed to create edits from discoverer: %v", err) + } + + if len(edits.DeviceNodes) == 0 { + return nil, fmt.Errorf("no NVIDIA device nodes found") + } + + device := specs.Device{ + Name: "all", + ContainerEdits: *edits.ContainerEdits, + } + return []specs.Device{device}, nil +} + +// GetCommonEdits returns the common edits for use in managementlib containers. +func (m *managementlib) GetCommonEdits() (*cdi.ContainerEdits, error) { + if m.nvsandboxutilslib != nil { + if r := m.nvsandboxutilslib.Init(m.driverRoot); r != nvsandboxutils.SUCCESS { + m.logger.Warningf("Failed to init nvsandboxutils: %v; ignoring", r) + m.nvsandboxutilslib = nil + } + defer func() { + if m.nvsandboxutilslib == nil { + return + } + _ = m.nvsandboxutilslib.Shutdown() + }() + } + + version, err := m.getCudaVersion() + if err != nil { + return nil, fmt.Errorf("failed to get CUDA version: %v", err) + } + + driver, err := (*nvcdilib)(m).newDriverVersionDiscoverer(version) + if err != nil { + return nil, fmt.Errorf("failed to create driver library discoverer: %v", err) + } + + edits, err := edits.FromDiscoverer(driver) + if err != nil { + return nil, fmt.Errorf("failed to create edits from discoverer: %v", err) + } + + return edits, nil +} + +// getCudaVersion returns the CUDA version for use in managementlib containers. +func (m *managementlib) getCudaVersion() (string, error) { + version, err := (*nvcdilib)(m).getCudaVersion() + if err == nil { + return version, nil + } + + libCudaPaths, err := cuda.New( + m.driver.Libraries(), + ).Locate(".*.*") + if err != nil { + return "", fmt.Errorf("failed to locate libcuda.so: %v", err) + } + + libCudaPath := libCudaPaths[0] + + version = strings.TrimPrefix(filepath.Base(libCudaPath), "libcuda.so.") + + return version, nil +} + +type managementDiscoverer struct { + discover.Discover +} + +// newManagementDeviceDiscoverer returns a discover.Discover that discovers device nodes for use in managementlib containers. +// NVML is not used to query devices and all device nodes are returned. +func (m *managementlib) newManagementDeviceDiscoverer() (discover.Discover, error) { + deviceNodes := discover.NewCharDeviceDiscoverer( + m.logger, + m.devRoot, + []string{ + "/dev/nvidia*", + "/dev/nvidia-caps/nvidia-cap*", + "/dev/nvidia-modeset", + "/dev/nvidia-uvm-tools", + "/dev/nvidia-uvm", + "/dev/nvidiactl", + "/dev/nvidia-caps-imex-channels/channel*", + }, + ) + + deviceFolderPermissionHooks := newDeviceFolderPermissionHookDiscoverer( + m.logger, + m.devRoot, + m.nvidiaCDIHookPath, + deviceNodes, + ) + + d := discover.Merge( + &managementDiscoverer{deviceNodes}, + deviceFolderPermissionHooks, + ) + return d, nil +} + +func (m *managementDiscoverer) Devices() ([]discover.Device, error) { + devices, err := m.Discover.Devices() + if err != nil { + return devices, err + } + + var filteredDevices []discover.Device + for _, device := range devices { + if m.nodeIsBlocked(device.HostPath) { + continue + } + filteredDevices = append(filteredDevices, device) + } + + return filteredDevices, nil +} + +// nodeIsBlocked returns true if the specified device node should be ignored. +func (m managementDiscoverer) nodeIsBlocked(path string) bool { + blockedPrefixes := []string{"nvidia-fs", "nvidia-nvswitch", "nvidia-nvlink"} + nodeName := filepath.Base(path) + for _, prefix := range blockedPrefixes { + if strings.HasPrefix(nodeName, prefix) { + return true + } + } + return false +} + +// GetSpec is unsppported for the managementlib specs. +// managementlib is typically wrapped by a spec that implements GetSpec. +func (m *managementlib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("GetSpec is not supported") +} + +// GetGPUDeviceEdits is unsupported for the managementlib specs +func (m *managementlib) GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetGPUDeviceEdits is not supported") +} + +// GetGPUDeviceSpecs is unsupported for the managementlib specs +func (m *managementlib) GetGPUDeviceSpecs(int, device.Device) ([]specs.Device, error) { + return nil, fmt.Errorf("GetGPUDeviceSpecs is not supported") +} + +// GetMIGDeviceEdits is unsupported for the managementlib specs +func (m *managementlib) GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetMIGDeviceEdits is not supported") +} + +// GetMIGDeviceSpecs is unsupported for the managementlib specs +func (m *managementlib) GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) { + return nil, fmt.Errorf("GetMIGDeviceSpecs is not supported") +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +func (l *managementlib) GetDeviceSpecsByID(...string) ([]specs.Device, error) { + return nil, fmt.Errorf("GetDeviceSpecsByID is not supported") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mig-device-nvml.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mig-device-nvml.go new file mode 100644 index 00000000..5c1a504c --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mig-device-nvml.go @@ -0,0 +1,70 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu" +) + +// GetMIGDeviceSpecs returns the CDI device specs for the full GPU represented by 'device'. +func (l *nvmllib) GetMIGDeviceSpecs(i int, d device.Device, j int, mig device.MigDevice) ([]specs.Device, error) { + edits, err := l.GetMIGDeviceEdits(d, mig) + if err != nil { + return nil, fmt.Errorf("failed to get edits for device: %v", err) + } + + names, err := l.deviceNamers.GetMigDeviceNames(i, convert{d}, j, convert{mig}) + if err != nil { + return nil, fmt.Errorf("failed to get device name: %v", err) + } + var deviceSpecs []specs.Device + for _, name := range names { + spec := specs.Device{ + Name: name, + ContainerEdits: *edits.ContainerEdits, + } + deviceSpecs = append(deviceSpecs, spec) + } + return deviceSpecs, nil +} + +// GetMIGDeviceEdits returns the CDI edits for the MIG device represented by 'mig' on 'parent'. +func (l *nvmllib) GetMIGDeviceEdits(parent device.Device, mig device.MigDevice) (*cdi.ContainerEdits, error) { + deviceNodes, err := dgpu.NewForMigDevice(parent, mig, + dgpu.WithDevRoot(l.devRoot), + dgpu.WithLogger(l.logger), + dgpu.WithNVIDIACDIHookPath(l.nvidiaCDIHookPath), + dgpu.WithNvsandboxuitilsLib(l.nvsandboxutilslib), + ) + if err != nil { + return nil, fmt.Errorf("failed to create device discoverer: %v", err) + } + + editsForDevice, err := edits.FromDiscoverer(deviceNodes) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for Compute Instance: %v", err) + } + + return editsForDevice, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mofed.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mofed.go new file mode 100644 index 00000000..9f45cfc9 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/mofed.go @@ -0,0 +1,90 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec" +) + +type mofedlib nvcdilib + +var _ Interface = (*mofedlib)(nil) + +// GetAllDeviceSpecs returns the device specs for all available devices. +func (l *mofedlib) GetAllDeviceSpecs() ([]specs.Device, error) { + discoverer, err := discover.NewMOFEDDiscoverer(l.logger, l.driverRoot) + if err != nil { + return nil, fmt.Errorf("failed to create MOFED discoverer: %v", err) + } + edits, err := edits.FromDiscoverer(discoverer) + if err != nil { + return nil, fmt.Errorf("failed to create container edits for MOFED devices: %v", err) + } + + deviceSpec := specs.Device{ + Name: "all", + ContainerEdits: *edits.ContainerEdits, + } + + return []specs.Device{deviceSpec}, nil +} + +// GetCommonEdits generates a CDI specification that can be used for ANY devices +func (l *mofedlib) GetCommonEdits() (*cdi.ContainerEdits, error) { + return edits.FromDiscoverer(discover.None{}) +} + +// GetSpec is unsppported for the mofedlib specs. +// mofedlib is typically wrapped by a spec that implements GetSpec. +func (l *mofedlib) GetSpec() (spec.Interface, error) { + return nil, fmt.Errorf("GetSpec is not supported") +} + +// GetGPUDeviceEdits is unsupported for the mofedlib specs +func (l *mofedlib) GetGPUDeviceEdits(device.Device) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetGPUDeviceEdits is not supported") +} + +// GetGPUDeviceSpecs is unsupported for the mofedlib specs +func (l *mofedlib) GetGPUDeviceSpecs(int, device.Device) ([]specs.Device, error) { + return nil, fmt.Errorf("GetGPUDeviceSpecs is not supported") +} + +// GetMIGDeviceEdits is unsupported for the mofedlib specs +func (l *mofedlib) GetMIGDeviceEdits(device.Device, device.MigDevice) (*cdi.ContainerEdits, error) { + return nil, fmt.Errorf("GetMIGDeviceEdits is not supported") +} + +// GetMIGDeviceSpecs is unsupported for the mofedlib specs +func (l *mofedlib) GetMIGDeviceSpecs(int, device.Device, int, device.MigDevice) ([]specs.Device, error) { + return nil, fmt.Errorf("GetMIGDeviceSpecs is not supported") +} + +// GetDeviceSpecsByID returns the CDI device specs for the GPU(s) represented by +// the provided identifiers, where an identifier is an index or UUID of a valid +// GPU device. +func (l *mofedlib) GetDeviceSpecsByID(...string) ([]specs.Device, error) { + return nil, fmt.Errorf("GetDeviceSpecsByID is not supported") +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer.go new file mode 100644 index 00000000..8edd8f07 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer.go @@ -0,0 +1,167 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "errors" + "fmt" + + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// UUIDer is an interface for getting UUIDs. +type UUIDer interface { + GetUUID() (string, error) +} + +// DeviceNamers represents a list of device namers +type DeviceNamers []DeviceNamer + +// DeviceNamer is an interface for getting device names +type DeviceNamer interface { + GetDeviceName(int, UUIDer) (string, error) + GetMigDeviceName(int, UUIDer, int, UUIDer) (string, error) +} + +// Supported device naming strategies +const ( + // DeviceNameStrategyIndex generates devices names such as 0 or 1:0 + DeviceNameStrategyIndex = "index" + // DeviceNameStrategyTypeIndex generates devices names such as gpu0 or mig1:0 + DeviceNameStrategyTypeIndex = "type-index" + // DeviceNameStrategyUUID uses the device UUID as the name + DeviceNameStrategyUUID = "uuid" +) + +type deviceNameIndex struct { + gpuPrefix string + migPrefix string +} +type deviceNameUUID struct{} + +// NewDeviceNamer creates a Device Namer based on the supplied strategy. +// This namer can be used to construct the names for MIG and GPU devices when generating the CDI spec. +func NewDeviceNamer(strategy string) (DeviceNamer, error) { + switch strategy { + case DeviceNameStrategyIndex: + return deviceNameIndex{}, nil + case DeviceNameStrategyTypeIndex: + return deviceNameIndex{gpuPrefix: "gpu", migPrefix: "mig"}, nil + case DeviceNameStrategyUUID: + return deviceNameUUID{}, nil + } + + return nil, fmt.Errorf("invalid device name strategy: %v", strategy) +} + +// GetDeviceName returns the name for the specified device based on the naming strategy +func (s deviceNameIndex) GetDeviceName(i int, _ UUIDer) (string, error) { + return fmt.Sprintf("%s%d", s.gpuPrefix, i), nil +} + +// GetMigDeviceName returns the name for the specified device based on the naming strategy +func (s deviceNameIndex) GetMigDeviceName(i int, _ UUIDer, j int, _ UUIDer) (string, error) { + return fmt.Sprintf("%s%d:%d", s.migPrefix, i, j), nil +} + +// GetDeviceName returns the name for the specified device based on the naming strategy +func (s deviceNameUUID) GetDeviceName(i int, d UUIDer) (string, error) { + uuid, err := d.GetUUID() + if err != nil { + return "", fmt.Errorf("failed to get device UUID: %v", err) + } + return uuid, nil +} + +// GetMigDeviceName returns the name for the specified device based on the naming strategy +func (s deviceNameUUID) GetMigDeviceName(i int, _ UUIDer, j int, mig UUIDer) (string, error) { + uuid, err := mig.GetUUID() + if err != nil { + return "", fmt.Errorf("failed to get device UUID: %v", err) + } + return uuid, nil +} + +//go:generate moq -stub -out namer_nvml_mock.go . nvmlUUIDer +type nvmlUUIDer interface { + GetUUID() (string, nvml.Return) +} + +type convert struct { + nvmlUUIDer +} + +type uuidIgnored struct{} + +func (m uuidIgnored) GetUUID() (string, error) { + return "", nil +} + +type uuidUnsupported struct{} + +func (m convert) GetUUID() (string, error) { + if m.nvmlUUIDer == nil { + return uuidUnsupported{}.GetUUID() + } + uuid, ret := m.nvmlUUIDer.GetUUID() + if ret != nvml.SUCCESS { + return "", ret + } + return uuid, nil +} + +var errUUIDUnsupported = errors.New("GetUUID is not supported") + +func (m uuidUnsupported) GetUUID() (string, error) { + return "", errUUIDUnsupported +} + +func (l DeviceNamers) GetDeviceNames(i int, d UUIDer) ([]string, error) { + var names []string + for _, namer := range l { + name, err := namer.GetDeviceName(i, d) + if err != nil { + return nil, err + } + if name == "" { + continue + } + names = append(names, name) + } + if len(names) == 0 { + return nil, errors.New("no names defined") + } + return names, nil +} + +func (l DeviceNamers) GetMigDeviceNames(i int, d UUIDer, j int, mig UUIDer) ([]string, error) { + var names []string + for _, namer := range l { + name, err := namer.GetMigDeviceName(i, d, j, mig) + if err != nil { + return nil, err + } + if name == "" { + continue + } + names = append(names, name) + } + if len(names) == 0 { + return nil, errors.New("no names defined") + } + return names, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer_nvml_mock.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer_nvml_mock.go new file mode 100644 index 00000000..6a704b45 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/namer_nvml_mock.go @@ -0,0 +1,73 @@ +// Code generated by moq; DO NOT EDIT. +// github.com/matryer/moq + +package nvcdi + +import ( + "sync" + + "github.com/NVIDIA/go-nvml/pkg/nvml" +) + +// Ensure, that nvmlUUIDerMock does implement nvmlUUIDer. +// If this is not the case, regenerate this file with moq. +var _ nvmlUUIDer = &nvmlUUIDerMock{} + +// nvmlUUIDerMock is a mock implementation of nvmlUUIDer. +// +// func TestSomethingThatUsesnvmlUUIDer(t *testing.T) { +// +// // make and configure a mocked nvmlUUIDer +// mockednvmlUUIDer := &nvmlUUIDerMock{ +// GetUUIDFunc: func() (string, nvml.Return) { +// panic("mock out the GetUUID method") +// }, +// } +// +// // use mockednvmlUUIDer in code that requires nvmlUUIDer +// // and then make assertions. +// +// } +type nvmlUUIDerMock struct { + // GetUUIDFunc mocks the GetUUID method. + GetUUIDFunc func() (string, nvml.Return) + + // calls tracks calls to the methods. + calls struct { + // GetUUID holds details about calls to the GetUUID method. + GetUUID []struct { + } + } + lockGetUUID sync.RWMutex +} + +// GetUUID calls GetUUIDFunc. +func (mock *nvmlUUIDerMock) GetUUID() (string, nvml.Return) { + callInfo := struct { + }{} + mock.lockGetUUID.Lock() + mock.calls.GetUUID = append(mock.calls.GetUUID, callInfo) + mock.lockGetUUID.Unlock() + if mock.GetUUIDFunc == nil { + var ( + sOut string + returnOut nvml.Return + ) + return sOut, returnOut + } + return mock.GetUUIDFunc() +} + +// GetUUIDCalls gets all the calls that were made to GetUUID. +// Check the length with: +// +// len(mockednvmlUUIDer.GetUUIDCalls()) +func (mock *nvmlUUIDerMock) GetUUIDCalls() []struct { +} { + var calls []struct { + } + mock.lockGetUUID.RLock() + calls = mock.calls.GetUUID + mock.lockGetUUID.RUnlock() + return calls +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/options.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/options.go new file mode 100644 index 00000000..d94a8e6b --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/options.go @@ -0,0 +1,168 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "github.com/NVIDIA/go-nvlib/pkg/nvlib/device" + "github.com/NVIDIA/go-nvlib/pkg/nvlib/info" + "github.com/NVIDIA/go-nvml/pkg/nvml" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform" +) + +// Option is a function that configures the nvcdilib +type Option func(*nvcdilib) + +// WithDeviceLib sets the device library for the library +func WithDeviceLib(devicelib device.Interface) Option { + return func(l *nvcdilib) { + l.devicelib = devicelib + } +} + +// WithInfoLib sets the info library for CDI spec generation. +func WithInfoLib(infolib info.Interface) Option { + return func(l *nvcdilib) { + l.infolib = infolib + } +} + +// WithDeviceNamers sets the device namer for the library +func WithDeviceNamers(namers ...DeviceNamer) Option { + return func(l *nvcdilib) { + l.deviceNamers = namers + } +} + +// WithDriverRoot sets the driver root for the library +func WithDriverRoot(root string) Option { + return func(l *nvcdilib) { + l.driverRoot = root + } +} + +// WithDevRoot sets the root where /dev is located. +func WithDevRoot(root string) Option { + return func(l *nvcdilib) { + l.devRoot = root + } +} + +// WithLogger sets the logger for the library +func WithLogger(logger logger.Interface) Option { + return func(l *nvcdilib) { + l.logger = logger + } +} + +// WithNVIDIACTKPath sets the path to the NVIDIA Container Toolkit CLI path for the library +// +// Deprecated: Use WithNVIDIACDIHookPath instead. +func WithNVIDIACTKPath(path string) Option { + return WithNVIDIACDIHookPath(path) +} + +// WithNVIDIACDIHookPath sets the path to the NVIDIA Container Toolkit CLI path for the library +func WithNVIDIACDIHookPath(path string) Option { + return func(l *nvcdilib) { + l.nvidiaCDIHookPath = path + } +} + +// WithLdconfigPath sets the path to the ldconfig program +func WithLdconfigPath(path string) Option { + return func(l *nvcdilib) { + l.ldconfigPath = path + } +} + +// WithNvmlLib sets the nvml library for the library +func WithNvmlLib(nvmllib nvml.Interface) Option { + return func(l *nvcdilib) { + l.nvmllib = nvmllib + } +} + +// WithMode sets the discovery mode for the library +func WithMode(mode string) Option { + return func(l *nvcdilib) { + l.mode = mode + } +} + +// WithVendor sets the vendor for the library +func WithVendor(vendor string) Option { + return func(o *nvcdilib) { + o.vendor = vendor + } +} + +// WithClass sets the class for the library +func WithClass(class string) Option { + return func(o *nvcdilib) { + o.class = class + } +} + +// WithMergedDeviceOptions sets the merged device options for the library +// If these are not set, no merged device will be generated. +func WithMergedDeviceOptions(opts ...transform.MergedDeviceOption) Option { + return func(o *nvcdilib) { + o.mergedDeviceOptions = opts + } +} + +// WithCSVFiles sets the CSV files for the library +func WithCSVFiles(csvFiles []string) Option { + return func(o *nvcdilib) { + o.csvFiles = csvFiles + } +} + +// WithCSVIgnorePatterns sets the ignore patterns for entries in the CSV files. +func WithCSVIgnorePatterns(csvIgnorePatterns []string) Option { + return func(o *nvcdilib) { + o.csvIgnorePatterns = csvIgnorePatterns + } +} + +// WithConfigSearchPaths sets the search paths for config files. +func WithConfigSearchPaths(paths []string) Option { + return func(o *nvcdilib) { + o.configSearchPaths = paths + } +} + +// WithLibrarySearchPaths sets the library search paths. +// This is currently only used for CSV-mode. +func WithLibrarySearchPaths(paths []string) Option { + return func(o *nvcdilib) { + o.librarySearchPaths = paths + } +} + +// WithDisabledHook allows specific hooks to the disabled. +// This option can be specified multiple times for each hook. +func WithDisabledHook(hook HookName) Option { + return func(o *nvcdilib) { + if o.disabledHooks == nil { + o.disabledHooks = make(map[HookName]bool) + } + o.disabledHooks[hook] = true + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/api.go new file mode 100644 index 00000000..918f56f2 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/api.go @@ -0,0 +1,42 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package spec + +import ( + "io" + + "tags.cncf.io/container-device-interface/specs-go" +) + +const ( + // DetectMinimumVersion is a constant that triggers a spec to detect the minimum required version. + // + // Deprecated: DetectMinimumVersion is deprecated and will be removed. + DetectMinimumVersion = "DETECT_MINIMUM_VERSION" + + // FormatJSON indicates a JSON output format + FormatJSON = "json" + // FormatYAML indicates a YAML output format + FormatYAML = "yaml" +) + +// Interface is the interface for the spec API +type Interface interface { + io.WriterTo + Save(string) error + Raw() *specs.Spec +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/builder.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/builder.go new file mode 100644 index 00000000..b7dffd98 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/builder.go @@ -0,0 +1,197 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package spec + +import ( + "fmt" + "os" + + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/pkg/parser" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform" +) + +type builder struct { + raw *specs.Spec + version string + vendor string + class string + deviceSpecs []specs.Device + edits specs.ContainerEdits + format string + + mergedDeviceOptions []transform.MergedDeviceOption + noSimplify bool + permissions os.FileMode + + transformOnSave transform.Transformer +} + +// newBuilder creates a new spec builder with the supplied options +func newBuilder(opts ...Option) *builder { + s := &builder{} + for _, opt := range opts { + opt(s) + } + + if s.raw != nil { + s.noSimplify = true + vendor, class := parser.ParseQualifier(s.raw.Kind) + if s.vendor == "" { + s.vendor = vendor + } + if s.class == "" { + s.class = class + } + if s.version == "" || s.version == DetectMinimumVersion { + s.version = s.raw.Version + } + } + if s.version == "" || s.version == DetectMinimumVersion { + s.transformOnSave = &setMinimumRequiredVersion{} + s.version = cdi.CurrentVersion + } + if s.vendor == "" { + s.vendor = "nvidia.com" + } + if s.class == "" { + s.class = "gpu" + } + if s.format == "" { + s.format = FormatYAML + } + if s.permissions == 0 { + s.permissions = 0644 + } + return s +} + +// Build builds a CDI spec form the spec builder. +func (o *builder) Build() (*spec, error) { + raw := o.raw + if raw == nil { + raw = &specs.Spec{ + Version: o.version, + Kind: fmt.Sprintf("%s/%s", o.vendor, o.class), + Devices: o.deviceSpecs, + ContainerEdits: o.edits, + } + } + if raw.Version == "" { + raw.Version = o.version + } + + if !o.noSimplify { + err := transform.NewSimplifier().Transform(raw) + if err != nil { + return nil, fmt.Errorf("failed to simplify spec: %v", err) + } + } + + if len(o.mergedDeviceOptions) > 0 { + merge, err := transform.NewMergedDevice(o.mergedDeviceOptions...) + if err != nil { + return nil, fmt.Errorf("failed to create merged device transformer: %v", err) + } + if err := merge.Transform(raw); err != nil { + return nil, fmt.Errorf("failed to merge devices: %v", err) + } + } + + s := spec{ + Spec: raw, + format: o.format, + permissions: o.permissions, + transformOnSave: o.transformOnSave, + } + return &s, nil +} + +// Option defines a function that can be used to configure the spec builder. +type Option func(*builder) + +// WithDeviceSpecs sets the device specs for the spec builder +func WithDeviceSpecs(deviceSpecs []specs.Device) Option { + return func(o *builder) { + o.deviceSpecs = deviceSpecs + } +} + +// WithEdits sets the container edits for the spec builder +func WithEdits(edits specs.ContainerEdits) Option { + return func(o *builder) { + o.edits = edits + } +} + +// WithVersion sets the version for the spec builder +func WithVersion(version string) Option { + return func(o *builder) { + o.version = version + } +} + +// WithVendor sets the vendor for the spec builder +func WithVendor(vendor string) Option { + return func(o *builder) { + o.vendor = vendor + } +} + +// WithClass sets the class for the spec builder +func WithClass(class string) Option { + return func(o *builder) { + o.class = class + } +} + +// WithFormat sets the output file format +func WithFormat(format string) Option { + return func(o *builder) { + o.format = format + } +} + +// WithNoSimplify sets whether the spec must be simplified +func WithNoSimplify(noSimplify bool) Option { + return func(o *builder) { + o.noSimplify = noSimplify + } +} + +// WithRawSpec sets the raw spec for the spec builder +func WithRawSpec(raw *specs.Spec) Option { + return func(o *builder) { + o.raw = raw + } +} + +// WithPermissions sets the permissions for the generated spec file +func WithPermissions(permissions os.FileMode) Option { + return func(o *builder) { + o.permissions = permissions + } +} + +// WithMergedDeviceOptions sets the options for generating a merged device. +func WithMergedDeviceOptions(opts ...transform.MergedDeviceOption) Option { + return func(o *builder) { + o.mergedDeviceOptions = opts + } +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/set-minimum-version.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/set-minimum-version.go new file mode 100644 index 00000000..69969c0b --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/set-minimum-version.go @@ -0,0 +1,35 @@ +/** +# Copyright 2024 NVIDIA CORPORATION +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package spec + +import ( + "fmt" + + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" +) + +type setMinimumRequiredVersion struct{} + +func (d setMinimumRequiredVersion) Transform(spec *specs.Spec) error { + minVersion, err := cdi.MinimumRequiredVersion(spec) + if err != nil { + return fmt.Errorf("failed to get minimum required CDI spec version: %v", err) + } + spec.Version = minVersion + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/spec.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/spec.go new file mode 100644 index 00000000..28cccc51 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec/spec.go @@ -0,0 +1,137 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package spec + +import ( + "fmt" + "io" + "os" + "path/filepath" + + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/specs-go" + + "github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform" +) + +type spec struct { + *specs.Spec + format string + permissions os.FileMode + transformOnSave transform.Transformer +} + +var _ Interface = (*spec)(nil) + +// New creates a new spec with the specified options. +func New(opts ...Option) (Interface, error) { + return newBuilder(opts...).Build() +} + +// Save writes the spec to the specified path and overwrites the file if it exists. +func (s *spec) Save(path string) error { + if s.transformOnSave != nil { + err := s.transformOnSave.Transform(s.Raw()) + if err != nil { + return fmt.Errorf("error applying transform: %w", err) + } + } + path, err := s.normalizePath(path) + if err != nil { + return fmt.Errorf("failed to normalize path: %w", err) + } + + specDir := filepath.Dir(path) + cache, _ := cdi.NewCache( + cdi.WithAutoRefresh(false), + cdi.WithSpecDirs(specDir), + ) + if err := cache.WriteSpec(s.Raw(), filepath.Base(path)); err != nil { + return fmt.Errorf("failed to write spec: %w", err) + } + + if err := os.Chmod(path, s.permissions); err != nil { + return fmt.Errorf("failed to set permissions on spec file: %w", err) + } + + return nil +} + +// WriteTo writes the spec to the specified writer. +func (s *spec) WriteTo(w io.Writer) (int64, error) { + name, err := cdi.GenerateNameForSpec(s.Raw()) + if err != nil { + return 0, err + } + + path, _ := s.normalizePath(name) + tmpFile, err := os.CreateTemp("", "*"+filepath.Base(path)) + if err != nil { + return 0, err + } + defer os.Remove(tmpFile.Name()) + + if err := s.Save(tmpFile.Name()); err != nil { + return 0, err + } + + err = tmpFile.Close() + if err != nil { + return 0, fmt.Errorf("failed to close temporary file: %w", err) + } + + r, err := os.Open(tmpFile.Name()) + if err != nil { + return 0, fmt.Errorf("failed to open temporary file: %w", err) + } + defer r.Close() + + return io.Copy(w, r) +} + +// Raw returns a pointer to the raw spec. +func (s *spec) Raw() *specs.Spec { + return s.Spec +} + +// normalizePath ensures that the specified path has a supported extension +func (s *spec) normalizePath(path string) (string, error) { + if ext := filepath.Ext(path); ext != ".yaml" && ext != ".json" { + path += s.extension() + } + + if filepath.Clean(filepath.Dir(path)) == "." { + pwd, err := os.Getwd() + if err != nil { + return path, fmt.Errorf("failed to get current working directory: %v", err) + } + path = filepath.Join(pwd, path) + } + + return path, nil +} + +func (s *spec) extension() string { + switch s.format { + case FormatJSON: + return ".json" + case FormatYAML: + return ".yaml" + } + + return ".yaml" +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/api.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/api.go new file mode 100644 index 00000000..786ffb46 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/api.go @@ -0,0 +1,24 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import "tags.cncf.io/container-device-interface/specs-go" + +// Transformer defines the API for applying arbitrary transforms to a spec in-place +type Transformer interface { + Transform(*specs.Spec) error +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/deduplicate.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/deduplicate.go new file mode 100644 index 00000000..27be1b67 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/deduplicate.go @@ -0,0 +1,152 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "tags.cncf.io/container-device-interface/specs-go" +) + +type dedupe struct{} + +var _ Transformer = (*dedupe)(nil) + +// NewDedupe creates a transformer that deduplicates container edits. +func NewDedupe() (Transformer, error) { + return &dedupe{}, nil +} + +// Transform removes duplicate entris from devices and common container edits. +func (d dedupe) Transform(spec *specs.Spec) error { + if spec == nil { + return nil + } + if err := d.transformEdits(&spec.ContainerEdits); err != nil { + return err + } + var updatedDevices []specs.Device + for _, device := range spec.Devices { + device := device + if err := d.transformEdits(&device.ContainerEdits); err != nil { + return err + } + updatedDevices = append(updatedDevices, device) + } + spec.Devices = updatedDevices + return nil +} + +func (d dedupe) transformEdits(edits *specs.ContainerEdits) error { + deviceNodes, err := d.deduplicateDeviceNodes(edits.DeviceNodes) + if err != nil { + return err + } + edits.DeviceNodes = deviceNodes + + envs, err := d.deduplicateEnvs(edits.Env) + if err != nil { + return err + } + edits.Env = envs + + hooks, err := d.deduplicateHooks(edits.Hooks) + if err != nil { + return err + } + edits.Hooks = hooks + + mounts, err := d.deduplicateMounts(edits.Mounts) + if err != nil { + return err + } + edits.Mounts = mounts + + return nil +} + +func (d dedupe) deduplicateDeviceNodes(entities []*specs.DeviceNode) ([]*specs.DeviceNode, error) { + seen := make(map[string]bool) + var deviceNodes []*specs.DeviceNode + for _, e := range entities { + if e == nil { + continue + } + id, err := deviceNode(*e).id() + if err != nil { + return nil, err + } + if seen[id] { + continue + } + seen[id] = true + deviceNodes = append(deviceNodes, e) + } + return deviceNodes, nil +} + +func (d dedupe) deduplicateEnvs(entities []string) ([]string, error) { + seen := make(map[string]bool) + var envs []string + for _, e := range entities { + id := e + if seen[id] { + continue + } + seen[id] = true + envs = append(envs, e) + } + return envs, nil +} + +func (d dedupe) deduplicateHooks(entities []*specs.Hook) ([]*specs.Hook, error) { + seen := make(map[string]bool) + var hooks []*specs.Hook + for _, e := range entities { + if e == nil { + continue + } + id, err := hook(*e).id() + if err != nil { + return nil, err + } + if seen[id] { + continue + } + seen[id] = true + hooks = append(hooks, e) + } + return hooks, nil +} + +func (d dedupe) deduplicateMounts(entities []*specs.Mount) ([]*specs.Mount, error) { + seen := make(map[string]bool) + var mounts []*specs.Mount + for _, e := range entities { + if e == nil { + continue + } + id, err := mount(*e).id() + if err != nil { + return nil, err + } + if seen[id] { + continue + } + seen[id] = true + mounts = append(mounts, e) + } + return mounts, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/edits.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/edits.go new file mode 100644 index 00000000..fea47ffa --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/edits.go @@ -0,0 +1,166 @@ +/* +* +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "encoding/json" + + "tags.cncf.io/container-device-interface/specs-go" +) + +type containerEdits specs.ContainerEdits + +// IsEmpty returns true if the edits are empty. +func (e containerEdits) IsEmpty() bool { + // Devices with empty edits are invalid + if len(e.DeviceNodes) > 0 { + return false + } + if len(e.Env) > 0 { + return false + } + if len(e.Hooks) > 0 { + return false + } + if len(e.Mounts) > 0 { + return false + } + + return true +} + +func (e *containerEdits) getEntityIds() ([]string, error) { + if e == nil { + return nil, nil + } + uniqueIDs := make(map[string]bool) + + deviceNodes, err := e.getDeviceNodeIDs() + if err != nil { + return nil, err + } + for k := range deviceNodes { + uniqueIDs[k] = true + } + + envs, err := e.getEnvIDs() + if err != nil { + return nil, err + } + for k := range envs { + uniqueIDs[k] = true + } + + hooks, err := e.getHookIDs() + if err != nil { + return nil, err + } + for k := range hooks { + uniqueIDs[k] = true + } + + mounts, err := e.getMountIDs() + if err != nil { + return nil, err + } + for k := range mounts { + uniqueIDs[k] = true + } + + var ids []string + for k := range uniqueIDs { + ids = append(ids, k) + } + + return ids, nil +} + +func (e *containerEdits) getDeviceNodeIDs() (map[string]bool, error) { + deviceIDs := make(map[string]bool) + for _, entity := range e.DeviceNodes { + id, err := deviceNode(*entity).id() + if err != nil { + return nil, err + } + deviceIDs[id] = true + } + return deviceIDs, nil +} + +func (e *containerEdits) getEnvIDs() (map[string]bool, error) { + envIDs := make(map[string]bool) + for _, entity := range e.Env { + id, err := env(entity).id() + if err != nil { + return nil, err + } + envIDs[id] = true + } + return envIDs, nil +} + +func (e *containerEdits) getHookIDs() (map[string]bool, error) { + hookIDs := make(map[string]bool) + for _, entity := range e.Hooks { + id, err := hook(*entity).id() + if err != nil { + return nil, err + } + hookIDs[id] = true + } + return hookIDs, nil +} + +func (e *containerEdits) getMountIDs() (map[string]bool, error) { + mountIDs := make(map[string]bool) + for _, entity := range e.Mounts { + id, err := mount(*entity).id() + if err != nil { + return nil, err + } + mountIDs[id] = true + } + return mountIDs, nil +} + +type deviceNode specs.DeviceNode + +func (dn deviceNode) id() (string, error) { + b, err := json.Marshal(dn) + return string(b), err +} + +type env string + +func (e env) id() (string, error) { + return string(e), nil +} + +type mount specs.Mount + +func (m mount) id() (string, error) { + b, err := json.Marshal(m) + return string(b), err +} + +type hook specs.Hook + +func (m hook) id() (string, error) { + b, err := json.Marshal(m) + return string(b), err +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merge.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merge.go new file mode 100644 index 00000000..762107b3 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merge.go @@ -0,0 +1,36 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import "tags.cncf.io/container-device-interface/specs-go" + +type merged []Transformer + +// Merge creates a merged transofrmer from the specified transformers. +func Merge(transformers ...Transformer) Transformer { + return merged(transformers) +} + +// Transform applies all the transformers in the merged set. +func (t merged) Transform(spec *specs.Spec) error { + for _, transformer := range t { + if err := transformer.Transform(spec); err != nil { + return err + } + } + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merged-device.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merged-device.go new file mode 100644 index 00000000..523876e3 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/merged-device.go @@ -0,0 +1,126 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "fmt" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/edits" + + "tags.cncf.io/container-device-interface/pkg/cdi" + "tags.cncf.io/container-device-interface/pkg/parser" + "tags.cncf.io/container-device-interface/specs-go" +) + +const ( + allDeviceName = "all" +) + +type mergedDevice struct { + name string + skipIfExists bool + simplifier Transformer +} + +var _ Transformer = (*mergedDevice)(nil) + +// MergedDeviceOption is a function that configures a merged device +type MergedDeviceOption func(*mergedDevice) + +// WithName sets the name of the merged device +func WithName(name string) MergedDeviceOption { + return func(m *mergedDevice) { + m.name = name + } +} + +// WithSkipIfExists sets whether to skip adding the merged device if it already exists +func WithSkipIfExists(skipIfExists bool) MergedDeviceOption { + return func(m *mergedDevice) { + m.skipIfExists = skipIfExists + } +} + +// NewMergedDevice creates a transformer with the specified options +func NewMergedDevice(opts ...MergedDeviceOption) (Transformer, error) { + m := &mergedDevice{} + for _, opt := range opts { + opt(m) + } + if m.name == "" { + m.name = allDeviceName + } + m.simplifier = NewSimplifier() + + if err := parser.ValidateDeviceName(m.name); err != nil { + return nil, fmt.Errorf("invalid device name %q: %v", m.name, err) + } + + return m, nil +} + +// Transform adds a merged device to the spec +func (m mergedDevice) Transform(spec *specs.Spec) error { + if spec == nil { + return nil + } + + mergedDevice, err := mergeDeviceSpecs(spec.Devices, m.name) + if err != nil { + return fmt.Errorf("failed to generate merged device %q: %v", m.name, err) + } + if mergedDevice == nil { + if m.skipIfExists { + return nil + } + return fmt.Errorf("device %q already exists", m.name) + } + + spec.Devices = append(spec.Devices, *mergedDevice) + + if err := m.simplifier.Transform(spec); err != nil { + return fmt.Errorf("failed to simplify spec after merging device %q: %v", m.name, err) + } + + return nil +} + +// mergeDeviceSpecs creates a device with the specified name which combines the edits from the previous devices. +// If a device of the specified name already exists, no device is created and nil is returned. +func mergeDeviceSpecs(deviceSpecs []specs.Device, mergedDeviceName string) (*specs.Device, error) { + for _, d := range deviceSpecs { + if d.Name == mergedDeviceName { + return nil, nil + } + } + + mergedEdits := edits.NewContainerEdits() + + for _, d := range deviceSpecs { + d := d + edit := cdi.ContainerEdits{ + ContainerEdits: &d.ContainerEdits, + } + mergedEdits.Append(&edit) + } + + merged := specs.Device{ + Name: mergedDeviceName, + ContainerEdits: *mergedEdits.ContainerEdits, + } + return &merged, nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/remove.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/remove.go new file mode 100644 index 00000000..bc009485 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/remove.go @@ -0,0 +1,106 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "fmt" + + "tags.cncf.io/container-device-interface/specs-go" +) + +type remove map[string]bool + +func newRemover(ids ...string) Transformer { + r := make(remove) + for _, id := range ids { + r[id] = true + } + return r +} + +// Transform remove the specified entities from the spec. +func (r remove) Transform(spec *specs.Spec) error { + if spec == nil { + return nil + } + + for _, device := range spec.Devices { + device := device + if err := r.transformEdits(&device.ContainerEdits); err != nil { + return fmt.Errorf("failed to remove edits from device %q: %w", device.Name, err) + } + } + + return r.transformEdits(&spec.ContainerEdits) +} + +func (r remove) transformEdits(edits *specs.ContainerEdits) error { + if edits == nil { + return nil + } + + var deviceNodes []*specs.DeviceNode + for _, entity := range edits.DeviceNodes { + id, err := deviceNode(*entity).id() + if err != nil { + return err + } + if r[id] { + continue + } + deviceNodes = append(deviceNodes, entity) + } + edits.DeviceNodes = deviceNodes + + var envs []string + for _, entity := range edits.Env { + id := entity + if r[id] { + continue + } + envs = append(envs, entity) + } + edits.Env = envs + + var hooks []*specs.Hook + for _, entity := range edits.Hooks { + id, err := hook(*entity).id() + if err != nil { + return err + } + if r[id] { + continue + } + hooks = append(hooks, entity) + } + edits.Hooks = hooks + + var mounts []*specs.Mount + for _, entity := range edits.Mounts { + id, err := mount(*entity).id() + if err != nil { + return err + } + if r[id] { + continue + } + mounts = append(mounts, entity) + } + edits.Mounts = mounts + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/simplify.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/simplify.go new file mode 100644 index 00000000..23bdfed8 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/simplify.go @@ -0,0 +1,78 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "fmt" + + "tags.cncf.io/container-device-interface/specs-go" +) + +type simplify struct{} + +var _ Transformer = (*simplify)(nil) + +// NewSimplifier creates a simplifier transformer. +// This transoformer ensures that entities in the spec are deduplicated and that common edits are removed from device-specific edits. +func NewSimplifier() Transformer { + return Merge( + dedupe{}, + simplify{}, + sorter{}, + ) +} + +// Transform simplifies the supplied spec. +// Edits that are present in the common edits are removed from device-specific edits. +func (s simplify) Transform(spec *specs.Spec) error { + if spec == nil { + return nil + } + + dedupe := dedupe{} + if err := dedupe.Transform(spec); err != nil { + return err + } + + commonEntityIDs, err := (*containerEdits)(&spec.ContainerEdits).getEntityIds() + if err != nil { + return err + } + + toRemove := newRemover(commonEntityIDs...) + var updatedDevices []specs.Device + for _, device := range spec.Devices { + deviceAsSpec := specs.Spec{ + ContainerEdits: device.ContainerEdits, + } + err := toRemove.Transform(&deviceAsSpec) + if err != nil { + return fmt.Errorf("failed to transform device edits: %w", err) + } + + if !(containerEdits)(deviceAsSpec.ContainerEdits).IsEmpty() { + // Devices with empty edits are invalid. + // We only update the container edits for the device if this would + // result in a valid device. + device.ContainerEdits = deviceAsSpec.ContainerEdits + } + updatedDevices = append(updatedDevices, device) + } + spec.Devices = updatedDevices + + return nil +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/sorter.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/sorter.go new file mode 100644 index 00000000..2fc53ac3 --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform/sorter.go @@ -0,0 +1,96 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package transform + +import ( + "os" + "path/filepath" + "sort" + "strings" + + "tags.cncf.io/container-device-interface/specs-go" +) + +type sorter struct{} + +var _ Transformer = (*sorter)(nil) + +// NewSorter creates a transformer that sorts container edits. +func NewSorter() Transformer { + return nil +} + +// Transform sorts the entities in the specified CDI specification. +func (d sorter) Transform(spec *specs.Spec) error { + if spec == nil { + return nil + } + if err := d.transformEdits(&spec.ContainerEdits); err != nil { + return err + } + var updatedDevices []specs.Device + for _, device := range spec.Devices { + device := device + if err := d.transformEdits(&device.ContainerEdits); err != nil { + return err + } + updatedDevices = append(updatedDevices, device) + } + spec.Devices = d.sortDevices(updatedDevices) + return nil +} + +func (d sorter) transformEdits(edits *specs.ContainerEdits) error { + edits.DeviceNodes = d.sortDeviceNodes(edits.DeviceNodes) + edits.Mounts = d.sortMounts(edits.Mounts) + return nil +} + +func (d sorter) sortDevices(devices []specs.Device) []specs.Device { + sort.Slice(devices, func(i, j int) bool { + return devices[i].Name < devices[j].Name + }) + return devices +} + +// sortDeviceNodes sorts the specified device nodes by container path. +// If two device nodes have the same container path, the host path is used to break ties. +func (d sorter) sortDeviceNodes(entities []*specs.DeviceNode) []*specs.DeviceNode { + sort.Slice(entities, func(i, j int) bool { + ip := strings.Count(filepath.Clean(entities[i].Path), string(os.PathSeparator)) + jp := strings.Count(filepath.Clean(entities[j].Path), string(os.PathSeparator)) + if ip == jp { + return entities[i].Path < entities[j].Path + } + return ip < jp + }) + return entities +} + +// sortMounts sorts the specified mounts by container path. +// If two mounts have the same mount path, the host path is used to break ties. +func (d sorter) sortMounts(entities []*specs.Mount) []*specs.Mount { + sort.Slice(entities, func(i, j int) bool { + ip := strings.Count(filepath.Clean(entities[i].ContainerPath), string(os.PathSeparator)) + jp := strings.Count(filepath.Clean(entities[j].ContainerPath), string(os.PathSeparator)) + if ip == jp { + return entities[i].ContainerPath < entities[j].ContainerPath + } + return ip < jp + }) + return entities +} diff --git a/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/workarounds-device-folder-permissions.go b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/workarounds-device-folder-permissions.go new file mode 100644 index 00000000..511eb1fc --- /dev/null +++ b/vendor/github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/workarounds-device-folder-permissions.go @@ -0,0 +1,118 @@ +/** +# Copyright (c) NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +**/ + +package nvcdi + +import ( + "fmt" + "path/filepath" + + "github.com/NVIDIA/nvidia-container-toolkit/internal/discover" + "github.com/NVIDIA/nvidia-container-toolkit/internal/logger" +) + +type deviceFolderPermissions struct { + logger logger.Interface + devRoot string + nvidiaCDIHookPath string + devices discover.Discover +} + +var _ discover.Discover = (*deviceFolderPermissions)(nil) + +// newDeviceFolderPermissionHookDiscoverer creates a discoverer that can be used to update the permissions for the parent folders of nested device nodes from the specified set of device specs. +// This works around an issue with rootless podman when using crun as a low-level runtime. +// See https://github.com/containers/crun/issues/1047 +// The nested devices that are applicable to the NVIDIA GPU devices are: +// - DRM devices at /dev/dri/* +// - NVIDIA Caps devices at /dev/nvidia-caps/* +func newDeviceFolderPermissionHookDiscoverer(logger logger.Interface, devRoot string, nvidiaCDIHookPath string, devices discover.Discover) discover.Discover { + d := &deviceFolderPermissions{ + logger: logger, + devRoot: devRoot, + nvidiaCDIHookPath: nvidiaCDIHookPath, + devices: devices, + } + + return d +} + +// Devices are empty for this discoverer +func (d *deviceFolderPermissions) Devices() ([]discover.Device, error) { + return nil, nil +} + +// Hooks returns a set of hooks that sets the file mode to 755 of parent folders for nested device nodes. +func (d *deviceFolderPermissions) Hooks() ([]discover.Hook, error) { + folders, err := d.getDeviceSubfolders() + if err != nil { + return nil, fmt.Errorf("failed to get device subfolders: %v", err) + } + if len(folders) == 0 { + return nil, nil + } + + args := []string{"--mode", "755"} + for _, folder := range folders { + args = append(args, "--path", folder) + } + + hook := discover.CreateNvidiaCDIHook( + d.nvidiaCDIHookPath, + "chmod", + args..., + ) + + return []discover.Hook{hook}, nil +} + +func (d *deviceFolderPermissions) getDeviceSubfolders() ([]string, error) { + // For now we only consider the following special case paths + allowedPaths := map[string]bool{ + "/dev/dri": true, + "/dev/nvidia-caps": true, + } + + devices, err := d.devices.Devices() + if err != nil { + return nil, fmt.Errorf("failed to get devices: %v", err) + } + + var folders []string + seen := make(map[string]bool) + for _, device := range devices { + df := filepath.Dir(device.Path) + if seen[df] { + continue + } + // We only consider the special case paths + if !allowedPaths[df] { + continue + } + folders = append(folders, df) + seen[df] = true + if len(folders) == len(allowedPaths) { + break + } + } + + return folders, nil +} + +// Mounts are empty for this discoverer +func (d *deviceFolderPermissions) Mounts() ([]discover.Mount, error) { + return nil, nil +} diff --git a/vendor/github.com/fsnotify/fsnotify/.cirrus.yml b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml new file mode 100644 index 00000000..7f257e99 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.cirrus.yml @@ -0,0 +1,14 @@ +freebsd_task: + name: 'FreeBSD' + freebsd_instance: + image_family: freebsd-14-2 + install_script: + - pkg update -f + - pkg install -y go + test_script: + # run tests as user "cirrus" instead of root + - pw useradd cirrus -m + - chown -R cirrus:cirrus . + - FSNOTIFY_BUFFER=4096 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... + - sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race ./... + - FSNOTIFY_DEBUG=1 sudo --preserve-env=FSNOTIFY_BUFFER -u cirrus go test -parallel 1 -race -v ./... diff --git a/vendor/github.com/fsnotify/fsnotify/.gitignore b/vendor/github.com/fsnotify/fsnotify/.gitignore new file mode 100644 index 00000000..daea9dd6 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.gitignore @@ -0,0 +1,10 @@ +# go test -c output +*.test +*.test.exe + +# Output of go build ./cmd/fsnotify +/fsnotify +/fsnotify.exe + +/test/kqueue +/test/a.out diff --git a/vendor/github.com/fsnotify/fsnotify/.mailmap b/vendor/github.com/fsnotify/fsnotify/.mailmap new file mode 100644 index 00000000..a04f2907 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/.mailmap @@ -0,0 +1,2 @@ +Chris Howey +Nathan Youngman <4566+nathany@users.noreply.github.com> diff --git a/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md new file mode 100644 index 00000000..6468d2cf --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/CHANGELOG.md @@ -0,0 +1,602 @@ +# Changelog + +1.9.0 2024-04-04 +---------------- + +### Changes and fixes + +- all: make BufferedWatcher buffered again ([#657]) + +- inotify: fix race when adding/removing watches while a watched path is being + deleted ([#678], [#686]) + +- inotify: don't send empty event if a watched path is unmounted ([#655]) + +- inotify: don't register duplicate watches when watching both a symlink and its + target; previously that would get "half-added" and removing the second would + panic ([#679]) + +- kqueue: fix watching relative symlinks ([#681]) + +- kqueue: correctly mark pre-existing entries when watching a link to a dir on + kqueue ([#682]) + +- illumos: don't send error if changed file is deleted while processing the + event ([#678]) + + +[#657]: https://github.com/fsnotify/fsnotify/pull/657 +[#678]: https://github.com/fsnotify/fsnotify/pull/678 +[#686]: https://github.com/fsnotify/fsnotify/pull/686 +[#655]: https://github.com/fsnotify/fsnotify/pull/655 +[#681]: https://github.com/fsnotify/fsnotify/pull/681 +[#679]: https://github.com/fsnotify/fsnotify/pull/679 +[#682]: https://github.com/fsnotify/fsnotify/pull/682 + +1.8.0 2024-10-31 +---------------- + +### Additions + +- all: add `FSNOTIFY_DEBUG` to print debug logs to stderr ([#619]) + +### Changes and fixes + +- windows: fix behaviour of `WatchList()` to be consistent with other platforms ([#610]) + +- kqueue: ignore events with Ident=0 ([#590]) + +- kqueue: set O_CLOEXEC to prevent passing file descriptors to children ([#617]) + +- kqueue: emit events as "/path/dir/file" instead of "path/link/file" when watching a symlink ([#625]) + +- inotify: don't send event for IN_DELETE_SELF when also watching the parent ([#620]) + +- inotify: fix panic when calling Remove() in a goroutine ([#650]) + +- fen: allow watching subdirectories of watched directories ([#621]) + +[#590]: https://github.com/fsnotify/fsnotify/pull/590 +[#610]: https://github.com/fsnotify/fsnotify/pull/610 +[#617]: https://github.com/fsnotify/fsnotify/pull/617 +[#619]: https://github.com/fsnotify/fsnotify/pull/619 +[#620]: https://github.com/fsnotify/fsnotify/pull/620 +[#621]: https://github.com/fsnotify/fsnotify/pull/621 +[#625]: https://github.com/fsnotify/fsnotify/pull/625 +[#650]: https://github.com/fsnotify/fsnotify/pull/650 + +1.7.0 - 2023-10-22 +------------------ +This version of fsnotify needs Go 1.17. + +### Additions + +- illumos: add FEN backend to support illumos and Solaris. ([#371]) + +- all: add `NewBufferedWatcher()` to use a buffered channel, which can be useful + in cases where you can't control the kernel buffer and receive a large number + of events in bursts. ([#550], [#572]) + +- all: add `AddWith()`, which is identical to `Add()` but allows passing + options. ([#521]) + +- windows: allow setting the ReadDirectoryChangesW() buffer size with + `fsnotify.WithBufferSize()`; the default of 64K is the highest value that + works on all platforms and is enough for most purposes, but in some cases a + highest buffer is needed. ([#521]) + +### Changes and fixes + +- inotify: remove watcher if a watched path is renamed ([#518]) + + After a rename the reported name wasn't updated, or even an empty string. + Inotify doesn't provide any good facilities to update it, so just remove the + watcher. This is already how it worked on kqueue and FEN. + + On Windows this does work, and remains working. + +- windows: don't listen for file attribute changes ([#520]) + + File attribute changes are sent as `FILE_ACTION_MODIFIED` by the Windows API, + with no way to see if they're a file write or attribute change, so would show + up as a fsnotify.Write event. This is never useful, and could result in many + spurious Write events. + +- windows: return `ErrEventOverflow` if the buffer is full ([#525]) + + Before it would merely return "short read", making it hard to detect this + error. + +- kqueue: make sure events for all files are delivered properly when removing a + watched directory ([#526]) + + Previously they would get sent with `""` (empty string) or `"."` as the path + name. + +- kqueue: don't emit spurious Create events for symbolic links ([#524]) + + The link would get resolved but kqueue would "forget" it already saw the link + itself, resulting on a Create for every Write event for the directory. + +- all: return `ErrClosed` on `Add()` when the watcher is closed ([#516]) + +- other: add `Watcher.Errors` and `Watcher.Events` to the no-op `Watcher` in + `backend_other.go`, making it easier to use on unsupported platforms such as + WASM, AIX, etc. ([#528]) + +- other: use the `backend_other.go` no-op if the `appengine` build tag is set; + Google AppEngine forbids usage of the unsafe package so the inotify backend + won't compile there. + +[#371]: https://github.com/fsnotify/fsnotify/pull/371 +[#516]: https://github.com/fsnotify/fsnotify/pull/516 +[#518]: https://github.com/fsnotify/fsnotify/pull/518 +[#520]: https://github.com/fsnotify/fsnotify/pull/520 +[#521]: https://github.com/fsnotify/fsnotify/pull/521 +[#524]: https://github.com/fsnotify/fsnotify/pull/524 +[#525]: https://github.com/fsnotify/fsnotify/pull/525 +[#526]: https://github.com/fsnotify/fsnotify/pull/526 +[#528]: https://github.com/fsnotify/fsnotify/pull/528 +[#537]: https://github.com/fsnotify/fsnotify/pull/537 +[#550]: https://github.com/fsnotify/fsnotify/pull/550 +[#572]: https://github.com/fsnotify/fsnotify/pull/572 + +1.6.0 - 2022-10-13 +------------------ +This version of fsnotify needs Go 1.16 (this was already the case since 1.5.1, +but not documented). It also increases the minimum Linux version to 2.6.32. + +### Additions + +- all: add `Event.Has()` and `Op.Has()` ([#477]) + + This makes checking events a lot easier; for example: + + if event.Op&Write == Write && !(event.Op&Remove == Remove) { + } + + Becomes: + + if event.Has(Write) && !event.Has(Remove) { + } + +- all: add cmd/fsnotify ([#463]) + + A command-line utility for testing and some examples. + +### Changes and fixes + +- inotify: don't ignore events for files that don't exist ([#260], [#470]) + + Previously the inotify watcher would call `os.Lstat()` to check if a file + still exists before emitting events. + + This was inconsistent with other platforms and resulted in inconsistent event + reporting (e.g. when a file is quickly removed and re-created), and generally + a source of confusion. It was added in 2013 to fix a memory leak that no + longer exists. + +- all: return `ErrNonExistentWatch` when `Remove()` is called on a path that's + not watched ([#460]) + +- inotify: replace epoll() with non-blocking inotify ([#434]) + + Non-blocking inotify was not generally available at the time this library was + written in 2014, but now it is. As a result, the minimum Linux version is + bumped from 2.6.27 to 2.6.32. This hugely simplifies the code and is faster. + +- kqueue: don't check for events every 100ms ([#480]) + + The watcher would wake up every 100ms, even when there was nothing to do. Now + it waits until there is something to do. + +- macos: retry opening files on EINTR ([#475]) + +- kqueue: skip unreadable files ([#479]) + + kqueue requires a file descriptor for every file in a directory; this would + fail if a file was unreadable by the current user. Now these files are simply + skipped. + +- windows: fix renaming a watched directory if the parent is also watched ([#370]) + +- windows: increase buffer size from 4K to 64K ([#485]) + +- windows: close file handle on Remove() ([#288]) + +- kqueue: put pathname in the error if watching a file fails ([#471]) + +- inotify, windows: calling Close() more than once could race ([#465]) + +- kqueue: improve Close() performance ([#233]) + +- all: various documentation additions and clarifications. + +[#233]: https://github.com/fsnotify/fsnotify/pull/233 +[#260]: https://github.com/fsnotify/fsnotify/pull/260 +[#288]: https://github.com/fsnotify/fsnotify/pull/288 +[#370]: https://github.com/fsnotify/fsnotify/pull/370 +[#434]: https://github.com/fsnotify/fsnotify/pull/434 +[#460]: https://github.com/fsnotify/fsnotify/pull/460 +[#463]: https://github.com/fsnotify/fsnotify/pull/463 +[#465]: https://github.com/fsnotify/fsnotify/pull/465 +[#470]: https://github.com/fsnotify/fsnotify/pull/470 +[#471]: https://github.com/fsnotify/fsnotify/pull/471 +[#475]: https://github.com/fsnotify/fsnotify/pull/475 +[#477]: https://github.com/fsnotify/fsnotify/pull/477 +[#479]: https://github.com/fsnotify/fsnotify/pull/479 +[#480]: https://github.com/fsnotify/fsnotify/pull/480 +[#485]: https://github.com/fsnotify/fsnotify/pull/485 + +## [1.5.4] - 2022-04-25 + +* Windows: add missing defer to `Watcher.WatchList` [#447](https://github.com/fsnotify/fsnotify/pull/447) +* go.mod: use latest x/sys [#444](https://github.com/fsnotify/fsnotify/pull/444) +* Fix compilation for OpenBSD [#443](https://github.com/fsnotify/fsnotify/pull/443) + +## [1.5.3] - 2022-04-22 + +* This version is retracted. An incorrect branch is published accidentally [#445](https://github.com/fsnotify/fsnotify/issues/445) + +## [1.5.2] - 2022-04-21 + +* Add a feature to return the directories and files that are being monitored [#374](https://github.com/fsnotify/fsnotify/pull/374) +* Fix potential crash on windows if `raw.FileNameLength` exceeds `syscall.MAX_PATH` [#361](https://github.com/fsnotify/fsnotify/pull/361) +* Allow build on unsupported GOOS [#424](https://github.com/fsnotify/fsnotify/pull/424) +* Don't set `poller.fd` twice in `newFdPoller` [#406](https://github.com/fsnotify/fsnotify/pull/406) +* fix go vet warnings: call to `(*T).Fatalf` from a non-test goroutine [#416](https://github.com/fsnotify/fsnotify/pull/416) + +## [1.5.1] - 2021-08-24 + +* Revert Add AddRaw to not follow symlinks [#394](https://github.com/fsnotify/fsnotify/pull/394) + +## [1.5.0] - 2021-08-20 + +* Go: Increase minimum required version to Go 1.12 [#381](https://github.com/fsnotify/fsnotify/pull/381) +* Feature: Add AddRaw method which does not follow symlinks when adding a watch [#289](https://github.com/fsnotify/fsnotify/pull/298) +* Windows: Follow symlinks by default like on all other systems [#289](https://github.com/fsnotify/fsnotify/pull/289) +* CI: Use GitHub Actions for CI and cover go 1.12-1.17 + [#378](https://github.com/fsnotify/fsnotify/pull/378) + [#381](https://github.com/fsnotify/fsnotify/pull/381) + [#385](https://github.com/fsnotify/fsnotify/pull/385) +* Go 1.14+: Fix unsafe pointer conversion [#325](https://github.com/fsnotify/fsnotify/pull/325) + +## [1.4.9] - 2020-03-11 + +* Move example usage to the readme #329. This may resolve #328. + +## [1.4.8] - 2020-03-10 + +* CI: test more go versions (@nathany 1d13583d846ea9d66dcabbfefbfb9d8e6fb05216) +* Tests: Queued inotify events could have been read by the test before max_queued_events was hit (@matthias-stone #265) +* Tests: t.Fatalf -> t.Errorf in go routines (@gdey #266) +* CI: Less verbosity (@nathany #267) +* Tests: Darwin: Exchangedata is deprecated on 10.13 (@nathany #267) +* Tests: Check if channels are closed in the example (@alexeykazakov #244) +* CI: Only run golint on latest version of go and fix issues (@cpuguy83 #284) +* CI: Add windows to travis matrix (@cpuguy83 #284) +* Docs: Remover appveyor badge (@nathany 11844c0959f6fff69ba325d097fce35bd85a8e93) +* Linux: create epoll and pipe fds with close-on-exec (@JohannesEbke #219) +* Linux: open files with close-on-exec (@linxiulei #273) +* Docs: Plan to support fanotify (@nathany ab058b44498e8b7566a799372a39d150d9ea0119 ) +* Project: Add go.mod (@nathany #309) +* Project: Revise editor config (@nathany #309) +* Project: Update copyright for 2019 (@nathany #309) +* CI: Drop go1.8 from CI matrix (@nathany #309) +* Docs: Updating the FAQ section for supportability with NFS & FUSE filesystems (@Pratik32 4bf2d1fec78374803a39307bfb8d340688f4f28e ) + +## [1.4.7] - 2018-01-09 + +* BSD/macOS: Fix possible deadlock on closing the watcher on kqueue (thanks @nhooyr and @glycerine) +* Tests: Fix missing verb on format string (thanks @rchiossi) +* Linux: Fix deadlock in Remove (thanks @aarondl) +* Linux: Watch.Add improvements (avoid race, fix consistency, reduce garbage) (thanks @twpayne) +* Docs: Moved FAQ into the README (thanks @vahe) +* Linux: Properly handle inotify's IN_Q_OVERFLOW event (thanks @zeldovich) +* Docs: replace references to OS X with macOS + +## [1.4.2] - 2016-10-10 + +* Linux: use InotifyInit1 with IN_CLOEXEC to stop leaking a file descriptor to a child process when using fork/exec [#178](https://github.com/fsnotify/fsnotify/pull/178) (thanks @pattyshack) + +## [1.4.1] - 2016-10-04 + +* Fix flaky inotify stress test on Linux [#177](https://github.com/fsnotify/fsnotify/pull/177) (thanks @pattyshack) + +## [1.4.0] - 2016-10-01 + +* add a String() method to Event.Op [#165](https://github.com/fsnotify/fsnotify/pull/165) (thanks @oozie) + +## [1.3.1] - 2016-06-28 + +* Windows: fix for double backslash when watching the root of a drive [#151](https://github.com/fsnotify/fsnotify/issues/151) (thanks @brunoqc) + +## [1.3.0] - 2016-04-19 + +* Support linux/arm64 by [patching](https://go-review.googlesource.com/#/c/21971/) x/sys/unix and switching to to it from syscall (thanks @suihkulokki) [#135](https://github.com/fsnotify/fsnotify/pull/135) + +## [1.2.10] - 2016-03-02 + +* Fix golint errors in windows.go [#121](https://github.com/fsnotify/fsnotify/pull/121) (thanks @tiffanyfj) + +## [1.2.9] - 2016-01-13 + +kqueue: Fix logic for CREATE after REMOVE [#111](https://github.com/fsnotify/fsnotify/pull/111) (thanks @bep) + +## [1.2.8] - 2015-12-17 + +* kqueue: fix race condition in Close [#105](https://github.com/fsnotify/fsnotify/pull/105) (thanks @djui for reporting the issue and @ppknap for writing a failing test) +* inotify: fix race in test +* enable race detection for continuous integration (Linux, Mac, Windows) + +## [1.2.5] - 2015-10-17 + +* inotify: use epoll_create1 for arm64 support (requires Linux 2.6.27 or later) [#100](https://github.com/fsnotify/fsnotify/pull/100) (thanks @suihkulokki) +* inotify: fix path leaks [#73](https://github.com/fsnotify/fsnotify/pull/73) (thanks @chamaken) +* kqueue: watch for rename events on subdirectories [#83](https://github.com/fsnotify/fsnotify/pull/83) (thanks @guotie) +* kqueue: avoid infinite loops from symlinks cycles [#101](https://github.com/fsnotify/fsnotify/pull/101) (thanks @illicitonion) + +## [1.2.1] - 2015-10-14 + +* kqueue: don't watch named pipes [#98](https://github.com/fsnotify/fsnotify/pull/98) (thanks @evanphx) + +## [1.2.0] - 2015-02-08 + +* inotify: use epoll to wake up readEvents [#66](https://github.com/fsnotify/fsnotify/pull/66) (thanks @PieterD) +* inotify: closing watcher should now always shut down goroutine [#63](https://github.com/fsnotify/fsnotify/pull/63) (thanks @PieterD) +* kqueue: close kqueue after removing watches, fixes [#59](https://github.com/fsnotify/fsnotify/issues/59) + +## [1.1.1] - 2015-02-05 + +* inotify: Retry read on EINTR [#61](https://github.com/fsnotify/fsnotify/issues/61) (thanks @PieterD) + +## [1.1.0] - 2014-12-12 + +* kqueue: rework internals [#43](https://github.com/fsnotify/fsnotify/pull/43) + * add low-level functions + * only need to store flags on directories + * less mutexes [#13](https://github.com/fsnotify/fsnotify/issues/13) + * done can be an unbuffered channel + * remove calls to os.NewSyscallError +* More efficient string concatenation for Event.String() [#52](https://github.com/fsnotify/fsnotify/pull/52) (thanks @mdlayher) +* kqueue: fix regression in rework causing subdirectories to be watched [#48](https://github.com/fsnotify/fsnotify/issues/48) +* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) + +## [1.0.4] - 2014-09-07 + +* kqueue: add dragonfly to the build tags. +* Rename source code files, rearrange code so exported APIs are at the top. +* Add done channel to example code. [#37](https://github.com/fsnotify/fsnotify/pull/37) (thanks @chenyukang) + +## [1.0.3] - 2014-08-19 + +* [Fix] Windows MOVED_TO now translates to Create like on BSD and Linux. [#36](https://github.com/fsnotify/fsnotify/issues/36) + +## [1.0.2] - 2014-08-17 + +* [Fix] Missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) +* [Fix] Make ./path and path equivalent. (thanks @zhsso) + +## [1.0.0] - 2014-08-15 + +* [API] Remove AddWatch on Windows, use Add. +* Improve documentation for exported identifiers. [#30](https://github.com/fsnotify/fsnotify/issues/30) +* Minor updates based on feedback from golint. + +## dev / 2014-07-09 + +* Moved to [github.com/fsnotify/fsnotify](https://github.com/fsnotify/fsnotify). +* Use os.NewSyscallError instead of returning errno (thanks @hariharan-uno) + +## dev / 2014-07-04 + +* kqueue: fix incorrect mutex used in Close() +* Update example to demonstrate usage of Op. + +## dev / 2014-06-28 + +* [API] Don't set the Write Op for attribute notifications [#4](https://github.com/fsnotify/fsnotify/issues/4) +* Fix for String() method on Event (thanks Alex Brainman) +* Don't build on Plan 9 or Solaris (thanks @4ad) + +## dev / 2014-06-21 + +* Events channel of type Event rather than *Event. +* [internal] use syscall constants directly for inotify and kqueue. +* [internal] kqueue: rename events to kevents and fileEvent to event. + +## dev / 2014-06-19 + +* Go 1.3+ required on Windows (uses syscall.ERROR_MORE_DATA internally). +* [internal] remove cookie from Event struct (unused). +* [internal] Event struct has the same definition across every OS. +* [internal] remove internal watch and removeWatch methods. + +## dev / 2014-06-12 + +* [API] Renamed Watch() to Add() and RemoveWatch() to Remove(). +* [API] Pluralized channel names: Events and Errors. +* [API] Renamed FileEvent struct to Event. +* [API] Op constants replace methods like IsCreate(). + +## dev / 2014-06-12 + +* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) + +## dev / 2014-05-23 + +* [API] Remove current implementation of WatchFlags. + * current implementation doesn't take advantage of OS for efficiency + * provides little benefit over filtering events as they are received, but has extra bookkeeping and mutexes + * no tests for the current implementation + * not fully implemented on Windows [#93](https://github.com/howeyc/fsnotify/issues/93#issuecomment-39285195) + +## [0.9.3] - 2014-12-31 + +* kqueue: cleanup internal watch before sending remove event [#51](https://github.com/fsnotify/fsnotify/issues/51) + +## [0.9.2] - 2014-08-17 + +* [Backport] Fix missing create events on macOS. [#14](https://github.com/fsnotify/fsnotify/issues/14) (thanks @zhsso) + +## [0.9.1] - 2014-06-12 + +* Fix data race on kevent buffer (thanks @tilaks) [#98](https://github.com/howeyc/fsnotify/pull/98) + +## [0.9.0] - 2014-01-17 + +* IsAttrib() for events that only concern a file's metadata [#79][] (thanks @abustany) +* [Fix] kqueue: fix deadlock [#77][] (thanks @cespare) +* [NOTICE] Development has moved to `code.google.com/p/go.exp/fsnotify` in preparation for inclusion in the Go standard library. + +## [0.8.12] - 2013-11-13 + +* [API] Remove FD_SET and friends from Linux adapter + +## [0.8.11] - 2013-11-02 + +* [Doc] Add Changelog [#72][] (thanks @nathany) +* [Doc] Spotlight and double modify events on macOS [#62][] (reported by @paulhammond) + +## [0.8.10] - 2013-10-19 + +* [Fix] kqueue: remove file watches when parent directory is removed [#71][] (reported by @mdwhatcott) +* [Fix] kqueue: race between Close and readEvents [#70][] (reported by @bernerdschaefer) +* [Doc] specify OS-specific limits in README (thanks @debrando) + +## [0.8.9] - 2013-09-08 + +* [Doc] Contributing (thanks @nathany) +* [Doc] update package path in example code [#63][] (thanks @paulhammond) +* [Doc] GoCI badge in README (Linux only) [#60][] +* [Doc] Cross-platform testing with Vagrant [#59][] (thanks @nathany) + +## [0.8.8] - 2013-06-17 + +* [Fix] Windows: handle `ERROR_MORE_DATA` on Windows [#49][] (thanks @jbowtie) + +## [0.8.7] - 2013-06-03 + +* [API] Make syscall flags internal +* [Fix] inotify: ignore event changes +* [Fix] race in symlink test [#45][] (reported by @srid) +* [Fix] tests on Windows +* lower case error messages + +## [0.8.6] - 2013-05-23 + +* kqueue: Use EVT_ONLY flag on Darwin +* [Doc] Update README with full example + +## [0.8.5] - 2013-05-09 + +* [Fix] inotify: allow monitoring of "broken" symlinks (thanks @tsg) + +## [0.8.4] - 2013-04-07 + +* [Fix] kqueue: watch all file events [#40][] (thanks @ChrisBuchholz) + +## [0.8.3] - 2013-03-13 + +* [Fix] inoitfy/kqueue memory leak [#36][] (reported by @nbkolchin) +* [Fix] kqueue: use fsnFlags for watching a directory [#33][] (reported by @nbkolchin) + +## [0.8.2] - 2013-02-07 + +* [Doc] add Authors +* [Fix] fix data races for map access [#29][] (thanks @fsouza) + +## [0.8.1] - 2013-01-09 + +* [Fix] Windows path separators +* [Doc] BSD License + +## [0.8.0] - 2012-11-09 + +* kqueue: directory watching improvements (thanks @vmirage) +* inotify: add `IN_MOVED_TO` [#25][] (requested by @cpisto) +* [Fix] kqueue: deleting watched directory [#24][] (reported by @jakerr) + +## [0.7.4] - 2012-10-09 + +* [Fix] inotify: fixes from https://codereview.appspot.com/5418045/ (ugorji) +* [Fix] kqueue: preserve watch flags when watching for delete [#21][] (reported by @robfig) +* [Fix] kqueue: watch the directory even if it isn't a new watch (thanks @robfig) +* [Fix] kqueue: modify after recreation of file + +## [0.7.3] - 2012-09-27 + +* [Fix] kqueue: watch with an existing folder inside the watched folder (thanks @vmirage) +* [Fix] kqueue: no longer get duplicate CREATE events + +## [0.7.2] - 2012-09-01 + +* kqueue: events for created directories + +## [0.7.1] - 2012-07-14 + +* [Fix] for renaming files + +## [0.7.0] - 2012-07-02 + +* [Feature] FSNotify flags +* [Fix] inotify: Added file name back to event path + +## [0.6.0] - 2012-06-06 + +* kqueue: watch files after directory created (thanks @tmc) + +## [0.5.1] - 2012-05-22 + +* [Fix] inotify: remove all watches before Close() + +## [0.5.0] - 2012-05-03 + +* [API] kqueue: return errors during watch instead of sending over channel +* kqueue: match symlink behavior on Linux +* inotify: add `DELETE_SELF` (requested by @taralx) +* [Fix] kqueue: handle EINTR (reported by @robfig) +* [Doc] Godoc example [#1][] (thanks @davecheney) + +## [0.4.0] - 2012-03-30 + +* Go 1 released: build with go tool +* [Feature] Windows support using winfsnotify +* Windows does not have attribute change notifications +* Roll attribute notifications into IsModify + +## [0.3.0] - 2012-02-19 + +* kqueue: add files when watch directory + +## [0.2.0] - 2011-12-30 + +* update to latest Go weekly code + +## [0.1.0] - 2011-10-19 + +* kqueue: add watch on file creation to match inotify +* kqueue: create file event +* inotify: ignore `IN_IGNORED` events +* event String() +* linux: common FileEvent functions +* initial commit + +[#79]: https://github.com/howeyc/fsnotify/pull/79 +[#77]: https://github.com/howeyc/fsnotify/pull/77 +[#72]: https://github.com/howeyc/fsnotify/issues/72 +[#71]: https://github.com/howeyc/fsnotify/issues/71 +[#70]: https://github.com/howeyc/fsnotify/issues/70 +[#63]: https://github.com/howeyc/fsnotify/issues/63 +[#62]: https://github.com/howeyc/fsnotify/issues/62 +[#60]: https://github.com/howeyc/fsnotify/issues/60 +[#59]: https://github.com/howeyc/fsnotify/issues/59 +[#49]: https://github.com/howeyc/fsnotify/issues/49 +[#45]: https://github.com/howeyc/fsnotify/issues/45 +[#40]: https://github.com/howeyc/fsnotify/issues/40 +[#36]: https://github.com/howeyc/fsnotify/issues/36 +[#33]: https://github.com/howeyc/fsnotify/issues/33 +[#29]: https://github.com/howeyc/fsnotify/issues/29 +[#25]: https://github.com/howeyc/fsnotify/issues/25 +[#24]: https://github.com/howeyc/fsnotify/issues/24 +[#21]: https://github.com/howeyc/fsnotify/issues/21 diff --git a/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md new file mode 100644 index 00000000..4cc40fa5 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/CONTRIBUTING.md @@ -0,0 +1,145 @@ +Thank you for your interest in contributing to fsnotify! We try to review and +merge PRs in a reasonable timeframe, but please be aware that: + +- To avoid "wasted" work, please discuss changes on the issue tracker first. You + can just send PRs, but they may end up being rejected for one reason or the + other. + +- fsnotify is a cross-platform library, and changes must work reasonably well on + all supported platforms. + +- Changes will need to be compatible; old code should still compile, and the + runtime behaviour can't change in ways that are likely to lead to problems for + users. + +Testing +------- +Just `go test ./...` runs all the tests; the CI runs this on all supported +platforms. Testing different platforms locally can be done with something like +[goon] or [Vagrant], but this isn't super-easy to set up at the moment. + +Use the `-short` flag to make the "stress test" run faster. + +Writing new tests +----------------- +Scripts in the testdata directory allow creating test cases in a "shell-like" +syntax. The basic format is: + + script + + Output: + desired output + +For example: + + # Create a new empty file with some data. + watch / + echo data >/file + + Output: + create /file + write /file + +Just create a new file to add a new test; select which tests to run with +`-run TestScript/[path]`. + +script +------ +The script is a "shell-like" script: + + cmd arg arg + +Comments are supported with `#`: + + # Comment + cmd arg arg # Comment + +All operations are done in a temp directory; a path like "/foo" is rewritten to +"/tmp/TestFoo/foo". + +Arguments can be quoted with `"` or `'`; there are no escapes and they're +functionally identical right now, but this may change in the future, so best to +assume shell-like rules. + + touch "/file with spaces" + +End-of-line escapes with `\` are not supported. + +### Supported commands + + watch path [ops] # Watch the path, reporting events for it. Nothing is + # watched by default. Optionally a list of ops can be + # given, as with AddWith(path, WithOps(...)). + unwatch path # Stop watching the path. + watchlist n # Assert watchlist length. + + stop # Stop running the script; for debugging. + debug [yes/no] # Enable/disable FSNOTIFY_DEBUG (tests are run in + parallel by default, so -parallel=1 is probably a good + idea). + print [any strings] # Print text to stdout; for debugging. + + touch path + mkdir [-p] dir + ln -s target link # Only ln -s supported. + mkfifo path + mknod dev path + mv src dst + rm [-r] path + chmod mode path # Octal only + sleep time-in-ms + + cat path # Read path (does nothing with the data; just reads it). + echo str >>path # Append "str" to "path". + echo str >path # Truncate "path" and write "str". + + require reason # Skip the test if "reason" is true; "skip" and + skip reason # "require" behave identical; it supports both for + # readability. Possible reasons are: + # + # always Always skip this test. + # symlink Symlinks are supported (requires admin + # permissions on Windows). + # mkfifo Platform doesn't support FIFO named sockets. + # mknod Platform doesn't support device nodes. + + +output +------ +After `Output:` the desired output is given; this is indented by convention, but +that's not required. + +The format of that is: + + # Comment + event path # Comment + + system: + event path + system2: + event path + +Every event is one line, and any whitespace between the event and path are +ignored. The path can optionally be surrounded in ". Anything after a "#" is +ignored. + +Platform-specific tests can be added after GOOS; for example: + + watch / + touch /file + + Output: + # Tested if nothing else matches + create /file + + # Windows-specific test. + windows: + write /file + +You can specify multiple platforms with a comma (e.g. "windows, linux:"). +"kqueue" is a shortcut for all kqueue systems (BSD, macOS). + + +[goon]: https://github.com/arp242/goon +[Vagrant]: https://www.vagrantup.com/ +[integration_test.go]: /integration_test.go diff --git a/vendor/github.com/fsnotify/fsnotify/LICENSE b/vendor/github.com/fsnotify/fsnotify/LICENSE new file mode 100644 index 00000000..fb03ade7 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/LICENSE @@ -0,0 +1,25 @@ +Copyright © 2012 The Go Authors. All rights reserved. +Copyright © fsnotify Authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright notice, this + list of conditions and the following disclaimer in the documentation and/or + other materials provided with the distribution. +* Neither the name of Google Inc. nor the names of its contributors may be used + to endorse or promote products derived from this software without specific + prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/fsnotify/fsnotify/README.md b/vendor/github.com/fsnotify/fsnotify/README.md new file mode 100644 index 00000000..1f4eb583 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/README.md @@ -0,0 +1,182 @@ +fsnotify is a Go library to provide cross-platform filesystem notifications on +Windows, Linux, macOS, BSD, and illumos. + +Go 1.17 or newer is required; the full documentation is at +https://pkg.go.dev/github.com/fsnotify/fsnotify + +--- + +Platform support: + +| Backend | OS | Status | +| :-------------------- | :--------- | :------------------------------------------------------------------------ | +| inotify | Linux | Supported | +| kqueue | BSD, macOS | Supported | +| ReadDirectoryChangesW | Windows | Supported | +| FEN | illumos | Supported | +| fanotify | Linux 5.9+ | [Not yet](https://github.com/fsnotify/fsnotify/issues/114) | +| FSEvents | macOS | [Needs support in x/sys/unix][fsevents] | +| USN Journals | Windows | [Needs support in x/sys/windows][usn] | +| Polling | *All* | [Not yet](https://github.com/fsnotify/fsnotify/issues/9) | + +Linux and illumos should include Android and Solaris, but these are currently +untested. + +[fsevents]: https://github.com/fsnotify/fsnotify/issues/11#issuecomment-1279133120 +[usn]: https://github.com/fsnotify/fsnotify/issues/53#issuecomment-1279829847 + +Usage +----- +A basic example: + +```go +package main + +import ( + "log" + + "github.com/fsnotify/fsnotify" +) + +func main() { + // Create new watcher. + watcher, err := fsnotify.NewWatcher() + if err != nil { + log.Fatal(err) + } + defer watcher.Close() + + // Start listening for events. + go func() { + for { + select { + case event, ok := <-watcher.Events: + if !ok { + return + } + log.Println("event:", event) + if event.Has(fsnotify.Write) { + log.Println("modified file:", event.Name) + } + case err, ok := <-watcher.Errors: + if !ok { + return + } + log.Println("error:", err) + } + } + }() + + // Add a path. + err = watcher.Add("/tmp") + if err != nil { + log.Fatal(err) + } + + // Block main goroutine forever. + <-make(chan struct{}) +} +``` + +Some more examples can be found in [cmd/fsnotify](cmd/fsnotify), which can be +run with: + + % go run ./cmd/fsnotify + +Further detailed documentation can be found in godoc: +https://pkg.go.dev/github.com/fsnotify/fsnotify + +FAQ +--- +### Will a file still be watched when it's moved to another directory? +No, not unless you are watching the location it was moved to. + +### Are subdirectories watched? +No, you must add watches for any directory you want to watch (a recursive +watcher is on the roadmap: [#18]). + +[#18]: https://github.com/fsnotify/fsnotify/issues/18 + +### Do I have to watch the Error and Event channels in a goroutine? +Yes. You can read both channels in the same goroutine using `select` (you don't +need a separate goroutine for both channels; see the example). + +### Why don't notifications work with NFS, SMB, FUSE, /proc, or /sys? +fsnotify requires support from underlying OS to work. The current NFS and SMB +protocols does not provide network level support for file notifications, and +neither do the /proc and /sys virtual filesystems. + +This could be fixed with a polling watcher ([#9]), but it's not yet implemented. + +[#9]: https://github.com/fsnotify/fsnotify/issues/9 + +### Why do I get many Chmod events? +Some programs may generate a lot of attribute changes; for example Spotlight on +macOS, anti-virus programs, backup applications, and some others are known to do +this. As a rule, it's typically best to ignore Chmod events. They're often not +useful, and tend to cause problems. + +Spotlight indexing on macOS can result in multiple events (see [#15]). A +temporary workaround is to add your folder(s) to the *Spotlight Privacy +settings* until we have a native FSEvents implementation (see [#11]). + +[#11]: https://github.com/fsnotify/fsnotify/issues/11 +[#15]: https://github.com/fsnotify/fsnotify/issues/15 + +### Watching a file doesn't work well +Watching individual files (rather than directories) is generally not recommended +as many programs (especially editors) update files atomically: it will write to +a temporary file which is then moved to to destination, overwriting the original +(or some variant thereof). The watcher on the original file is now lost, as that +no longer exists. + +The upshot of this is that a power failure or crash won't leave a half-written +file. + +Watch the parent directory and use `Event.Name` to filter out files you're not +interested in. There is an example of this in `cmd/fsnotify/file.go`. + +Platform-specific notes +----------------------- +### Linux +When a file is removed a REMOVE event won't be emitted until all file +descriptors are closed; it will emit a CHMOD instead: + + fp := os.Open("file") + os.Remove("file") // CHMOD + fp.Close() // REMOVE + +This is the event that inotify sends, so not much can be changed about this. + +The `fs.inotify.max_user_watches` sysctl variable specifies the upper limit for +the number of watches per user, and `fs.inotify.max_user_instances` specifies +the maximum number of inotify instances per user. Every Watcher you create is an +"instance", and every path you add is a "watch". + +These are also exposed in `/proc` as `/proc/sys/fs/inotify/max_user_watches` and +`/proc/sys/fs/inotify/max_user_instances` + +To increase them you can use `sysctl` or write the value to proc file: + + # The default values on Linux 5.18 + sysctl fs.inotify.max_user_watches=124983 + sysctl fs.inotify.max_user_instances=128 + +To make the changes persist on reboot edit `/etc/sysctl.conf` or +`/usr/lib/sysctl.d/50-default.conf` (details differ per Linux distro; check your +distro's documentation): + + fs.inotify.max_user_watches=124983 + fs.inotify.max_user_instances=128 + +Reaching the limit will result in a "no space left on device" or "too many open +files" error. + +### kqueue (macOS, all BSD systems) +kqueue requires opening a file descriptor for every file that's being watched; +so if you're watching a directory with five files then that's six file +descriptors. You will run in to your system's "max open files" limit faster on +these platforms. + +The sysctl variables `kern.maxfiles` and `kern.maxfilesperproc` can be used to +control the maximum number of open files. diff --git a/vendor/github.com/fsnotify/fsnotify/backend_fen.go b/vendor/github.com/fsnotify/fsnotify/backend_fen.go new file mode 100644 index 00000000..57fc6928 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_fen.go @@ -0,0 +1,467 @@ +//go:build solaris + +// FEN backend for illumos (supported) and Solaris (untested, but should work). +// +// See port_create(3c) etc. for docs. https://www.illumos.org/man/3C/port_create + +package fsnotify + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sync" + "time" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type fen struct { + *shared + Events chan Event + Errors chan error + + mu sync.Mutex + port *unix.EventPort + dirs map[string]Op // Explicitly watched directories + watches map[string]Op // Explicitly watched non-directories +} + +var defaultBufferSize = 0 + +func newBackend(ev chan Event, errs chan error) (backend, error) { + w := &fen{ + shared: newShared(ev, errs), + Events: ev, + Errors: errs, + dirs: make(map[string]Op), + watches: make(map[string]Op), + } + + var err error + w.port, err = unix.NewEventPort() + if err != nil { + return nil, fmt.Errorf("fsnotify.NewWatcher: %w", err) + } + + go w.readEvents() + return w, nil +} + +func (w *fen) Close() error { + if w.shared.close() { + return nil + } + return w.port.Close() +} + +func (w *fen) Add(name string) error { return w.AddWith(name) } + +func (w *fen) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + // Currently we resolve symlinks that were explicitly requested to be + // watched. Otherwise we would use LStat here. + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Associate all files in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, true, w.associateFile) + if err != nil { + return err + } + + w.mu.Lock() + w.dirs[name] = with.op + w.mu.Unlock() + return nil + } + + err = w.associateFile(name, stat, true) + if err != nil { + return err + } + + w.mu.Lock() + w.watches[name] = with.op + w.mu.Unlock() + return nil +} + +func (w *fen) Remove(name string) error { + if w.isClosed() { + return nil + } + if !w.port.PathIsWatched(name) { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + // The user has expressed an intent. Immediately remove this name from + // whichever watch list it might be in. If it's not in there the delete + // doesn't cause harm. + w.mu.Lock() + delete(w.watches, name) + delete(w.dirs, name) + w.mu.Unlock() + + stat, err := os.Stat(name) + if err != nil { + return err + } + + // Remove associations for every file in the directory. + if stat.IsDir() { + err := w.handleDirectory(name, stat, false, w.dissociateFile) + if err != nil { + return err + } + return nil + } + + err = w.port.DissociatePath(name) + if err != nil { + return err + } + + return nil +} + +// readEvents contains the main loop that runs in a goroutine watching for events. +func (w *fen) readEvents() { + // If this function returns, the watcher has been closed and we can close + // these channels + defer func() { + close(w.Errors) + close(w.Events) + }() + + pevents := make([]unix.PortEvent, 8) + for { + count, err := w.port.Get(pevents, 1, nil) + if err != nil && err != unix.ETIME { + // Interrupted system call (count should be 0) ignore and continue + if errors.Is(err, unix.EINTR) && count == 0 { + continue + } + // Get failed because we called w.Close() + if errors.Is(err, unix.EBADF) && w.isClosed() { + return + } + // There was an error not caused by calling w.Close() + if !w.sendError(fmt.Errorf("port.Get: %w", err)) { + return + } + } + + p := pevents[:count] + for _, pevent := range p { + if pevent.Source != unix.PORT_SOURCE_FILE { + // Event from unexpected source received; should never happen. + if !w.sendError(errors.New("Event from unexpected source received")) { + return + } + continue + } + + if debug { + internal.Debug(pevent.Path, pevent.Events) + } + + err = w.handleEvent(&pevent) + if !w.sendError(err) { + return + } + } + } +} + +func (w *fen) handleDirectory(path string, stat os.FileInfo, follow bool, handler func(string, os.FileInfo, bool) error) error { + files, err := os.ReadDir(path) + if err != nil { + return err + } + + // Handle all children of the directory. + for _, entry := range files { + finfo, err := entry.Info() + if err != nil { + return err + } + err = handler(filepath.Join(path, finfo.Name()), finfo, false) + if err != nil { + return err + } + } + + // And finally handle the directory itself. + return handler(path, stat, follow) +} + +// handleEvent might need to emit more than one fsnotify event if the events +// bitmap matches more than one event type (e.g. the file was both modified and +// had the attributes changed between when the association was created and the +// when event was returned) +func (w *fen) handleEvent(event *unix.PortEvent) error { + var ( + events = event.Events + path = event.Path + fmode = event.Cookie.(os.FileMode) + reRegister = true + ) + + w.mu.Lock() + _, watchedDir := w.dirs[path] + _, watchedPath := w.watches[path] + w.mu.Unlock() + isWatched := watchedDir || watchedPath + + if events&unix.FILE_DELETE != 0 { + if !w.sendEvent(Event{Name: path, Op: Remove}) { + return nil + } + reRegister = false + } + if events&unix.FILE_RENAME_FROM != 0 { + if !w.sendEvent(Event{Name: path, Op: Rename}) { + return nil + } + // Don't keep watching the new file name + reRegister = false + } + if events&unix.FILE_RENAME_TO != 0 { + // We don't report a Rename event for this case, because Rename events + // are interpreted as referring to the _old_ name of the file, and in + // this case the event would refer to the new name of the file. This + // type of rename event is not supported by fsnotify. + + // inotify reports a Remove event in this case, so we simulate this + // here. + if !w.sendEvent(Event{Name: path, Op: Remove}) { + return nil + } + // Don't keep watching the file that was removed + reRegister = false + } + + // The file is gone, nothing left to do. + if !reRegister { + if watchedDir { + w.mu.Lock() + delete(w.dirs, path) + w.mu.Unlock() + } + if watchedPath { + w.mu.Lock() + delete(w.watches, path) + w.mu.Unlock() + } + return nil + } + + // If we didn't get a deletion the file still exists and we're going to have + // to watch it again. Let's Stat it now so that we can compare permissions + // and have what we need to continue watching the file + + stat, err := os.Lstat(path) + if err != nil { + // This is unexpected, but we should still emit an event. This happens + // most often on "rm -r" of a subdirectory inside a watched directory We + // get a modify event of something happening inside, but by the time we + // get here, the sudirectory is already gone. Clearly we were watching + // this path but now it is gone. Let's tell the user that it was + // removed. + if !w.sendEvent(Event{Name: path, Op: Remove}) { + return nil + } + // Suppress extra write events on removed directories; they are not + // informative and can be confusing. + return nil + } + + // resolve symlinks that were explicitly watched as we would have at Add() + // time. this helps suppress spurious Chmod events on watched symlinks + if isWatched { + stat, err = os.Stat(path) + if err != nil { + // The symlink still exists, but the target is gone. Report the + // Remove similar to above. + if !w.sendEvent(Event{Name: path, Op: Remove}) { + return nil + } + // Don't return the error + } + } + + if events&unix.FILE_MODIFIED != 0 { + if fmode.IsDir() && watchedDir { + if err := w.updateDirectory(path); err != nil { + return err + } + } else { + if !w.sendEvent(Event{Name: path, Op: Write}) { + return nil + } + } + } + if events&unix.FILE_ATTRIB != 0 && stat != nil { + // Only send Chmod if perms changed + if stat.Mode().Perm() != fmode.Perm() { + if !w.sendEvent(Event{Name: path, Op: Chmod}) { + return nil + } + } + } + + if stat != nil { + // If we get here, it means we've hit an event above that requires us to + // continue watching the file or directory + err := w.associateFile(path, stat, isWatched) + if errors.Is(err, fs.ErrNotExist) { + // Path may have been removed since the stat. + err = nil + } + return err + } + return nil +} + +// The directory was modified, so we must find unwatched entities and watch +// them. If something was removed from the directory, nothing will happen, as +// everything else should still be watched. +func (w *fen) updateDirectory(path string) error { + files, err := os.ReadDir(path) + if err != nil { + // Directory no longer exists: probably just deleted since we got the + // event. + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + + for _, entry := range files { + path := filepath.Join(path, entry.Name()) + if w.port.PathIsWatched(path) { + continue + } + + finfo, err := entry.Info() + if err != nil { + return err + } + err = w.associateFile(path, finfo, false) + if errors.Is(err, fs.ErrNotExist) { + // File may have disappeared between getting the dir listing and + // adding the port: that's okay to ignore. + continue + } + if !w.sendError(err) { + return nil + } + if !w.sendEvent(Event{Name: path, Op: Create}) { + return nil + } + } + return nil +} + +func (w *fen) associateFile(path string, stat os.FileInfo, follow bool) error { + if w.isClosed() { + return ErrClosed + } + // This is primarily protecting the call to AssociatePath but it is + // important and intentional that the call to PathIsWatched is also + // protected by this mutex. Without this mutex, AssociatePath has been seen + // to error out that the path is already associated. + w.mu.Lock() + defer w.mu.Unlock() + + if w.port.PathIsWatched(path) { + // Remove the old association in favor of this one If we get ENOENT, + // then while the x/sys/unix wrapper still thought that this path was + // associated, the underlying event port did not. This call will have + // cleared up that discrepancy. The most likely cause is that the event + // has fired but we haven't processed it yet. + err := w.port.DissociatePath(path) + if err != nil && !errors.Is(err, unix.ENOENT) { + return fmt.Errorf("port.DissociatePath(%q): %w", path, err) + } + } + + var events int + if !follow { + // Watch symlinks themselves rather than their targets unless this entry + // is explicitly watched. + events |= unix.FILE_NOFOLLOW + } + if true { // TODO: implement withOps() + events |= unix.FILE_MODIFIED + } + if true { + events |= unix.FILE_ATTRIB + } + err := w.port.AssociatePath(path, stat, events, stat.Mode()) + if err != nil { + return fmt.Errorf("port.AssociatePath(%q): %w", path, err) + } + return nil +} + +func (w *fen) dissociateFile(path string, stat os.FileInfo, unused bool) error { + if !w.port.PathIsWatched(path) { + return nil + } + err := w.port.DissociatePath(path) + if err != nil { + return fmt.Errorf("port.DissociatePath(%q): %w", path, err) + } + return nil +} + +func (w *fen) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + + entries := make([]string, 0, len(w.watches)+len(w.dirs)) + for pathname := range w.dirs { + entries = append(entries, pathname) + } + for pathname := range w.watches { + entries = append(entries, pathname) + } + + return entries +} + +func (w *fen) xSupports(op Op) bool { + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_inotify.go b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go new file mode 100644 index 00000000..a36cb89d --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_inotify.go @@ -0,0 +1,583 @@ +//go:build linux && !appengine + +package fsnotify + +import ( + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "strings" + "sync" + "time" + "unsafe" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type inotify struct { + *shared + Events chan Event + Errors chan error + + // Store fd here as os.File.Read() will no longer return on close after + // calling Fd(). See: https://github.com/golang/go/issues/26439 + fd int + inotifyFile *os.File + watches *watches + doneResp chan struct{} // Channel to respond to Close + + // Store rename cookies in an array, with the index wrapping to 0. Almost + // all of the time what we get is a MOVED_FROM to set the cookie and the + // next event inotify sends will be MOVED_TO to read it. However, this is + // not guaranteed – as described in inotify(7) – and we may get other events + // between the two MOVED_* events (including other MOVED_* ones). + // + // A second issue is that moving a file outside the watched directory will + // trigger a MOVED_FROM to set the cookie, but we never see the MOVED_TO to + // read and delete it. So just storing it in a map would slowly leak memory. + // + // Doing it like this gives us a simple fast LRU-cache that won't allocate. + // Ten items should be more than enough for our purpose, and a loop over + // such a short array is faster than a map access anyway (not that it hugely + // matters since we're talking about hundreds of ns at the most, but still). + cookies [10]koekje + cookieIndex uint8 + cookiesMu sync.Mutex +} + +type ( + watches struct { + wd map[uint32]*watch // wd → watch + path map[string]uint32 // pathname → wd + } + watch struct { + wd uint32 // Watch descriptor (as returned by the inotify_add_watch() syscall) + flags uint32 // inotify flags of this watch (see inotify(7) for the list of valid flags) + path string // Watch path. + recurse bool // Recursion with ./...? + } + koekje struct { + cookie uint32 + path string + } +) + +func newWatches() *watches { + return &watches{ + wd: make(map[uint32]*watch), + path: make(map[string]uint32), + } +} + +func (w *watches) byPath(path string) *watch { return w.wd[w.path[path]] } +func (w *watches) byWd(wd uint32) *watch { return w.wd[wd] } +func (w *watches) len() int { return len(w.wd) } +func (w *watches) add(ww *watch) { w.wd[ww.wd] = ww; w.path[ww.path] = ww.wd } +func (w *watches) remove(watch *watch) { delete(w.path, watch.path); delete(w.wd, watch.wd) } + +func (w *watches) removePath(path string) ([]uint32, error) { + path, recurse := recursivePath(path) + wd, ok := w.path[path] + if !ok { + return nil, fmt.Errorf("%w: %s", ErrNonExistentWatch, path) + } + + watch := w.wd[wd] + if recurse && !watch.recurse { + return nil, fmt.Errorf("can't use /... with non-recursive watch %q", path) + } + + delete(w.path, path) + delete(w.wd, wd) + if !watch.recurse { + return []uint32{wd}, nil + } + + wds := make([]uint32, 0, 8) + wds = append(wds, wd) + for p, rwd := range w.path { + if strings.HasPrefix(p, path) { + delete(w.path, p) + delete(w.wd, rwd) + wds = append(wds, rwd) + } + } + return wds, nil +} + +func (w *watches) updatePath(path string, f func(*watch) (*watch, error)) error { + var existing *watch + wd, ok := w.path[path] + if ok { + existing = w.wd[wd] + } + + upd, err := f(existing) + if err != nil { + return err + } + if upd != nil { + w.wd[upd.wd] = upd + w.path[upd.path] = upd.wd + + if upd.wd != wd { + delete(w.wd, wd) + } + } + + return nil +} + +var defaultBufferSize = 0 + +func newBackend(ev chan Event, errs chan error) (backend, error) { + // Need to set nonblocking mode for SetDeadline to work, otherwise blocking + // I/O operations won't terminate on close. + fd, errno := unix.InotifyInit1(unix.IN_CLOEXEC | unix.IN_NONBLOCK) + if fd == -1 { + return nil, errno + } + + w := &inotify{ + shared: newShared(ev, errs), + Events: ev, + Errors: errs, + fd: fd, + inotifyFile: os.NewFile(uintptr(fd), ""), + watches: newWatches(), + doneResp: make(chan struct{}), + } + + go w.readEvents() + return w, nil +} + +func (w *inotify) Close() error { + if w.shared.close() { + return nil + } + + // Causes any blocking reads to return with an error, provided the file + // still supports deadline operations. + err := w.inotifyFile.Close() + if err != nil { + return err + } + + <-w.doneResp // Wait for readEvents() to finish. + return nil +} + +func (w *inotify) Add(name string) error { return w.AddWith(name) } + +func (w *inotify) AddWith(path string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), path) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + add := func(path string, with withOpts, recurse bool) error { + var flags uint32 + if with.noFollow { + flags |= unix.IN_DONT_FOLLOW + } + if with.op.Has(Create) { + flags |= unix.IN_CREATE + } + if with.op.Has(Write) { + flags |= unix.IN_MODIFY + } + if with.op.Has(Remove) { + flags |= unix.IN_DELETE | unix.IN_DELETE_SELF + } + if with.op.Has(Rename) { + flags |= unix.IN_MOVED_TO | unix.IN_MOVED_FROM | unix.IN_MOVE_SELF + } + if with.op.Has(Chmod) { + flags |= unix.IN_ATTRIB + } + if with.op.Has(xUnportableOpen) { + flags |= unix.IN_OPEN + } + if with.op.Has(xUnportableRead) { + flags |= unix.IN_ACCESS + } + if with.op.Has(xUnportableCloseWrite) { + flags |= unix.IN_CLOSE_WRITE + } + if with.op.Has(xUnportableCloseRead) { + flags |= unix.IN_CLOSE_NOWRITE + } + return w.register(path, flags, recurse) + } + + w.mu.Lock() + defer w.mu.Unlock() + path, recurse := recursivePath(path) + if recurse { + return filepath.WalkDir(path, func(root string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if !d.IsDir() { + if root == path { + return fmt.Errorf("fsnotify: not a directory: %q", path) + } + return nil + } + + // Send a Create event when adding new directory from a recursive + // watch; this is for "mkdir -p one/two/three". Usually all those + // directories will be created before we can set up watchers on the + // subdirectories, so only "one" would be sent as a Create event and + // not "one/two" and "one/two/three" (inotifywait -r has the same + // problem). + if with.sendCreate && root != path { + w.sendEvent(Event{Name: root, Op: Create}) + } + + return add(root, with, true) + }) + } + + return add(path, with, false) +} + +func (w *inotify) register(path string, flags uint32, recurse bool) error { + return w.watches.updatePath(path, func(existing *watch) (*watch, error) { + if existing != nil { + flags |= existing.flags | unix.IN_MASK_ADD + } + + wd, err := unix.InotifyAddWatch(w.fd, path, flags) + if wd == -1 { + return nil, err + } + + if e, ok := w.watches.wd[uint32(wd)]; ok { + return e, nil + } + + if existing == nil { + return &watch{ + wd: uint32(wd), + path: path, + flags: flags, + recurse: recurse, + }, nil + } + + existing.wd = uint32(wd) + existing.flags = flags + return existing, nil + }) +} + +func (w *inotify) Remove(name string) error { + if w.isClosed() { + return nil + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + w.mu.Lock() + defer w.mu.Unlock() + return w.remove(filepath.Clean(name)) +} + +func (w *inotify) remove(name string) error { + wds, err := w.watches.removePath(name) + if err != nil { + return err + } + + for _, wd := range wds { + _, err := unix.InotifyRmWatch(w.fd, wd) + if err != nil { + // TODO: Perhaps it's not helpful to return an error here in every + // case; the only two possible errors are: + // + // EBADF, which happens when w.fd is not a valid file descriptor of + // any kind. + // + // EINVAL, which is when fd is not an inotify descriptor or wd is + // not a valid watch descriptor. Watch descriptors are invalidated + // when they are removed explicitly or implicitly; explicitly by + // inotify_rm_watch, implicitly when the file they are watching is + // deleted. + return err + } + } + return nil +} + +func (w *inotify) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + entries := make([]string, 0, w.watches.len()) + for pathname := range w.watches.path { + entries = append(entries, pathname) + } + return entries +} + +// readEvents reads from the inotify file descriptor, converts the +// received events into Event objects and sends them via the Events channel +func (w *inotify) readEvents() { + defer func() { + close(w.doneResp) + close(w.Errors) + close(w.Events) + }() + + var buf [unix.SizeofInotifyEvent * 4096]byte // Buffer for a maximum of 4096 raw events + for { + if w.isClosed() { + return + } + + n, err := w.inotifyFile.Read(buf[:]) + if err != nil { + if errors.Is(err, os.ErrClosed) { + return + } + if !w.sendError(err) { + return + } + continue + } + + if n < unix.SizeofInotifyEvent { + err := errors.New("notify: short read in readEvents()") // Read was too short. + if n == 0 { + err = io.EOF // If EOF is received. This should really never happen. + } + if !w.sendError(err) { + return + } + continue + } + + // We don't know how many events we just read into the buffer While the + // offset points to at least one whole event. + var offset uint32 + for offset <= uint32(n-unix.SizeofInotifyEvent) { + // Point to the event in the buffer. + inEvent := (*unix.InotifyEvent)(unsafe.Pointer(&buf[offset])) + + if inEvent.Mask&unix.IN_Q_OVERFLOW != 0 { + if !w.sendError(ErrEventOverflow) { + return + } + } + + ev, ok := w.handleEvent(inEvent, &buf, offset) + if !ok { + return + } + if !w.sendEvent(ev) { + return + } + + // Move to the next event in the buffer + offset += unix.SizeofInotifyEvent + inEvent.Len + } + } +} + +func (w *inotify) handleEvent(inEvent *unix.InotifyEvent, buf *[65536]byte, offset uint32) (Event, bool) { + w.mu.Lock() + defer w.mu.Unlock() + + /// If the event happened to the watched directory or the watched file, the + /// kernel doesn't append the filename to the event, but we would like to + /// always fill the the "Name" field with a valid filename. We retrieve the + /// path of the watch from the "paths" map. + /// + /// Can be nil if Remove() was called in another goroutine for this path + /// inbetween reading the events from the kernel and reading the internal + /// state. Not much we can do about it, so just skip. See #616. + watch := w.watches.byWd(uint32(inEvent.Wd)) + if watch == nil { + return Event{}, true + } + + var ( + name = watch.path + nameLen = uint32(inEvent.Len) + ) + if nameLen > 0 { + /// Point "bytes" at the first byte of the filename + bb := *buf + bytes := (*[unix.PathMax]byte)(unsafe.Pointer(&bb[offset+unix.SizeofInotifyEvent]))[:nameLen:nameLen] + /// The filename is padded with NULL bytes. TrimRight() gets rid of those. + name += "/" + strings.TrimRight(string(bytes[0:nameLen]), "\x00") + } + + if debug { + internal.Debug(name, inEvent.Mask, inEvent.Cookie) + } + + if inEvent.Mask&unix.IN_IGNORED != 0 || inEvent.Mask&unix.IN_UNMOUNT != 0 { + w.watches.remove(watch) + return Event{}, true + } + + // inotify will automatically remove the watch on deletes; just need + // to clean our state here. + if inEvent.Mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF { + w.watches.remove(watch) + } + + // We can't really update the state when a watched path is moved; only + // IN_MOVE_SELF is sent and not IN_MOVED_{FROM,TO}. So remove the watch. + if inEvent.Mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF { + if watch.recurse { // Do nothing + return Event{}, true + } + + err := w.remove(watch.path) + if err != nil && !errors.Is(err, ErrNonExistentWatch) { + if !w.sendError(err) { + return Event{}, false + } + } + } + + /// Skip if we're watching both this path and the parent; the parent will + /// already send a delete so no need to do it twice. + if inEvent.Mask&unix.IN_DELETE_SELF != 0 { + _, ok := w.watches.path[filepath.Dir(watch.path)] + if ok { + return Event{}, true + } + } + + ev := w.newEvent(name, inEvent.Mask, inEvent.Cookie) + // Need to update watch path for recurse. + if watch.recurse { + isDir := inEvent.Mask&unix.IN_ISDIR == unix.IN_ISDIR + /// New directory created: set up watch on it. + if isDir && ev.Has(Create) { + err := w.register(ev.Name, watch.flags, true) + if !w.sendError(err) { + return Event{}, false + } + + // This was a directory rename, so we need to update all the + // children. + // + // TODO: this is of course pretty slow; we should use a better data + // structure for storing all of this, e.g. store children in the + // watch. I have some code for this in my kqueue refactor we can use + // in the future. For now I'm okay with this as it's not publicly + // available. Correctness first, performance second. + if ev.renamedFrom != "" { + for k, ww := range w.watches.wd { + if k == watch.wd || ww.path == ev.Name { + continue + } + if strings.HasPrefix(ww.path, ev.renamedFrom) { + ww.path = strings.Replace(ww.path, ev.renamedFrom, ev.Name, 1) + w.watches.wd[k] = ww + } + } + } + } + } + + return ev, true +} + +func (w *inotify) isRecursive(path string) bool { + ww := w.watches.byPath(path) + if ww == nil { // path could be a file, so also check the Dir. + ww = w.watches.byPath(filepath.Dir(path)) + } + return ww != nil && ww.recurse +} + +func (w *inotify) newEvent(name string, mask, cookie uint32) Event { + e := Event{Name: name} + if mask&unix.IN_CREATE == unix.IN_CREATE || mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { + e.Op |= Create + } + if mask&unix.IN_DELETE_SELF == unix.IN_DELETE_SELF || mask&unix.IN_DELETE == unix.IN_DELETE { + e.Op |= Remove + } + if mask&unix.IN_MODIFY == unix.IN_MODIFY { + e.Op |= Write + } + if mask&unix.IN_OPEN == unix.IN_OPEN { + e.Op |= xUnportableOpen + } + if mask&unix.IN_ACCESS == unix.IN_ACCESS { + e.Op |= xUnportableRead + } + if mask&unix.IN_CLOSE_WRITE == unix.IN_CLOSE_WRITE { + e.Op |= xUnportableCloseWrite + } + if mask&unix.IN_CLOSE_NOWRITE == unix.IN_CLOSE_NOWRITE { + e.Op |= xUnportableCloseRead + } + if mask&unix.IN_MOVE_SELF == unix.IN_MOVE_SELF || mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { + e.Op |= Rename + } + if mask&unix.IN_ATTRIB == unix.IN_ATTRIB { + e.Op |= Chmod + } + + if cookie != 0 { + if mask&unix.IN_MOVED_FROM == unix.IN_MOVED_FROM { + w.cookiesMu.Lock() + w.cookies[w.cookieIndex] = koekje{cookie: cookie, path: e.Name} + w.cookieIndex++ + if w.cookieIndex > 9 { + w.cookieIndex = 0 + } + w.cookiesMu.Unlock() + } else if mask&unix.IN_MOVED_TO == unix.IN_MOVED_TO { + w.cookiesMu.Lock() + var prev string + for _, c := range w.cookies { + if c.cookie == cookie { + prev = c.path + break + } + } + w.cookiesMu.Unlock() + e.renamedFrom = prev + } + } + return e +} + +func (w *inotify) xSupports(op Op) bool { + return true // Supports everything. +} + +func (w *inotify) state() { + w.mu.Lock() + defer w.mu.Unlock() + for wd, ww := range w.watches.wd { + fmt.Fprintf(os.Stderr, "%4d: recurse=%t %q\n", wd, ww.recurse, ww.path) + } +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go new file mode 100644 index 00000000..340aeec0 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_kqueue.go @@ -0,0 +1,705 @@ +//go:build freebsd || openbsd || netbsd || dragonfly || darwin + +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "runtime" + "sync" + "time" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/unix" +) + +type kqueue struct { + *shared + Events chan Event + Errors chan error + + kq int // File descriptor (as returned by the kqueue() syscall). + closepipe [2]int // Pipe used for closing kq. + watches *watches +} + +type ( + watches struct { + mu sync.RWMutex + wd map[int]watch // wd → watch + path map[string]int // pathname → wd + byDir map[string]map[int]struct{} // dirname(path) → wd + seen map[string]struct{} // Keep track of if we know this file exists. + byUser map[string]struct{} // Watches added with Watcher.Add() + } + watch struct { + wd int + name string + linkName string // In case of links; name is the target, and this is the link. + isDir bool + dirFlags uint32 + } +) + +func newWatches() *watches { + return &watches{ + wd: make(map[int]watch), + path: make(map[string]int), + byDir: make(map[string]map[int]struct{}), + seen: make(map[string]struct{}), + byUser: make(map[string]struct{}), + } +} + +func (w *watches) listPaths(userOnly bool) []string { + w.mu.RLock() + defer w.mu.RUnlock() + + if userOnly { + l := make([]string, 0, len(w.byUser)) + for p := range w.byUser { + l = append(l, p) + } + return l + } + + l := make([]string, 0, len(w.path)) + for p := range w.path { + l = append(l, p) + } + return l +} + +func (w *watches) watchesInDir(path string) []string { + w.mu.RLock() + defer w.mu.RUnlock() + + l := make([]string, 0, 4) + for fd := range w.byDir[path] { + info := w.wd[fd] + if _, ok := w.byUser[info.name]; !ok { + l = append(l, info.name) + } + } + return l +} + +// Mark path as added by the user. +func (w *watches) addUserWatch(path string) { + w.mu.Lock() + defer w.mu.Unlock() + w.byUser[path] = struct{}{} +} + +func (w *watches) addLink(path string, fd int) { + w.mu.Lock() + defer w.mu.Unlock() + + w.path[path] = fd + w.seen[path] = struct{}{} +} + +func (w *watches) add(path, linkPath string, fd int, isDir bool) { + w.mu.Lock() + defer w.mu.Unlock() + + w.path[path] = fd + w.wd[fd] = watch{wd: fd, name: path, linkName: linkPath, isDir: isDir} + + parent := filepath.Dir(path) + byDir, ok := w.byDir[parent] + if !ok { + byDir = make(map[int]struct{}, 1) + w.byDir[parent] = byDir + } + byDir[fd] = struct{}{} +} + +func (w *watches) byWd(fd int) (watch, bool) { + w.mu.RLock() + defer w.mu.RUnlock() + info, ok := w.wd[fd] + return info, ok +} + +func (w *watches) byPath(path string) (watch, bool) { + w.mu.RLock() + defer w.mu.RUnlock() + info, ok := w.wd[w.path[path]] + return info, ok +} + +func (w *watches) updateDirFlags(path string, flags uint32) bool { + w.mu.Lock() + defer w.mu.Unlock() + + fd, ok := w.path[path] + if !ok { // Already deleted: don't re-set it here. + return false + } + info := w.wd[fd] + info.dirFlags = flags + w.wd[fd] = info + return true +} + +func (w *watches) remove(fd int, path string) bool { + w.mu.Lock() + defer w.mu.Unlock() + + isDir := w.wd[fd].isDir + delete(w.path, path) + delete(w.byUser, path) + + parent := filepath.Dir(path) + delete(w.byDir[parent], fd) + + if len(w.byDir[parent]) == 0 { + delete(w.byDir, parent) + } + + delete(w.wd, fd) + delete(w.seen, path) + return isDir +} + +func (w *watches) markSeen(path string, exists bool) { + w.mu.Lock() + defer w.mu.Unlock() + if exists { + w.seen[path] = struct{}{} + } else { + delete(w.seen, path) + } +} + +func (w *watches) seenBefore(path string) bool { + w.mu.RLock() + defer w.mu.RUnlock() + _, ok := w.seen[path] + return ok +} + +var defaultBufferSize = 0 + +func newBackend(ev chan Event, errs chan error) (backend, error) { + kq, closepipe, err := newKqueue() + if err != nil { + return nil, err + } + + w := &kqueue{ + shared: newShared(ev, errs), + Events: ev, + Errors: errs, + kq: kq, + closepipe: closepipe, + watches: newWatches(), + } + + go w.readEvents() + return w, nil +} + +// newKqueue creates a new kernel event queue and returns a descriptor. +// +// This registers a new event on closepipe, which will trigger an event when +// it's closed. This way we can use kevent() without timeout/polling; without +// the closepipe, it would block forever and we wouldn't be able to stop it at +// all. +func newKqueue() (kq int, closepipe [2]int, err error) { + kq, err = unix.Kqueue() + if err != nil { + return kq, closepipe, err + } + + // Register the close pipe. + err = unix.Pipe(closepipe[:]) + if err != nil { + unix.Close(kq) + return kq, closepipe, err + } + unix.CloseOnExec(closepipe[0]) + unix.CloseOnExec(closepipe[1]) + + // Register changes to listen on the closepipe. + changes := make([]unix.Kevent_t, 1) + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[0], closepipe[0], unix.EVFILT_READ, + unix.EV_ADD|unix.EV_ENABLE|unix.EV_ONESHOT) + + ok, err := unix.Kevent(kq, changes, nil, nil) + if ok == -1 { + unix.Close(kq) + unix.Close(closepipe[0]) + unix.Close(closepipe[1]) + return kq, closepipe, err + } + return kq, closepipe, nil +} + +func (w *kqueue) Close() error { + if w.shared.close() { + return nil + } + + pathsToRemove := w.watches.listPaths(false) + for _, name := range pathsToRemove { + w.Remove(name) + } + + unix.Close(w.closepipe[1]) // Send "quit" message to readEvents + return nil +} + +func (w *kqueue) Add(name string) error { return w.AddWith(name) } + +func (w *kqueue) AddWith(name string, opts ...addOpt) error { + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + + _, err := w.addWatch(name, noteAllEvents, false) + if err != nil { + return err + } + w.watches.addUserWatch(name) + return nil +} + +func (w *kqueue) Remove(name string) error { + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), name) + } + return w.remove(name, true) +} + +func (w *kqueue) remove(name string, unwatchFiles bool) error { + if w.isClosed() { + return nil + } + + name = filepath.Clean(name) + info, ok := w.watches.byPath(name) + if !ok { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, name) + } + + err := w.register([]int{info.wd}, unix.EV_DELETE, 0) + if err != nil { + return err + } + + unix.Close(info.wd) + + isDir := w.watches.remove(info.wd, name) + + // Find all watched paths that are in this directory that are not external. + if unwatchFiles && isDir { + pathsToRemove := w.watches.watchesInDir(name) + for _, name := range pathsToRemove { + // Since these are internal, not much sense in propagating error to + // the user, as that will just confuse them with an error about a + // path they did not explicitly watch themselves. + w.Remove(name) + } + } + return nil +} + +func (w *kqueue) WatchList() []string { + if w.isClosed() { + return nil + } + return w.watches.listPaths(true) +} + +// Watch all events (except NOTE_EXTEND, NOTE_LINK, NOTE_REVOKE) +const noteAllEvents = unix.NOTE_DELETE | unix.NOTE_WRITE | unix.NOTE_ATTRIB | unix.NOTE_RENAME + +// addWatch adds name to the watched file set; the flags are interpreted as +// described in kevent(2). +// +// Returns the real path to the file which was added, with symlinks resolved. +func (w *kqueue) addWatch(name string, flags uint32, listDir bool) (string, error) { + if w.isClosed() { + return "", ErrClosed + } + + name = filepath.Clean(name) + + info, alreadyWatching := w.watches.byPath(name) + if !alreadyWatching { + fi, err := os.Lstat(name) + if err != nil { + return "", err + } + + // Don't watch sockets or named pipes. + if (fi.Mode()&os.ModeSocket == os.ModeSocket) || (fi.Mode()&os.ModeNamedPipe == os.ModeNamedPipe) { + return "", nil + } + + // Follow symlinks, but only for paths added with Add(), and not paths + // we're adding from internalWatch from a listdir. + if !listDir && fi.Mode()&os.ModeSymlink == os.ModeSymlink { + link, err := os.Readlink(name) + if err != nil { + return "", err + } + if !filepath.IsAbs(link) { + link = filepath.Join(filepath.Dir(name), link) + } + + _, alreadyWatching = w.watches.byPath(link) + if alreadyWatching { + // Add to watches so we don't get spurious Create events later + // on when we diff the directories. + w.watches.addLink(name, 0) + return link, nil + } + + info.linkName = name + name = link + fi, err = os.Lstat(name) + if err != nil { + return "", err + } + } + + // Retry on EINTR; open() can return EINTR in practice on macOS. + // See #354, and Go issues 11180 and 39237. + for { + info.wd, err = unix.Open(name, openMode, 0) + if err == nil { + break + } + if errors.Is(err, unix.EINTR) { + continue + } + return "", err + } + + info.isDir = fi.IsDir() + } + + err := w.register([]int{info.wd}, unix.EV_ADD|unix.EV_CLEAR|unix.EV_ENABLE, flags) + if err != nil { + unix.Close(info.wd) + return "", err + } + + if !alreadyWatching { + w.watches.add(name, info.linkName, info.wd, info.isDir) + } + + // Watch the directory if it has not been watched before, or if it was + // watched before, but perhaps only a NOTE_DELETE (watchDirectoryFiles) + if info.isDir { + watchDir := (flags&unix.NOTE_WRITE) == unix.NOTE_WRITE && + (!alreadyWatching || (info.dirFlags&unix.NOTE_WRITE) != unix.NOTE_WRITE) + if !w.watches.updateDirFlags(name, flags) { + return "", nil + } + + if watchDir { + d := name + if info.linkName != "" { + d = info.linkName + } + if err := w.watchDirectoryFiles(d); err != nil { + return "", err + } + } + } + return name, nil +} + +// readEvents reads from kqueue and converts the received kevents into +// Event values that it sends down the Events channel. +func (w *kqueue) readEvents() { + defer func() { + close(w.Events) + close(w.Errors) + _ = unix.Close(w.kq) + unix.Close(w.closepipe[0]) + }() + + eventBuffer := make([]unix.Kevent_t, 10) + for { + kevents, err := w.read(eventBuffer) + // EINTR is okay, the syscall was interrupted before timeout expired. + if err != nil && err != unix.EINTR { + if !w.sendError(fmt.Errorf("fsnotify.readEvents: %w", err)) { + return + } + } + + for _, kevent := range kevents { + var ( + wd = int(kevent.Ident) + mask = uint32(kevent.Fflags) + ) + + // Shut down the loop when the pipe is closed, but only after all + // other events have been processed. + if wd == w.closepipe[0] { + return + } + + path, ok := w.watches.byWd(wd) + if debug { + internal.Debug(path.name, &kevent) + } + + // On macOS it seems that sometimes an event with Ident=0 is + // delivered, and no other flags/information beyond that, even + // though we never saw such a file descriptor. For example in + // TestWatchSymlink/277 (usually at the end, but sometimes sooner): + // + // fmt.Printf("READ: %2d %#v\n", kevent.Ident, kevent) + // unix.Kevent_t{Ident:0x2a, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} + // unix.Kevent_t{Ident:0x0, Filter:-4, Flags:0x25, Fflags:0x2, Data:0, Udata:(*uint8)(nil)} + // + // The first is a normal event, the second with Ident 0. No error + // flag, no data, no ... nothing. + // + // I read a bit through bsd/kern_event.c from the xnu source, but I + // don't really see an obvious location where this is triggered – + // this doesn't seem intentional, but idk... + // + // Technically fd 0 is a valid descriptor, so only skip it if + // there's no path, and if we're on macOS. + if !ok && kevent.Ident == 0 && runtime.GOOS == "darwin" { + continue + } + + event := w.newEvent(path.name, path.linkName, mask) + + if event.Has(Rename) || event.Has(Remove) { + w.remove(event.Name, false) + w.watches.markSeen(event.Name, false) + } + + if path.isDir && event.Has(Write) && !event.Has(Remove) { + w.dirChange(event.Name) + } else if !w.sendEvent(event) { + return + } + + if event.Has(Remove) { + // Look for a file that may have overwritten this; for example, + // mv f1 f2 will delete f2, then create f2. + if path.isDir { + fileDir := filepath.Clean(event.Name) + _, found := w.watches.byPath(fileDir) + if found { + // TODO: this branch is never triggered in any test. + // Added in d6220df (2012). + // isDir check added in 8611c35 (2016): https://github.com/fsnotify/fsnotify/pull/111 + // + // I don't really get how this can be triggered either. + // And it wasn't triggered in the patch that added it, + // either. + // + // Original also had a comment: + // make sure the directory exists before we watch for + // changes. When we do a recursive watch and perform + // rm -rf, the parent directory might have gone + // missing, ignore the missing directory and let the + // upcoming delete event remove the watch from the + // parent directory. + err := w.dirChange(fileDir) + if !w.sendError(err) { + return + } + } + } else { + path := filepath.Clean(event.Name) + if fi, err := os.Lstat(path); err == nil { + err := w.sendCreateIfNew(path, fi) + if !w.sendError(err) { + return + } + } + } + } + } + } +} + +// newEvent returns an platform-independent Event based on kqueue Fflags. +func (w *kqueue) newEvent(name, linkName string, mask uint32) Event { + e := Event{Name: name} + if linkName != "" { + // If the user watched "/path/link" then emit events as "/path/link" + // rather than "/path/target". + e.Name = linkName + } + + if mask&unix.NOTE_DELETE == unix.NOTE_DELETE { + e.Op |= Remove + } + if mask&unix.NOTE_WRITE == unix.NOTE_WRITE { + e.Op |= Write + } + if mask&unix.NOTE_RENAME == unix.NOTE_RENAME { + e.Op |= Rename + } + if mask&unix.NOTE_ATTRIB == unix.NOTE_ATTRIB { + e.Op |= Chmod + } + // No point sending a write and delete event at the same time: if it's gone, + // then it's gone. + if e.Op.Has(Write) && e.Op.Has(Remove) { + e.Op &^= Write + } + return e +} + +// watchDirectoryFiles to mimic inotify when adding a watch on a directory +func (w *kqueue) watchDirectoryFiles(dirPath string) error { + files, err := os.ReadDir(dirPath) + if err != nil { + return err + } + + for _, f := range files { + path := filepath.Join(dirPath, f.Name()) + + fi, err := f.Info() + if err != nil { + return fmt.Errorf("%q: %w", path, err) + } + + cleanPath, err := w.internalWatch(path, fi) + if err != nil { + // No permission to read the file; that's not a problem: just skip. + // But do add it to w.fileExists to prevent it from being picked up + // as a "new" file later (it still shows up in the directory + // listing). + switch { + case errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM): + cleanPath = filepath.Clean(path) + default: + return fmt.Errorf("%q: %w", path, err) + } + } + + w.watches.markSeen(cleanPath, true) + } + + return nil +} + +// Search the directory for new files and send an event for them. +// +// This functionality is to have the BSD watcher match the inotify, which sends +// a create event for files created in a watched directory. +func (w *kqueue) dirChange(dir string) error { + files, err := os.ReadDir(dir) + if err != nil { + // Directory no longer exists: we can ignore this safely. kqueue will + // still give us the correct events. + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("fsnotify.dirChange %q: %w", dir, err) + } + + for _, f := range files { + fi, err := f.Info() + if err != nil { + if errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("fsnotify.dirChange: %w", err) + } + + err = w.sendCreateIfNew(filepath.Join(dir, fi.Name()), fi) + if err != nil { + // Don't need to send an error if this file isn't readable. + if errors.Is(err, unix.EACCES) || errors.Is(err, unix.EPERM) || errors.Is(err, os.ErrNotExist) { + return nil + } + return fmt.Errorf("fsnotify.dirChange: %w", err) + } + } + return nil +} + +// Send a create event if the file isn't already being tracked, and start +// watching this file. +func (w *kqueue) sendCreateIfNew(path string, fi os.FileInfo) error { + if !w.watches.seenBefore(path) { + if !w.sendEvent(Event{Name: path, Op: Create}) { + return nil + } + } + + // Like watchDirectoryFiles, but without doing another ReadDir. + path, err := w.internalWatch(path, fi) + if err != nil { + return err + } + w.watches.markSeen(path, true) + return nil +} + +func (w *kqueue) internalWatch(name string, fi os.FileInfo) (string, error) { + if fi.IsDir() { + // mimic Linux providing delete events for subdirectories, but preserve + // the flags used if currently watching subdirectory + info, _ := w.watches.byPath(name) + return w.addWatch(name, info.dirFlags|unix.NOTE_DELETE|unix.NOTE_RENAME, true) + } + + // Watch file to mimic Linux inotify. + return w.addWatch(name, noteAllEvents, true) +} + +// Register events with the queue. +func (w *kqueue) register(fds []int, flags int, fflags uint32) error { + changes := make([]unix.Kevent_t, len(fds)) + for i, fd := range fds { + // SetKevent converts int to the platform-specific types. + unix.SetKevent(&changes[i], fd, unix.EVFILT_VNODE, flags) + changes[i].Fflags = fflags + } + + // Register the events. + success, err := unix.Kevent(w.kq, changes, nil, nil) + if success == -1 { + return err + } + return nil +} + +// read retrieves pending events, or waits until an event occurs. +func (w *kqueue) read(events []unix.Kevent_t) ([]unix.Kevent_t, error) { + n, err := unix.Kevent(w.kq, nil, events, nil) + if err != nil { + return nil, err + } + return events[0:n], nil +} + +func (w *kqueue) xSupports(op Op) bool { + //if runtime.GOOS == "freebsd" { + // return true // Supports everything. + //} + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/backend_other.go b/vendor/github.com/fsnotify/fsnotify/backend_other.go new file mode 100644 index 00000000..b8c0ad72 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_other.go @@ -0,0 +1,22 @@ +//go:build appengine || (!darwin && !dragonfly && !freebsd && !openbsd && !linux && !netbsd && !solaris && !windows) + +package fsnotify + +import "errors" + +type other struct { + Events chan Event + Errors chan error +} + +var defaultBufferSize = 0 + +func newBackend(ev chan Event, errs chan error) (backend, error) { + return nil, errors.New("fsnotify not supported on the current platform") +} +func (w *other) Close() error { return nil } +func (w *other) WatchList() []string { return nil } +func (w *other) Add(name string) error { return nil } +func (w *other) AddWith(name string, opts ...addOpt) error { return nil } +func (w *other) Remove(name string) error { return nil } +func (w *other) xSupports(op Op) bool { return false } diff --git a/vendor/github.com/fsnotify/fsnotify/backend_windows.go b/vendor/github.com/fsnotify/fsnotify/backend_windows.go new file mode 100644 index 00000000..3433642d --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/backend_windows.go @@ -0,0 +1,680 @@ +//go:build windows + +// Windows backend based on ReadDirectoryChangesW() +// +// https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-readdirectorychangesw + +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "sync" + "time" + "unsafe" + + "github.com/fsnotify/fsnotify/internal" + "golang.org/x/sys/windows" +) + +type readDirChangesW struct { + Events chan Event + Errors chan error + + port windows.Handle // Handle to completion port + input chan *input // Inputs to the reader are sent on this channel + done chan chan<- error + + mu sync.Mutex // Protects access to watches, closed + watches watchMap // Map of watches (key: i-number) + closed bool // Set to true when Close() is first called +} + +var defaultBufferSize = 50 + +func newBackend(ev chan Event, errs chan error) (backend, error) { + port, err := windows.CreateIoCompletionPort(windows.InvalidHandle, 0, 0, 0) + if err != nil { + return nil, os.NewSyscallError("CreateIoCompletionPort", err) + } + w := &readDirChangesW{ + Events: ev, + Errors: errs, + port: port, + watches: make(watchMap), + input: make(chan *input, 1), + done: make(chan chan<- error, 1), + } + go w.readEvents() + return w, nil +} + +func (w *readDirChangesW) isClosed() bool { + w.mu.Lock() + defer w.mu.Unlock() + return w.closed +} + +func (w *readDirChangesW) sendEvent(name, renamedFrom string, mask uint64) bool { + if mask == 0 { + return false + } + + event := w.newEvent(name, uint32(mask)) + event.renamedFrom = renamedFrom + select { + case ch := <-w.done: + w.done <- ch + case w.Events <- event: + } + return true +} + +// Returns true if the error was sent, or false if watcher is closed. +func (w *readDirChangesW) sendError(err error) bool { + if err == nil { + return true + } + select { + case <-w.done: + return false + case w.Errors <- err: + return true + } +} + +func (w *readDirChangesW) Close() error { + if w.isClosed() { + return nil + } + + w.mu.Lock() + w.closed = true + w.mu.Unlock() + + // Send "done" message to the reader goroutine + ch := make(chan error) + w.done <- ch + if err := w.wakeupReader(); err != nil { + return err + } + return <-ch +} + +func (w *readDirChangesW) Add(name string) error { return w.AddWith(name) } + +func (w *readDirChangesW) AddWith(name string, opts ...addOpt) error { + if w.isClosed() { + return ErrClosed + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s AddWith(%q)\n", + time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) + } + + with := getOptions(opts...) + if !w.xSupports(with.op) { + return fmt.Errorf("%w: %s", xErrUnsupported, with.op) + } + if with.bufsize < 4096 { + return fmt.Errorf("fsnotify.WithBufferSize: buffer size cannot be smaller than 4096 bytes") + } + + in := &input{ + op: opAddWatch, + path: filepath.Clean(name), + flags: sysFSALLEVENTS, + reply: make(chan error), + bufsize: with.bufsize, + } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply +} + +func (w *readDirChangesW) Remove(name string) error { + if w.isClosed() { + return nil + } + if debug { + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s Remove(%q)\n", + time.Now().Format("15:04:05.000000000"), filepath.ToSlash(name)) + } + + in := &input{ + op: opRemoveWatch, + path: filepath.Clean(name), + reply: make(chan error), + } + w.input <- in + if err := w.wakeupReader(); err != nil { + return err + } + return <-in.reply +} + +func (w *readDirChangesW) WatchList() []string { + if w.isClosed() { + return nil + } + + w.mu.Lock() + defer w.mu.Unlock() + + entries := make([]string, 0, len(w.watches)) + for _, entry := range w.watches { + for _, watchEntry := range entry { + for name := range watchEntry.names { + entries = append(entries, filepath.Join(watchEntry.path, name)) + } + // the directory itself is being watched + if watchEntry.mask != 0 { + entries = append(entries, watchEntry.path) + } + } + } + + return entries +} + +// These options are from the old golang.org/x/exp/winfsnotify, where you could +// add various options to the watch. This has long since been removed. +// +// The "sys" in the name is misleading as they're not part of any "system". +// +// This should all be removed at some point, and just use windows.FILE_NOTIFY_* +const ( + sysFSALLEVENTS = 0xfff + sysFSCREATE = 0x100 + sysFSDELETE = 0x200 + sysFSDELETESELF = 0x400 + sysFSMODIFY = 0x2 + sysFSMOVE = 0xc0 + sysFSMOVEDFROM = 0x40 + sysFSMOVEDTO = 0x80 + sysFSMOVESELF = 0x800 + sysFSIGNORED = 0x8000 +) + +func (w *readDirChangesW) newEvent(name string, mask uint32) Event { + e := Event{Name: name} + if mask&sysFSCREATE == sysFSCREATE || mask&sysFSMOVEDTO == sysFSMOVEDTO { + e.Op |= Create + } + if mask&sysFSDELETE == sysFSDELETE || mask&sysFSDELETESELF == sysFSDELETESELF { + e.Op |= Remove + } + if mask&sysFSMODIFY == sysFSMODIFY { + e.Op |= Write + } + if mask&sysFSMOVE == sysFSMOVE || mask&sysFSMOVESELF == sysFSMOVESELF || mask&sysFSMOVEDFROM == sysFSMOVEDFROM { + e.Op |= Rename + } + return e +} + +const ( + opAddWatch = iota + opRemoveWatch +) + +const ( + provisional uint64 = 1 << (32 + iota) +) + +type input struct { + op int + path string + flags uint32 + bufsize int + reply chan error +} + +type inode struct { + handle windows.Handle + volume uint32 + index uint64 +} + +type watch struct { + ov windows.Overlapped + ino *inode // i-number + recurse bool // Recursive watch? + path string // Directory path + mask uint64 // Directory itself is being watched with these notify flags + names map[string]uint64 // Map of names being watched and their notify flags + rename string // Remembers the old name while renaming a file + buf []byte // buffer, allocated later +} + +type ( + indexMap map[uint64]*watch + watchMap map[uint32]indexMap +) + +func (w *readDirChangesW) wakeupReader() error { + err := windows.PostQueuedCompletionStatus(w.port, 0, 0, nil) + if err != nil { + return os.NewSyscallError("PostQueuedCompletionStatus", err) + } + return nil +} + +func (w *readDirChangesW) getDir(pathname string) (dir string, err error) { + attr, err := windows.GetFileAttributes(windows.StringToUTF16Ptr(pathname)) + if err != nil { + return "", os.NewSyscallError("GetFileAttributes", err) + } + if attr&windows.FILE_ATTRIBUTE_DIRECTORY != 0 { + dir = pathname + } else { + dir, _ = filepath.Split(pathname) + dir = filepath.Clean(dir) + } + return +} + +func (w *readDirChangesW) getIno(path string) (ino *inode, err error) { + h, err := windows.CreateFile(windows.StringToUTF16Ptr(path), + windows.FILE_LIST_DIRECTORY, + windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, + nil, windows.OPEN_EXISTING, + windows.FILE_FLAG_BACKUP_SEMANTICS|windows.FILE_FLAG_OVERLAPPED, 0) + if err != nil { + return nil, os.NewSyscallError("CreateFile", err) + } + + var fi windows.ByHandleFileInformation + err = windows.GetFileInformationByHandle(h, &fi) + if err != nil { + windows.CloseHandle(h) + return nil, os.NewSyscallError("GetFileInformationByHandle", err) + } + ino = &inode{ + handle: h, + volume: fi.VolumeSerialNumber, + index: uint64(fi.FileIndexHigh)<<32 | uint64(fi.FileIndexLow), + } + return ino, nil +} + +// Must run within the I/O thread. +func (m watchMap) get(ino *inode) *watch { + if i := m[ino.volume]; i != nil { + return i[ino.index] + } + return nil +} + +// Must run within the I/O thread. +func (m watchMap) set(ino *inode, watch *watch) { + i := m[ino.volume] + if i == nil { + i = make(indexMap) + m[ino.volume] = i + } + i[ino.index] = watch +} + +// Must run within the I/O thread. +func (w *readDirChangesW) addWatch(pathname string, flags uint64, bufsize int) error { + pathname, recurse := recursivePath(pathname) + + dir, err := w.getDir(pathname) + if err != nil { + return err + } + + ino, err := w.getIno(dir) + if err != nil { + return err + } + w.mu.Lock() + watchEntry := w.watches.get(ino) + w.mu.Unlock() + if watchEntry == nil { + _, err := windows.CreateIoCompletionPort(ino.handle, w.port, 0, 0) + if err != nil { + windows.CloseHandle(ino.handle) + return os.NewSyscallError("CreateIoCompletionPort", err) + } + watchEntry = &watch{ + ino: ino, + path: dir, + names: make(map[string]uint64), + recurse: recurse, + buf: make([]byte, bufsize), + } + w.mu.Lock() + w.watches.set(ino, watchEntry) + w.mu.Unlock() + flags |= provisional + } else { + windows.CloseHandle(ino.handle) + } + if pathname == dir { + watchEntry.mask |= flags + } else { + watchEntry.names[filepath.Base(pathname)] |= flags + } + + err = w.startRead(watchEntry) + if err != nil { + return err + } + + if pathname == dir { + watchEntry.mask &= ^provisional + } else { + watchEntry.names[filepath.Base(pathname)] &= ^provisional + } + return nil +} + +// Must run within the I/O thread. +func (w *readDirChangesW) remWatch(pathname string) error { + pathname, recurse := recursivePath(pathname) + + dir, err := w.getDir(pathname) + if err != nil { + return err + } + ino, err := w.getIno(dir) + if err != nil { + return err + } + + w.mu.Lock() + watch := w.watches.get(ino) + w.mu.Unlock() + + if recurse && !watch.recurse { + return fmt.Errorf("can't use \\... with non-recursive watch %q", pathname) + } + + err = windows.CloseHandle(ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + if watch == nil { + return fmt.Errorf("%w: %s", ErrNonExistentWatch, pathname) + } + if pathname == dir { + w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) + watch.mask = 0 + } else { + name := filepath.Base(pathname) + w.sendEvent(filepath.Join(watch.path, name), "", watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } + + return w.startRead(watch) +} + +// Must run within the I/O thread. +func (w *readDirChangesW) deleteWatch(watch *watch) { + for name, mask := range watch.names { + if mask&provisional == 0 { + w.sendEvent(filepath.Join(watch.path, name), "", mask&sysFSIGNORED) + } + delete(watch.names, name) + } + if watch.mask != 0 { + if watch.mask&provisional == 0 { + w.sendEvent(watch.path, "", watch.mask&sysFSIGNORED) + } + watch.mask = 0 + } +} + +// Must run within the I/O thread. +func (w *readDirChangesW) startRead(watch *watch) error { + err := windows.CancelIo(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CancelIo", err)) + w.deleteWatch(watch) + } + mask := w.toWindowsFlags(watch.mask) + for _, m := range watch.names { + mask |= w.toWindowsFlags(m) + } + if mask == 0 { + err := windows.CloseHandle(watch.ino.handle) + if err != nil { + w.sendError(os.NewSyscallError("CloseHandle", err)) + } + w.mu.Lock() + delete(w.watches[watch.ino.volume], watch.ino.index) + w.mu.Unlock() + return nil + } + + // We need to pass the array, rather than the slice. + hdr := (*reflect.SliceHeader)(unsafe.Pointer(&watch.buf)) + rdErr := windows.ReadDirectoryChanges(watch.ino.handle, + (*byte)(unsafe.Pointer(hdr.Data)), uint32(hdr.Len), + watch.recurse, mask, nil, &watch.ov, 0) + if rdErr != nil { + err := os.NewSyscallError("ReadDirectoryChanges", rdErr) + if rdErr == windows.ERROR_ACCESS_DENIED && watch.mask&provisional == 0 { + // Watched directory was probably removed + w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) + err = nil + } + w.deleteWatch(watch) + w.startRead(watch) + return err + } + return nil +} + +// readEvents reads from the I/O completion port, converts the +// received events into Event objects and sends them via the Events channel. +// Entry point to the I/O thread. +func (w *readDirChangesW) readEvents() { + var ( + n uint32 + key uintptr + ov *windows.Overlapped + ) + runtime.LockOSThread() + + for { + // This error is handled after the watch == nil check below. + qErr := windows.GetQueuedCompletionStatus(w.port, &n, &key, &ov, windows.INFINITE) + + watch := (*watch)(unsafe.Pointer(ov)) + if watch == nil { + select { + case ch := <-w.done: + w.mu.Lock() + var indexes []indexMap + for _, index := range w.watches { + indexes = append(indexes, index) + } + w.mu.Unlock() + for _, index := range indexes { + for _, watch := range index { + w.deleteWatch(watch) + w.startRead(watch) + } + } + + err := windows.CloseHandle(w.port) + if err != nil { + err = os.NewSyscallError("CloseHandle", err) + } + close(w.Events) + close(w.Errors) + ch <- err + return + case in := <-w.input: + switch in.op { + case opAddWatch: + in.reply <- w.addWatch(in.path, uint64(in.flags), in.bufsize) + case opRemoveWatch: + in.reply <- w.remWatch(in.path) + } + default: + } + continue + } + + switch qErr { + case nil: + // No error + case windows.ERROR_MORE_DATA: + if watch == nil { + w.sendError(errors.New("ERROR_MORE_DATA has unexpectedly null lpOverlapped buffer")) + } else { + // The i/o succeeded but the buffer is full. + // In theory we should be building up a full packet. + // In practice we can get away with just carrying on. + n = uint32(unsafe.Sizeof(watch.buf)) + } + case windows.ERROR_ACCESS_DENIED: + // Watched directory was probably removed + w.sendEvent(watch.path, "", watch.mask&sysFSDELETESELF) + w.deleteWatch(watch) + w.startRead(watch) + continue + case windows.ERROR_OPERATION_ABORTED: + // CancelIo was called on this handle + continue + default: + w.sendError(os.NewSyscallError("GetQueuedCompletionPort", qErr)) + continue + } + + var offset uint32 + for { + if n == 0 { + w.sendError(ErrEventOverflow) + break + } + + // Point "raw" to the event in the buffer + raw := (*windows.FileNotifyInformation)(unsafe.Pointer(&watch.buf[offset])) + + // Create a buf that is the size of the path name + size := int(raw.FileNameLength / 2) + var buf []uint16 + // TODO: Use unsafe.Slice in Go 1.17; https://stackoverflow.com/questions/51187973 + sh := (*reflect.SliceHeader)(unsafe.Pointer(&buf)) + sh.Data = uintptr(unsafe.Pointer(&raw.FileName)) + sh.Len = size + sh.Cap = size + name := windows.UTF16ToString(buf) + fullname := filepath.Join(watch.path, name) + + if debug { + internal.Debug(fullname, raw.Action) + } + + var mask uint64 + switch raw.Action { + case windows.FILE_ACTION_REMOVED: + mask = sysFSDELETESELF + case windows.FILE_ACTION_MODIFIED: + mask = sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + watch.rename = name + case windows.FILE_ACTION_RENAMED_NEW_NAME: + // Update saved path of all sub-watches. + old := filepath.Join(watch.path, watch.rename) + w.mu.Lock() + for _, watchMap := range w.watches { + for _, ww := range watchMap { + if strings.HasPrefix(ww.path, old) { + ww.path = filepath.Join(fullname, strings.TrimPrefix(ww.path, old)) + } + } + } + w.mu.Unlock() + + if watch.names[watch.rename] != 0 { + watch.names[name] |= watch.names[watch.rename] + delete(watch.names, watch.rename) + mask = sysFSMOVESELF + } + } + + if raw.Action != windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(fullname, "", watch.names[name]&mask) + } + if raw.Action == windows.FILE_ACTION_REMOVED { + w.sendEvent(fullname, "", watch.names[name]&sysFSIGNORED) + delete(watch.names, name) + } + + if watch.rename != "" && raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(fullname, filepath.Join(watch.path, watch.rename), watch.mask&w.toFSnotifyFlags(raw.Action)) + } else { + w.sendEvent(fullname, "", watch.mask&w.toFSnotifyFlags(raw.Action)) + } + + if raw.Action == windows.FILE_ACTION_RENAMED_NEW_NAME { + w.sendEvent(filepath.Join(watch.path, watch.rename), "", watch.names[name]&mask) + } + + // Move to the next event in the buffer + if raw.NextEntryOffset == 0 { + break + } + offset += raw.NextEntryOffset + + // Error! + if offset >= n { + //lint:ignore ST1005 Windows should be capitalized + w.sendError(errors.New("Windows system assumed buffer larger than it is, events have likely been missed")) + break + } + } + + if err := w.startRead(watch); err != nil { + w.sendError(err) + } + } +} + +func (w *readDirChangesW) toWindowsFlags(mask uint64) uint32 { + var m uint32 + if mask&sysFSMODIFY != 0 { + m |= windows.FILE_NOTIFY_CHANGE_LAST_WRITE + } + if mask&(sysFSMOVE|sysFSCREATE|sysFSDELETE) != 0 { + m |= windows.FILE_NOTIFY_CHANGE_FILE_NAME | windows.FILE_NOTIFY_CHANGE_DIR_NAME + } + return m +} + +func (w *readDirChangesW) toFSnotifyFlags(action uint32) uint64 { + switch action { + case windows.FILE_ACTION_ADDED: + return sysFSCREATE + case windows.FILE_ACTION_REMOVED: + return sysFSDELETE + case windows.FILE_ACTION_MODIFIED: + return sysFSMODIFY + case windows.FILE_ACTION_RENAMED_OLD_NAME: + return sysFSMOVEDFROM + case windows.FILE_ACTION_RENAMED_NEW_NAME: + return sysFSMOVEDTO + } + return 0 +} + +func (w *readDirChangesW) xSupports(op Op) bool { + if op.Has(xUnportableOpen) || op.Has(xUnportableRead) || + op.Has(xUnportableCloseWrite) || op.Has(xUnportableCloseRead) { + return false + } + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/fsnotify.go b/vendor/github.com/fsnotify/fsnotify/fsnotify.go new file mode 100644 index 00000000..f64be4bf --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/fsnotify.go @@ -0,0 +1,496 @@ +// Package fsnotify provides a cross-platform interface for file system +// notifications. +// +// Currently supported systems: +// +// - Linux via inotify +// - BSD, macOS via kqueue +// - Windows via ReadDirectoryChangesW +// - illumos via FEN +// +// # FSNOTIFY_DEBUG +// +// Set the FSNOTIFY_DEBUG environment variable to "1" to print debug messages to +// stderr. This can be useful to track down some problems, especially in cases +// where fsnotify is used as an indirect dependency. +// +// Every event will be printed as soon as there's something useful to print, +// with as little processing from fsnotify. +// +// Example output: +// +// FSNOTIFY_DEBUG: 11:34:23.633087586 256:IN_CREATE → "/tmp/file-1" +// FSNOTIFY_DEBUG: 11:34:23.633202319 4:IN_ATTRIB → "/tmp/file-1" +// FSNOTIFY_DEBUG: 11:34:28.989728764 512:IN_DELETE → "/tmp/file-1" +package fsnotify + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" +) + +// Watcher watches a set of paths, delivering events on a channel. +// +// A watcher should not be copied (e.g. pass it by pointer, rather than by +// value). +// +// # Linux notes +// +// When a file is removed a Remove event won't be emitted until all file +// descriptors are closed, and deletes will always emit a Chmod. For example: +// +// fp := os.Open("file") +// os.Remove("file") // Triggers Chmod +// fp.Close() // Triggers Remove +// +// This is the event that inotify sends, so not much can be changed about this. +// +// The fs.inotify.max_user_watches sysctl variable specifies the upper limit +// for the number of watches per user, and fs.inotify.max_user_instances +// specifies the maximum number of inotify instances per user. Every Watcher you +// create is an "instance", and every path you add is a "watch". +// +// These are also exposed in /proc as /proc/sys/fs/inotify/max_user_watches and +// /proc/sys/fs/inotify/max_user_instances +// +// To increase them you can use sysctl or write the value to the /proc file: +// +// # Default values on Linux 5.18 +// sysctl fs.inotify.max_user_watches=124983 +// sysctl fs.inotify.max_user_instances=128 +// +// To make the changes persist on reboot edit /etc/sysctl.conf or +// /usr/lib/sysctl.d/50-default.conf (details differ per Linux distro; check +// your distro's documentation): +// +// fs.inotify.max_user_watches=124983 +// fs.inotify.max_user_instances=128 +// +// Reaching the limit will result in a "no space left on device" or "too many open +// files" error. +// +// # kqueue notes (macOS, BSD) +// +// kqueue requires opening a file descriptor for every file that's being watched; +// so if you're watching a directory with five files then that's six file +// descriptors. You will run in to your system's "max open files" limit faster on +// these platforms. +// +// The sysctl variables kern.maxfiles and kern.maxfilesperproc can be used to +// control the maximum number of open files, as well as /etc/login.conf on BSD +// systems. +// +// # Windows notes +// +// Paths can be added as "C:\\path\\to\\dir", but forward slashes +// ("C:/path/to/dir") will also work. +// +// When a watched directory is removed it will always send an event for the +// directory itself, but may not send events for all files in that directory. +// Sometimes it will send events for all files, sometimes it will send no +// events, and often only for some files. +// +// The default ReadDirectoryChangesW() buffer size is 64K, which is the largest +// value that is guaranteed to work with SMB filesystems. If you have many +// events in quick succession this may not be enough, and you will have to use +// [WithBufferSize] to increase the value. +type Watcher struct { + b backend + + // Events sends the filesystem change events. + // + // fsnotify can send the following events; a "path" here can refer to a + // file, directory, symbolic link, or special file like a FIFO. + // + // fsnotify.Create A new path was created; this may be followed by one + // or more Write events if data also gets written to a + // file. + // + // fsnotify.Remove A path was removed. + // + // fsnotify.Rename A path was renamed. A rename is always sent with the + // old path as Event.Name, and a Create event will be + // sent with the new name. Renames are only sent for + // paths that are currently watched; e.g. moving an + // unmonitored file into a monitored directory will + // show up as just a Create. Similarly, renaming a file + // to outside a monitored directory will show up as + // only a Rename. + // + // fsnotify.Write A file or named pipe was written to. A Truncate will + // also trigger a Write. A single "write action" + // initiated by the user may show up as one or multiple + // writes, depending on when the system syncs things to + // disk. For example when compiling a large Go program + // you may get hundreds of Write events, and you may + // want to wait until you've stopped receiving them + // (see the dedup example in cmd/fsnotify). + // + // Some systems may send Write event for directories + // when the directory content changes. + // + // fsnotify.Chmod Attributes were changed. On Linux this is also sent + // when a file is removed (or more accurately, when a + // link to an inode is removed). On kqueue it's sent + // when a file is truncated. On Windows it's never + // sent. + Events chan Event + + // Errors sends any errors. + Errors chan error +} + +// Event represents a file system notification. +type Event struct { + // Path to the file or directory. + // + // Paths are relative to the input; for example with Add("dir") the Name + // will be set to "dir/file" if you create that file, but if you use + // Add("/path/to/dir") it will be "/path/to/dir/file". + Name string + + // File operation that triggered the event. + // + // This is a bitmask and some systems may send multiple operations at once. + // Use the Event.Has() method instead of comparing with ==. + Op Op + + // Create events will have this set to the old path if it's a rename. This + // only works when both the source and destination are watched. It's not + // reliable when watching individual files, only directories. + // + // For example "mv /tmp/file /tmp/rename" will emit: + // + // Event{Op: Rename, Name: "/tmp/file"} + // Event{Op: Create, Name: "/tmp/rename", RenamedFrom: "/tmp/file"} + renamedFrom string +} + +// Op describes a set of file operations. +type Op uint32 + +// The operations fsnotify can trigger; see the documentation on [Watcher] for a +// full description, and check them with [Event.Has]. +const ( + // A new pathname was created. + Create Op = 1 << iota + + // The pathname was written to; this does *not* mean the write has finished, + // and a write can be followed by more writes. + Write + + // The path was removed; any watches on it will be removed. Some "remove" + // operations may trigger a Rename if the file is actually moved (for + // example "remove to trash" is often a rename). + Remove + + // The path was renamed to something else; any watches on it will be + // removed. + Rename + + // File attributes were changed. + // + // It's generally not recommended to take action on this event, as it may + // get triggered very frequently by some software. For example, Spotlight + // indexing on macOS, anti-virus software, backup software, etc. + Chmod + + // File descriptor was opened. + // + // Only works on Linux and FreeBSD. + xUnportableOpen + + // File was read from. + // + // Only works on Linux and FreeBSD. + xUnportableRead + + // File opened for writing was closed. + // + // Only works on Linux and FreeBSD. + // + // The advantage of using this over Write is that it's more reliable than + // waiting for Write events to stop. It's also faster (if you're not + // listening to Write events): copying a file of a few GB can easily + // generate tens of thousands of Write events in a short span of time. + xUnportableCloseWrite + + // File opened for reading was closed. + // + // Only works on Linux and FreeBSD. + xUnportableCloseRead +) + +var ( + // ErrNonExistentWatch is used when Remove() is called on a path that's not + // added. + ErrNonExistentWatch = errors.New("fsnotify: can't remove non-existent watch") + + // ErrClosed is used when trying to operate on a closed Watcher. + ErrClosed = errors.New("fsnotify: watcher already closed") + + // ErrEventOverflow is reported from the Errors channel when there are too + // many events: + // + // - inotify: inotify returns IN_Q_OVERFLOW – because there are too + // many queued events (the fs.inotify.max_queued_events + // sysctl can be used to increase this). + // - windows: The buffer size is too small; WithBufferSize() can be used to increase it. + // - kqueue, fen: Not used. + ErrEventOverflow = errors.New("fsnotify: queue or buffer overflow") + + // ErrUnsupported is returned by AddWith() when WithOps() specified an + // Unportable event that's not supported on this platform. + //lint:ignore ST1012 not relevant + xErrUnsupported = errors.New("fsnotify: not supported with this backend") +) + +// NewWatcher creates a new Watcher. +func NewWatcher() (*Watcher, error) { + ev, errs := make(chan Event, defaultBufferSize), make(chan error) + b, err := newBackend(ev, errs) + if err != nil { + return nil, err + } + return &Watcher{b: b, Events: ev, Errors: errs}, nil +} + +// NewBufferedWatcher creates a new Watcher with a buffered Watcher.Events +// channel. +// +// The main use case for this is situations with a very large number of events +// where the kernel buffer size can't be increased (e.g. due to lack of +// permissions). An unbuffered Watcher will perform better for almost all use +// cases, and whenever possible you will be better off increasing the kernel +// buffers instead of adding a large userspace buffer. +func NewBufferedWatcher(sz uint) (*Watcher, error) { + ev, errs := make(chan Event, sz), make(chan error) + b, err := newBackend(ev, errs) + if err != nil { + return nil, err + } + return &Watcher{b: b, Events: ev, Errors: errs}, nil +} + +// Add starts monitoring the path for changes. +// +// A path can only be watched once; watching it more than once is a no-op and will +// not return an error. Paths that do not yet exist on the filesystem cannot be +// watched. +// +// A watch will be automatically removed if the watched path is deleted or +// renamed. The exception is the Windows backend, which doesn't remove the +// watcher on renames. +// +// Notifications on network filesystems (NFS, SMB, FUSE, etc.) or special +// filesystems (/proc, /sys, etc.) generally don't work. +// +// Returns [ErrClosed] if [Watcher.Close] was called. +// +// See [Watcher.AddWith] for a version that allows adding options. +// +// # Watching directories +// +// All files in a directory are monitored, including new files that are created +// after the watcher is started. Subdirectories are not watched (i.e. it's +// non-recursive). +// +// # Watching files +// +// Watching individual files (rather than directories) is generally not +// recommended as many programs (especially editors) update files atomically: it +// will write to a temporary file which is then moved to destination, +// overwriting the original (or some variant thereof). The watcher on the +// original file is now lost, as that no longer exists. +// +// The upshot of this is that a power failure or crash won't leave a +// half-written file. +// +// Watch the parent directory and use Event.Name to filter out files you're not +// interested in. There is an example of this in cmd/fsnotify/file.go. +func (w *Watcher) Add(path string) error { return w.b.Add(path) } + +// AddWith is like [Watcher.Add], but allows adding options. When using Add() +// the defaults described below are used. +// +// Possible options are: +// +// - [WithBufferSize] sets the buffer size for the Windows backend; no-op on +// other platforms. The default is 64K (65536 bytes). +func (w *Watcher) AddWith(path string, opts ...addOpt) error { return w.b.AddWith(path, opts...) } + +// Remove stops monitoring the path for changes. +// +// Directories are always removed non-recursively. For example, if you added +// /tmp/dir and /tmp/dir/subdir then you will need to remove both. +// +// Removing a path that has not yet been added returns [ErrNonExistentWatch]. +// +// Returns nil if [Watcher.Close] was called. +func (w *Watcher) Remove(path string) error { return w.b.Remove(path) } + +// Close removes all watches and closes the Events channel. +func (w *Watcher) Close() error { return w.b.Close() } + +// WatchList returns all paths explicitly added with [Watcher.Add] (and are not +// yet removed). +// +// The order is undefined, and may differ per call. Returns nil if +// [Watcher.Close] was called. +func (w *Watcher) WatchList() []string { return w.b.WatchList() } + +// Supports reports if all the listed operations are supported by this platform. +// +// Create, Write, Remove, Rename, and Chmod are always supported. It can only +// return false for an Op starting with Unportable. +func (w *Watcher) xSupports(op Op) bool { return w.b.xSupports(op) } + +func (o Op) String() string { + var b strings.Builder + if o.Has(Create) { + b.WriteString("|CREATE") + } + if o.Has(Remove) { + b.WriteString("|REMOVE") + } + if o.Has(Write) { + b.WriteString("|WRITE") + } + if o.Has(xUnportableOpen) { + b.WriteString("|OPEN") + } + if o.Has(xUnportableRead) { + b.WriteString("|READ") + } + if o.Has(xUnportableCloseWrite) { + b.WriteString("|CLOSE_WRITE") + } + if o.Has(xUnportableCloseRead) { + b.WriteString("|CLOSE_READ") + } + if o.Has(Rename) { + b.WriteString("|RENAME") + } + if o.Has(Chmod) { + b.WriteString("|CHMOD") + } + if b.Len() == 0 { + return "[no events]" + } + return b.String()[1:] +} + +// Has reports if this operation has the given operation. +func (o Op) Has(h Op) bool { return o&h != 0 } + +// Has reports if this event has the given operation. +func (e Event) Has(op Op) bool { return e.Op.Has(op) } + +// String returns a string representation of the event with their path. +func (e Event) String() string { + if e.renamedFrom != "" { + return fmt.Sprintf("%-13s %q ← %q", e.Op.String(), e.Name, e.renamedFrom) + } + return fmt.Sprintf("%-13s %q", e.Op.String(), e.Name) +} + +type ( + backend interface { + Add(string) error + AddWith(string, ...addOpt) error + Remove(string) error + WatchList() []string + Close() error + xSupports(Op) bool + } + addOpt func(opt *withOpts) + withOpts struct { + bufsize int + op Op + noFollow bool + sendCreate bool + } +) + +var debug = func() bool { + // Check for exactly "1" (rather than mere existence) so we can add + // options/flags in the future. I don't know if we ever want that, but it's + // nice to leave the option open. + return os.Getenv("FSNOTIFY_DEBUG") == "1" +}() + +var defaultOpts = withOpts{ + bufsize: 65536, // 64K + op: Create | Write | Remove | Rename | Chmod, +} + +func getOptions(opts ...addOpt) withOpts { + with := defaultOpts + for _, o := range opts { + if o != nil { + o(&with) + } + } + return with +} + +// WithBufferSize sets the [ReadDirectoryChangesW] buffer size. +// +// This only has effect on Windows systems, and is a no-op for other backends. +// +// The default value is 64K (65536 bytes) which is the highest value that works +// on all filesystems and should be enough for most applications, but if you +// have a large burst of events it may not be enough. You can increase it if +// you're hitting "queue or buffer overflow" errors ([ErrEventOverflow]). +// +// [ReadDirectoryChangesW]: https://learn.microsoft.com/en-gb/windows/win32/api/winbase/nf-winbase-readdirectorychangesw +func WithBufferSize(bytes int) addOpt { + return func(opt *withOpts) { opt.bufsize = bytes } +} + +// WithOps sets which operations to listen for. The default is [Create], +// [Write], [Remove], [Rename], and [Chmod]. +// +// Excluding operations you're not interested in can save quite a bit of CPU +// time; in some use cases there may be hundreds of thousands of useless Write +// or Chmod operations per second. +// +// This can also be used to add unportable operations not supported by all +// platforms; unportable operations all start with "Unportable": +// [UnportableOpen], [UnportableRead], [UnportableCloseWrite], and +// [UnportableCloseRead]. +// +// AddWith returns an error when using an unportable operation that's not +// supported. Use [Watcher.Support] to check for support. +func withOps(op Op) addOpt { + return func(opt *withOpts) { opt.op = op } +} + +// WithNoFollow disables following symlinks, so the symlinks themselves are +// watched. +func withNoFollow() addOpt { + return func(opt *withOpts) { opt.noFollow = true } +} + +// "Internal" option for recursive watches on inotify. +func withCreate() addOpt { + return func(opt *withOpts) { opt.sendCreate = true } +} + +var enableRecurse = false + +// Check if this path is recursive (ends with "/..." or "\..."), and return the +// path with the /... stripped. +func recursivePath(path string) (string, bool) { + path = filepath.Clean(path) + if !enableRecurse { // Only enabled in tests for now. + return path, false + } + if filepath.Base(path) == "..." { + return filepath.Dir(path), true + } + return path, false +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/darwin.go new file mode 100644 index 00000000..0b01bc18 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/darwin.go @@ -0,0 +1,39 @@ +//go:build darwin + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + ErrSyscallEACCES = syscall.EACCES + ErrUnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +func SetRlimit() { + // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = l.Cur + + if n, err := syscall.SysctlUint32("kern.maxfiles"); err == nil && uint64(n) < maxfiles { + maxfiles = uint64(n) + } + + if n, err := syscall.SysctlUint32("kern.maxfilesperproc"); err == nil && uint64(n) < maxfiles { + maxfiles = uint64(n) + } +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go new file mode 100644 index 00000000..928319fb --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_darwin.go @@ -0,0 +1,57 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ABSOLUTE", unix.NOTE_ABSOLUTE}, + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_BACKGROUND", unix.NOTE_BACKGROUND}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_CRITICAL", unix.NOTE_CRITICAL}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXITSTATUS", unix.NOTE_EXITSTATUS}, + {"NOTE_EXIT_CSERROR", unix.NOTE_EXIT_CSERROR}, + {"NOTE_EXIT_DECRYPTFAIL", unix.NOTE_EXIT_DECRYPTFAIL}, + {"NOTE_EXIT_DETAIL", unix.NOTE_EXIT_DETAIL}, + {"NOTE_EXIT_DETAIL_MASK", unix.NOTE_EXIT_DETAIL_MASK}, + {"NOTE_EXIT_MEMORY", unix.NOTE_EXIT_MEMORY}, + {"NOTE_EXIT_REPARENTED", unix.NOTE_EXIT_REPARENTED}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_FUNLOCK", unix.NOTE_FUNLOCK}, + {"NOTE_LEEWAY", unix.NOTE_LEEWAY}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_MACHTIME", unix.NOTE_MACHTIME}, + {"NOTE_MACH_CONTINUOUS_TIME", unix.NOTE_MACH_CONTINUOUS_TIME}, + {"NOTE_NONE", unix.NOTE_NONE}, + {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, + {"NOTE_OOB", unix.NOTE_OOB}, + //{"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, -0x100000 (?!) + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_REAP", unix.NOTE_REAP}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_SECONDS", unix.NOTE_SECONDS}, + {"NOTE_SIGNAL", unix.NOTE_SIGNAL}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_USECONDS", unix.NOTE_USECONDS}, + {"NOTE_VM_ERROR", unix.NOTE_VM_ERROR}, + {"NOTE_VM_PRESSURE", unix.NOTE_VM_PRESSURE}, + {"NOTE_VM_PRESSURE_SUDDEN_TERMINATE", unix.NOTE_VM_PRESSURE_SUDDEN_TERMINATE}, + {"NOTE_VM_PRESSURE_TERMINATE", unix.NOTE_VM_PRESSURE_TERMINATE}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go new file mode 100644 index 00000000..3186b0c3 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_dragonfly.go @@ -0,0 +1,33 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_OOB", unix.NOTE_OOB}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go new file mode 100644 index 00000000..f69fdb93 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_freebsd.go @@ -0,0 +1,42 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ABSTIME", unix.NOTE_ABSTIME}, + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_CLOSE", unix.NOTE_CLOSE}, + {"NOTE_CLOSE_WRITE", unix.NOTE_CLOSE_WRITE}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FFAND", unix.NOTE_FFAND}, + {"NOTE_FFCOPY", unix.NOTE_FFCOPY}, + {"NOTE_FFCTRLMASK", unix.NOTE_FFCTRLMASK}, + {"NOTE_FFLAGSMASK", unix.NOTE_FFLAGSMASK}, + {"NOTE_FFNOP", unix.NOTE_FFNOP}, + {"NOTE_FFOR", unix.NOTE_FFOR}, + {"NOTE_FILE_POLL", unix.NOTE_FILE_POLL}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_MSECONDS", unix.NOTE_MSECONDS}, + {"NOTE_NSECONDS", unix.NOTE_NSECONDS}, + {"NOTE_OPEN", unix.NOTE_OPEN}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_READ", unix.NOTE_READ}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_SECONDS", unix.NOTE_SECONDS}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRIGGER", unix.NOTE_TRIGGER}, + {"NOTE_USECONDS", unix.NOTE_USECONDS}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go new file mode 100644 index 00000000..607e683b --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_kqueue.go @@ -0,0 +1,32 @@ +//go:build freebsd || openbsd || netbsd || dragonfly || darwin + +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, kevent *unix.Kevent_t) { + mask := uint32(kevent.Fflags) + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-60s → %q\n", + time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go new file mode 100644 index 00000000..35c734be --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_linux.go @@ -0,0 +1,56 @@ +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, mask, cookie uint32) { + names := []struct { + n string + m uint32 + }{ + {"IN_ACCESS", unix.IN_ACCESS}, + {"IN_ATTRIB", unix.IN_ATTRIB}, + {"IN_CLOSE", unix.IN_CLOSE}, + {"IN_CLOSE_NOWRITE", unix.IN_CLOSE_NOWRITE}, + {"IN_CLOSE_WRITE", unix.IN_CLOSE_WRITE}, + {"IN_CREATE", unix.IN_CREATE}, + {"IN_DELETE", unix.IN_DELETE}, + {"IN_DELETE_SELF", unix.IN_DELETE_SELF}, + {"IN_IGNORED", unix.IN_IGNORED}, + {"IN_ISDIR", unix.IN_ISDIR}, + {"IN_MODIFY", unix.IN_MODIFY}, + {"IN_MOVE", unix.IN_MOVE}, + {"IN_MOVED_FROM", unix.IN_MOVED_FROM}, + {"IN_MOVED_TO", unix.IN_MOVED_TO}, + {"IN_MOVE_SELF", unix.IN_MOVE_SELF}, + {"IN_OPEN", unix.IN_OPEN}, + {"IN_Q_OVERFLOW", unix.IN_Q_OVERFLOW}, + {"IN_UNMOUNT", unix.IN_UNMOUNT}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + var c string + if cookie > 0 { + c = fmt.Sprintf("(cookie: %d) ", cookie) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-30s → %s%q\n", + time.Now().Format("15:04:05.000000000"), strings.Join(l, "|"), c, name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go new file mode 100644 index 00000000..e5b3b6f6 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_netbsd.go @@ -0,0 +1,25 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go new file mode 100644 index 00000000..1dd455bc --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_openbsd.go @@ -0,0 +1,28 @@ +package internal + +import "golang.org/x/sys/unix" + +var names = []struct { + n string + m uint32 +}{ + {"NOTE_ATTRIB", unix.NOTE_ATTRIB}, + // {"NOTE_CHANGE", unix.NOTE_CHANGE}, // Not on 386? + {"NOTE_CHILD", unix.NOTE_CHILD}, + {"NOTE_DELETE", unix.NOTE_DELETE}, + {"NOTE_EOF", unix.NOTE_EOF}, + {"NOTE_EXEC", unix.NOTE_EXEC}, + {"NOTE_EXIT", unix.NOTE_EXIT}, + {"NOTE_EXTEND", unix.NOTE_EXTEND}, + {"NOTE_FORK", unix.NOTE_FORK}, + {"NOTE_LINK", unix.NOTE_LINK}, + {"NOTE_LOWAT", unix.NOTE_LOWAT}, + {"NOTE_PCTRLMASK", unix.NOTE_PCTRLMASK}, + {"NOTE_PDATAMASK", unix.NOTE_PDATAMASK}, + {"NOTE_RENAME", unix.NOTE_RENAME}, + {"NOTE_REVOKE", unix.NOTE_REVOKE}, + {"NOTE_TRACK", unix.NOTE_TRACK}, + {"NOTE_TRACKERR", unix.NOTE_TRACKERR}, + {"NOTE_TRUNCATE", unix.NOTE_TRUNCATE}, + {"NOTE_WRITE", unix.NOTE_WRITE}, +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go new file mode 100644 index 00000000..f1b2e73b --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_solaris.go @@ -0,0 +1,45 @@ +package internal + +import ( + "fmt" + "os" + "strings" + "time" + + "golang.org/x/sys/unix" +) + +func Debug(name string, mask int32) { + names := []struct { + n string + m int32 + }{ + {"FILE_ACCESS", unix.FILE_ACCESS}, + {"FILE_MODIFIED", unix.FILE_MODIFIED}, + {"FILE_ATTRIB", unix.FILE_ATTRIB}, + {"FILE_TRUNC", unix.FILE_TRUNC}, + {"FILE_NOFOLLOW", unix.FILE_NOFOLLOW}, + {"FILE_DELETE", unix.FILE_DELETE}, + {"FILE_RENAME_TO", unix.FILE_RENAME_TO}, + {"FILE_RENAME_FROM", unix.FILE_RENAME_FROM}, + {"UNMOUNTED", unix.UNMOUNTED}, + {"MOUNTEDOVER", unix.MOUNTEDOVER}, + {"FILE_EXCEPTION", unix.FILE_EXCEPTION}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %10d:%-30s → %q\n", + time.Now().Format("15:04:05.000000000"), mask, strings.Join(l, " | "), name) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go b/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go new file mode 100644 index 00000000..52bf4ce5 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/debug_windows.go @@ -0,0 +1,40 @@ +package internal + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "time" + + "golang.org/x/sys/windows" +) + +func Debug(name string, mask uint32) { + names := []struct { + n string + m uint32 + }{ + {"FILE_ACTION_ADDED", windows.FILE_ACTION_ADDED}, + {"FILE_ACTION_REMOVED", windows.FILE_ACTION_REMOVED}, + {"FILE_ACTION_MODIFIED", windows.FILE_ACTION_MODIFIED}, + {"FILE_ACTION_RENAMED_OLD_NAME", windows.FILE_ACTION_RENAMED_OLD_NAME}, + {"FILE_ACTION_RENAMED_NEW_NAME", windows.FILE_ACTION_RENAMED_NEW_NAME}, + } + + var ( + l []string + unknown = mask + ) + for _, n := range names { + if mask&n.m == n.m { + l = append(l, n.n) + unknown ^= n.m + } + } + if unknown > 0 { + l = append(l, fmt.Sprintf("0x%x", unknown)) + } + fmt.Fprintf(os.Stderr, "FSNOTIFY_DEBUG: %s %-65s → %q\n", + time.Now().Format("15:04:05.000000000"), strings.Join(l, " | "), filepath.ToSlash(name)) +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go b/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go new file mode 100644 index 00000000..5ac8b507 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/freebsd.go @@ -0,0 +1,31 @@ +//go:build freebsd + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + ErrSyscallEACCES = syscall.EACCES + ErrUnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +func SetRlimit() { + // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = uint64(l.Cur) +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, uint64(dev)) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/internal.go b/vendor/github.com/fsnotify/fsnotify/internal/internal.go new file mode 100644 index 00000000..7daa45e1 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/internal.go @@ -0,0 +1,2 @@ +// Package internal contains some helpers. +package internal diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix.go b/vendor/github.com/fsnotify/fsnotify/internal/unix.go new file mode 100644 index 00000000..b251fb80 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/unix.go @@ -0,0 +1,31 @@ +//go:build !windows && !darwin && !freebsd && !plan9 + +package internal + +import ( + "syscall" + + "golang.org/x/sys/unix" +) + +var ( + ErrSyscallEACCES = syscall.EACCES + ErrUnixEACCES = unix.EACCES +) + +var maxfiles uint64 + +func SetRlimit() { + // Go 1.19 will do this automatically: https://go-review.googlesource.com/c/go/+/393354/ + var l syscall.Rlimit + err := syscall.Getrlimit(syscall.RLIMIT_NOFILE, &l) + if err == nil && l.Cur != l.Max { + l.Cur = l.Max + syscall.Setrlimit(syscall.RLIMIT_NOFILE, &l) + } + maxfiles = uint64(l.Cur) +} + +func Maxfiles() uint64 { return maxfiles } +func Mkfifo(path string, mode uint32) error { return unix.Mkfifo(path, mode) } +func Mknod(path string, mode uint32, dev int) error { return unix.Mknod(path, mode, dev) } diff --git a/vendor/github.com/fsnotify/fsnotify/internal/unix2.go b/vendor/github.com/fsnotify/fsnotify/internal/unix2.go new file mode 100644 index 00000000..37dfeddc --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/unix2.go @@ -0,0 +1,7 @@ +//go:build !windows + +package internal + +func HasPrivilegesForSymlink() bool { + return true +} diff --git a/vendor/github.com/fsnotify/fsnotify/internal/windows.go b/vendor/github.com/fsnotify/fsnotify/internal/windows.go new file mode 100644 index 00000000..896bc2e5 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/internal/windows.go @@ -0,0 +1,41 @@ +//go:build windows + +package internal + +import ( + "errors" + + "golang.org/x/sys/windows" +) + +// Just a dummy. +var ( + ErrSyscallEACCES = errors.New("dummy") + ErrUnixEACCES = errors.New("dummy") +) + +func SetRlimit() {} +func Maxfiles() uint64 { return 1<<64 - 1 } +func Mkfifo(path string, mode uint32) error { return errors.New("no FIFOs on Windows") } +func Mknod(path string, mode uint32, dev int) error { return errors.New("no device nodes on Windows") } + +func HasPrivilegesForSymlink() bool { + var sid *windows.SID + err := windows.AllocateAndInitializeSid( + &windows.SECURITY_NT_AUTHORITY, + 2, + windows.SECURITY_BUILTIN_DOMAIN_RID, + windows.DOMAIN_ALIAS_RID_ADMINS, + 0, 0, 0, 0, 0, 0, + &sid) + if err != nil { + return false + } + defer windows.FreeSid(sid) + token := windows.Token(0) + member, err := token.IsMember(sid) + if err != nil { + return false + } + return member || token.IsElevated() +} diff --git a/vendor/github.com/fsnotify/fsnotify/shared.go b/vendor/github.com/fsnotify/fsnotify/shared.go new file mode 100644 index 00000000..3ee9b58f --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/shared.go @@ -0,0 +1,64 @@ +package fsnotify + +import "sync" + +type shared struct { + Events chan Event + Errors chan error + done chan struct{} + mu sync.Mutex +} + +func newShared(ev chan Event, errs chan error) *shared { + return &shared{ + Events: ev, + Errors: errs, + done: make(chan struct{}), + } +} + +// Returns true if the event was sent, or false if watcher is closed. +func (w *shared) sendEvent(e Event) bool { + if e.Op == 0 { + return true + } + select { + case <-w.done: + return false + case w.Events <- e: + return true + } +} + +// Returns true if the error was sent, or false if watcher is closed. +func (w *shared) sendError(err error) bool { + if err == nil { + return true + } + select { + case <-w.done: + return false + case w.Errors <- err: + return true + } +} + +func (w *shared) isClosed() bool { + select { + case <-w.done: + return true + default: + return false + } +} + +// Mark as closed; returns true if it was already closed. +func (w *shared) close() bool { + w.mu.Lock() + defer w.mu.Unlock() + if w.isClosed() { + return true + } + close(w.done) + return false +} diff --git a/vendor/github.com/fsnotify/fsnotify/staticcheck.conf b/vendor/github.com/fsnotify/fsnotify/staticcheck.conf new file mode 100644 index 00000000..8fa7351f --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/staticcheck.conf @@ -0,0 +1,3 @@ +checks = ['all', + '-U1000', # Don't complain about unused functions. +] diff --git a/vendor/github.com/fsnotify/fsnotify/system_bsd.go b/vendor/github.com/fsnotify/fsnotify/system_bsd.go new file mode 100644 index 00000000..f65e8fe3 --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/system_bsd.go @@ -0,0 +1,7 @@ +//go:build freebsd || openbsd || netbsd || dragonfly + +package fsnotify + +import "golang.org/x/sys/unix" + +const openMode = unix.O_NONBLOCK | unix.O_RDONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/fsnotify/fsnotify/system_darwin.go b/vendor/github.com/fsnotify/fsnotify/system_darwin.go new file mode 100644 index 00000000..a29fc7aa --- /dev/null +++ b/vendor/github.com/fsnotify/fsnotify/system_darwin.go @@ -0,0 +1,8 @@ +//go:build darwin + +package fsnotify + +import "golang.org/x/sys/unix" + +// note: this constant is not defined on BSD +const openMode = unix.O_EVTONLY | unix.O_CLOEXEC diff --git a/vendor/github.com/opencontainers/runtime-spec/LICENSE b/vendor/github.com/opencontainers/runtime-spec/LICENSE new file mode 100644 index 00000000..bdc40365 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 The Linux Foundation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go new file mode 100644 index 00000000..1aa0693b --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/config.go @@ -0,0 +1,917 @@ +package specs + +import "os" + +// Spec is the base configuration for the container. +type Spec struct { + // Version of the Open Container Initiative Runtime Specification with which the bundle complies. + Version string `json:"ociVersion"` + // Process configures the container process. + Process *Process `json:"process,omitempty"` + // Root configures the container's root filesystem. + Root *Root `json:"root,omitempty"` + // Hostname configures the container's hostname. + Hostname string `json:"hostname,omitempty"` + // Domainname configures the container's domainname. + Domainname string `json:"domainname,omitempty"` + // Mounts configures additional mounts (on top of Root). + Mounts []Mount `json:"mounts,omitempty"` + // Hooks configures callbacks for container lifecycle events. + Hooks *Hooks `json:"hooks,omitempty" platform:"linux,solaris,zos"` + // Annotations contains arbitrary metadata for the container. + Annotations map[string]string `json:"annotations,omitempty"` + + // Linux is platform-specific configuration for Linux based containers. + Linux *Linux `json:"linux,omitempty" platform:"linux"` + // Solaris is platform-specific configuration for Solaris based containers. + Solaris *Solaris `json:"solaris,omitempty" platform:"solaris"` + // Windows is platform-specific configuration for Windows based containers. + Windows *Windows `json:"windows,omitempty" platform:"windows"` + // VM specifies configuration for virtual-machine-based containers. + VM *VM `json:"vm,omitempty" platform:"vm"` + // ZOS is platform-specific configuration for z/OS based containers. + ZOS *ZOS `json:"zos,omitempty" platform:"zos"` +} + +// Scheduler represents the scheduling attributes for a process. It is based on +// the Linux sched_setattr(2) syscall. +type Scheduler struct { + // Policy represents the scheduling policy (e.g., SCHED_FIFO, SCHED_RR, SCHED_OTHER). + Policy LinuxSchedulerPolicy `json:"policy"` + + // Nice is the nice value for the process, which affects its priority. + Nice int32 `json:"nice,omitempty"` + + // Priority represents the static priority of the process. + Priority int32 `json:"priority,omitempty"` + + // Flags is an array of scheduling flags. + Flags []LinuxSchedulerFlag `json:"flags,omitempty"` + + // The following ones are used by the DEADLINE scheduler. + + // Runtime is the amount of time in nanoseconds during which the process + // is allowed to run in a given period. + Runtime uint64 `json:"runtime,omitempty"` + + // Deadline is the absolute deadline for the process to complete its execution. + Deadline uint64 `json:"deadline,omitempty"` + + // Period is the length of the period in nanoseconds used for determining the process runtime. + Period uint64 `json:"period,omitempty"` +} + +// Process contains information to start a specific application inside the container. +type Process struct { + // Terminal creates an interactive terminal for the container. + Terminal bool `json:"terminal,omitempty"` + // ConsoleSize specifies the size of the console. + ConsoleSize *Box `json:"consoleSize,omitempty"` + // User specifies user information for the process. + User User `json:"user"` + // Args specifies the binary and arguments for the application to execute. + Args []string `json:"args,omitempty"` + // CommandLine specifies the full command line for the application to execute on Windows. + CommandLine string `json:"commandLine,omitempty" platform:"windows"` + // Env populates the process environment for the process. + Env []string `json:"env,omitempty"` + // Cwd is the current working directory for the process and must be + // relative to the container's root. + Cwd string `json:"cwd"` + // Capabilities are Linux capabilities that are kept for the process. + Capabilities *LinuxCapabilities `json:"capabilities,omitempty" platform:"linux"` + // Rlimits specifies rlimit options to apply to the process. + Rlimits []POSIXRlimit `json:"rlimits,omitempty" platform:"linux,solaris,zos"` + // NoNewPrivileges controls whether additional privileges could be gained by processes in the container. + NoNewPrivileges bool `json:"noNewPrivileges,omitempty" platform:"linux,zos"` + // ApparmorProfile specifies the apparmor profile for the container. + ApparmorProfile string `json:"apparmorProfile,omitempty" platform:"linux"` + // Specify an oom_score_adj for the container. + OOMScoreAdj *int `json:"oomScoreAdj,omitempty" platform:"linux"` + // Scheduler specifies the scheduling attributes for a process + Scheduler *Scheduler `json:"scheduler,omitempty" platform:"linux"` + // SelinuxLabel specifies the selinux context that the container process is run as. + SelinuxLabel string `json:"selinuxLabel,omitempty" platform:"linux"` + // IOPriority contains the I/O priority settings for the cgroup. + IOPriority *LinuxIOPriority `json:"ioPriority,omitempty" platform:"linux"` + // ExecCPUAffinity specifies CPU affinity for exec processes. + ExecCPUAffinity *CPUAffinity `json:"execCPUAffinity,omitempty" platform:"linux"` +} + +// LinuxCapabilities specifies the list of allowed capabilities that are kept for a process. +// https://man7.org/linux/man-pages/man7/capabilities.7.html +type LinuxCapabilities struct { + // Bounding is the set of capabilities checked by the kernel. + Bounding []string `json:"bounding,omitempty" platform:"linux"` + // Effective is the set of capabilities checked by the kernel. + Effective []string `json:"effective,omitempty" platform:"linux"` + // Inheritable is the capabilities preserved across execve. + Inheritable []string `json:"inheritable,omitempty" platform:"linux"` + // Permitted is the limiting superset for effective capabilities. + Permitted []string `json:"permitted,omitempty" platform:"linux"` + // Ambient is the ambient set of capabilities that are kept. + Ambient []string `json:"ambient,omitempty" platform:"linux"` +} + +// IOPriority represents I/O priority settings for the container's processes within the process group. +type LinuxIOPriority struct { + Class IOPriorityClass `json:"class"` + Priority int `json:"priority"` +} + +// IOPriorityClass represents an I/O scheduling class. +type IOPriorityClass string + +// Possible values for IOPriorityClass. +const ( + IOPRIO_CLASS_RT IOPriorityClass = "IOPRIO_CLASS_RT" + IOPRIO_CLASS_BE IOPriorityClass = "IOPRIO_CLASS_BE" + IOPRIO_CLASS_IDLE IOPriorityClass = "IOPRIO_CLASS_IDLE" +) + +// CPUAffinity specifies process' CPU affinity. +type CPUAffinity struct { + Initial string `json:"initial,omitempty"` + Final string `json:"final,omitempty"` +} + +// Box specifies dimensions of a rectangle. Used for specifying the size of a console. +type Box struct { + // Height is the vertical dimension of a box. + Height uint `json:"height"` + // Width is the horizontal dimension of a box. + Width uint `json:"width"` +} + +// User specifies specific user (and group) information for the container process. +type User struct { + // UID is the user id. + UID uint32 `json:"uid" platform:"linux,solaris,zos"` + // GID is the group id. + GID uint32 `json:"gid" platform:"linux,solaris,zos"` + // Umask is the umask for the init process. + Umask *uint32 `json:"umask,omitempty" platform:"linux,solaris,zos"` + // AdditionalGids are additional group ids set for the container's process. + AdditionalGids []uint32 `json:"additionalGids,omitempty" platform:"linux,solaris"` + // Username is the user name. + Username string `json:"username,omitempty" platform:"windows"` +} + +// Root contains information about the container's root filesystem on the host. +type Root struct { + // Path is the absolute path to the container's root filesystem. + Path string `json:"path"` + // Readonly makes the root filesystem for the container readonly before the process is executed. + Readonly bool `json:"readonly,omitempty"` +} + +// Mount specifies a mount for a container. +type Mount struct { + // Destination is the absolute path where the mount will be placed in the container. + Destination string `json:"destination"` + // Type specifies the mount kind. + Type string `json:"type,omitempty" platform:"linux,solaris,zos"` + // Source specifies the source path of the mount. + Source string `json:"source,omitempty"` + // Options are fstab style mount options. + Options []string `json:"options,omitempty"` + + // UID/GID mappings used for changing file owners w/o calling chown, fs should support it. + // Every mount point could have its own mapping. + UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty" platform:"linux"` + GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty" platform:"linux"` +} + +// Hook specifies a command that is run at a particular event in the lifecycle of a container +type Hook struct { + Path string `json:"path"` + Args []string `json:"args,omitempty"` + Env []string `json:"env,omitempty"` + Timeout *int `json:"timeout,omitempty"` +} + +// Hooks specifies a command that is run in the container at a particular event in the lifecycle of a container +// Hooks for container setup and teardown +type Hooks struct { + // Prestart is Deprecated. Prestart is a list of hooks to be run before the container process is executed. + // It is called in the Runtime Namespace + // + // Deprecated: use [Hooks.CreateRuntime], [Hooks.CreateContainer], and + // [Hooks.StartContainer] instead, which allow more granular hook control + // during the create and start phase. + Prestart []Hook `json:"prestart,omitempty"` + // CreateRuntime is a list of hooks to be run after the container has been created but before pivot_root or any equivalent operation has been called + // It is called in the Runtime Namespace + CreateRuntime []Hook `json:"createRuntime,omitempty"` + // CreateContainer is a list of hooks to be run after the container has been created but before pivot_root or any equivalent operation has been called + // It is called in the Container Namespace + CreateContainer []Hook `json:"createContainer,omitempty"` + // StartContainer is a list of hooks to be run after the start operation is called but before the container process is started + // It is called in the Container Namespace + StartContainer []Hook `json:"startContainer,omitempty"` + // Poststart is a list of hooks to be run after the container process is started. + // It is called in the Runtime Namespace + Poststart []Hook `json:"poststart,omitempty"` + // Poststop is a list of hooks to be run after the container process exits. + // It is called in the Runtime Namespace + Poststop []Hook `json:"poststop,omitempty"` +} + +// Linux contains platform-specific configuration for Linux based containers. +type Linux struct { + // UIDMapping specifies user mappings for supporting user namespaces. + UIDMappings []LinuxIDMapping `json:"uidMappings,omitempty"` + // GIDMapping specifies group mappings for supporting user namespaces. + GIDMappings []LinuxIDMapping `json:"gidMappings,omitempty"` + // Sysctl are a set of key value pairs that are set for the container on start + Sysctl map[string]string `json:"sysctl,omitempty"` + // Resources contain cgroup information for handling resource constraints + // for the container + Resources *LinuxResources `json:"resources,omitempty"` + // CgroupsPath specifies the path to cgroups that are created and/or joined by the container. + // The path is expected to be relative to the cgroups mountpoint. + // If resources are specified, the cgroups at CgroupsPath will be updated based on resources. + CgroupsPath string `json:"cgroupsPath,omitempty"` + // Namespaces contains the namespaces that are created and/or joined by the container + Namespaces []LinuxNamespace `json:"namespaces,omitempty"` + // Devices are a list of device nodes that are created for the container + Devices []LinuxDevice `json:"devices,omitempty"` + // Seccomp specifies the seccomp security settings for the container. + Seccomp *LinuxSeccomp `json:"seccomp,omitempty"` + // RootfsPropagation is the rootfs mount propagation mode for the container. + RootfsPropagation string `json:"rootfsPropagation,omitempty"` + // MaskedPaths masks over the provided paths inside the container. + MaskedPaths []string `json:"maskedPaths,omitempty"` + // ReadonlyPaths sets the provided paths as RO inside the container. + ReadonlyPaths []string `json:"readonlyPaths,omitempty"` + // MountLabel specifies the selinux context for the mounts in the container. + MountLabel string `json:"mountLabel,omitempty"` + // IntelRdt contains Intel Resource Director Technology (RDT) information for + // handling resource constraints and monitoring metrics (e.g., L3 cache, memory bandwidth) for the container + IntelRdt *LinuxIntelRdt `json:"intelRdt,omitempty"` + // Personality contains configuration for the Linux personality syscall + Personality *LinuxPersonality `json:"personality,omitempty"` + // TimeOffsets specifies the offset for supporting time namespaces. + TimeOffsets map[string]LinuxTimeOffset `json:"timeOffsets,omitempty"` +} + +// LinuxNamespace is the configuration for a Linux namespace +type LinuxNamespace struct { + // Type is the type of namespace + Type LinuxNamespaceType `json:"type"` + // Path is a path to an existing namespace persisted on disk that can be joined + // and is of the same type + Path string `json:"path,omitempty"` +} + +// LinuxNamespaceType is one of the Linux namespaces +type LinuxNamespaceType string + +const ( + // PIDNamespace for isolating process IDs + PIDNamespace LinuxNamespaceType = "pid" + // NetworkNamespace for isolating network devices, stacks, ports, etc + NetworkNamespace LinuxNamespaceType = "network" + // MountNamespace for isolating mount points + MountNamespace LinuxNamespaceType = "mount" + // IPCNamespace for isolating System V IPC, POSIX message queues + IPCNamespace LinuxNamespaceType = "ipc" + // UTSNamespace for isolating hostname and NIS domain name + UTSNamespace LinuxNamespaceType = "uts" + // UserNamespace for isolating user and group IDs + UserNamespace LinuxNamespaceType = "user" + // CgroupNamespace for isolating cgroup hierarchies + CgroupNamespace LinuxNamespaceType = "cgroup" + // TimeNamespace for isolating the clocks + TimeNamespace LinuxNamespaceType = "time" +) + +// LinuxIDMapping specifies UID/GID mappings +type LinuxIDMapping struct { + // ContainerID is the starting UID/GID in the container + ContainerID uint32 `json:"containerID"` + // HostID is the starting UID/GID on the host to be mapped to 'ContainerID' + HostID uint32 `json:"hostID"` + // Size is the number of IDs to be mapped + Size uint32 `json:"size"` +} + +// LinuxTimeOffset specifies the offset for Time Namespace +type LinuxTimeOffset struct { + // Secs is the offset of clock (in secs) in the container + Secs int64 `json:"secs,omitempty"` + // Nanosecs is the additional offset for Secs (in nanosecs) + Nanosecs uint32 `json:"nanosecs,omitempty"` +} + +// POSIXRlimit type and restrictions +type POSIXRlimit struct { + // Type of the rlimit to set + Type string `json:"type"` + // Hard is the hard limit for the specified type + Hard uint64 `json:"hard"` + // Soft is the soft limit for the specified type + Soft uint64 `json:"soft"` +} + +// LinuxHugepageLimit structure corresponds to limiting kernel hugepages. +// Default to reservation limits if supported. Otherwise fallback to page fault limits. +type LinuxHugepageLimit struct { + // Pagesize is the hugepage size. + // Format: "B' (e.g. 64KB, 2MB, 1GB, etc.). + Pagesize string `json:"pageSize"` + // Limit is the limit of "hugepagesize" hugetlb reservations (if supported) or usage. + Limit uint64 `json:"limit"` +} + +// LinuxInterfacePriority for network interfaces +type LinuxInterfacePriority struct { + // Name is the name of the network interface + Name string `json:"name"` + // Priority for the interface + Priority uint32 `json:"priority"` +} + +// LinuxBlockIODevice holds major:minor format supported in blkio cgroup +type LinuxBlockIODevice struct { + // Major is the device's major number. + Major int64 `json:"major"` + // Minor is the device's minor number. + Minor int64 `json:"minor"` +} + +// LinuxWeightDevice struct holds a `major:minor weight` pair for weightDevice +type LinuxWeightDevice struct { + LinuxBlockIODevice + // Weight is the bandwidth rate for the device. + Weight *uint16 `json:"weight,omitempty"` + // LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, CFQ scheduler only + LeafWeight *uint16 `json:"leafWeight,omitempty"` +} + +// LinuxThrottleDevice struct holds a `major:minor rate_per_second` pair +type LinuxThrottleDevice struct { + LinuxBlockIODevice + // Rate is the IO rate limit per cgroup per device + Rate uint64 `json:"rate"` +} + +// LinuxBlockIO for Linux cgroup 'blkio' resource management +type LinuxBlockIO struct { + // Specifies per cgroup weight + Weight *uint16 `json:"weight,omitempty"` + // Specifies tasks' weight in the given cgroup while competing with the cgroup's child cgroups, CFQ scheduler only + LeafWeight *uint16 `json:"leafWeight,omitempty"` + // Weight per cgroup per device, can override BlkioWeight + WeightDevice []LinuxWeightDevice `json:"weightDevice,omitempty"` + // IO read rate limit per cgroup per device, bytes per second + ThrottleReadBpsDevice []LinuxThrottleDevice `json:"throttleReadBpsDevice,omitempty"` + // IO write rate limit per cgroup per device, bytes per second + ThrottleWriteBpsDevice []LinuxThrottleDevice `json:"throttleWriteBpsDevice,omitempty"` + // IO read rate limit per cgroup per device, IO per second + ThrottleReadIOPSDevice []LinuxThrottleDevice `json:"throttleReadIOPSDevice,omitempty"` + // IO write rate limit per cgroup per device, IO per second + ThrottleWriteIOPSDevice []LinuxThrottleDevice `json:"throttleWriteIOPSDevice,omitempty"` +} + +// LinuxMemory for Linux cgroup 'memory' resource management +type LinuxMemory struct { + // Memory limit (in bytes). + Limit *int64 `json:"limit,omitempty"` + // Memory reservation or soft_limit (in bytes). + Reservation *int64 `json:"reservation,omitempty"` + // Total memory limit (memory + swap). + Swap *int64 `json:"swap,omitempty"` + // Kernel memory limit (in bytes). + // + // Deprecated: kernel-memory limits are not supported in cgroups v2, and + // were obsoleted in [kernel v5.4]. This field should no longer be used, + // as it may be ignored by runtimes. + // + // [kernel v5.4]: https://github.com/torvalds/linux/commit/0158115f702b0ba208ab0 + Kernel *int64 `json:"kernel,omitempty"` + // Kernel memory limit for tcp (in bytes) + KernelTCP *int64 `json:"kernelTCP,omitempty"` + // How aggressive the kernel will swap memory pages. + Swappiness *uint64 `json:"swappiness,omitempty"` + // DisableOOMKiller disables the OOM killer for out of memory conditions + DisableOOMKiller *bool `json:"disableOOMKiller,omitempty"` + // Enables hierarchical memory accounting + UseHierarchy *bool `json:"useHierarchy,omitempty"` + // CheckBeforeUpdate enables checking if a new memory limit is lower + // than the current usage during update, and if so, rejecting the new + // limit. + CheckBeforeUpdate *bool `json:"checkBeforeUpdate,omitempty"` +} + +// LinuxCPU for Linux cgroup 'cpu' resource management +type LinuxCPU struct { + // CPU shares (relative weight (ratio) vs. other cgroups with cpu shares). + Shares *uint64 `json:"shares,omitempty"` + // CPU hardcap limit (in usecs). Allowed cpu time in a given period. + Quota *int64 `json:"quota,omitempty"` + // CPU hardcap burst limit (in usecs). Allowed accumulated cpu time additionally for burst in a + // given period. + Burst *uint64 `json:"burst,omitempty"` + // CPU period to be used for hardcapping (in usecs). + Period *uint64 `json:"period,omitempty"` + // How much time realtime scheduling may use (in usecs). + RealtimeRuntime *int64 `json:"realtimeRuntime,omitempty"` + // CPU period to be used for realtime scheduling (in usecs). + RealtimePeriod *uint64 `json:"realtimePeriod,omitempty"` + // CPUs to use within the cpuset. Default is to use any CPU available. + Cpus string `json:"cpus,omitempty"` + // List of memory nodes in the cpuset. Default is to use any available memory node. + Mems string `json:"mems,omitempty"` + // cgroups are configured with minimum weight, 0: default behavior, 1: SCHED_IDLE. + Idle *int64 `json:"idle,omitempty"` +} + +// LinuxPids for Linux cgroup 'pids' resource management (Linux 4.3) +type LinuxPids struct { + // Maximum number of PIDs. Default is "no limit". + Limit int64 `json:"limit"` +} + +// LinuxNetwork identification and priority configuration +type LinuxNetwork struct { + // Set class identifier for container's network packets + ClassID *uint32 `json:"classID,omitempty"` + // Set priority of network traffic for container + Priorities []LinuxInterfacePriority `json:"priorities,omitempty"` +} + +// LinuxRdma for Linux cgroup 'rdma' resource management (Linux 4.11) +type LinuxRdma struct { + // Maximum number of HCA handles that can be opened. Default is "no limit". + HcaHandles *uint32 `json:"hcaHandles,omitempty"` + // Maximum number of HCA objects that can be created. Default is "no limit". + HcaObjects *uint32 `json:"hcaObjects,omitempty"` +} + +// LinuxResources has container runtime resource constraints +type LinuxResources struct { + // Devices configures the device allowlist. + Devices []LinuxDeviceCgroup `json:"devices,omitempty"` + // Memory restriction configuration + Memory *LinuxMemory `json:"memory,omitempty"` + // CPU resource restriction configuration + CPU *LinuxCPU `json:"cpu,omitempty"` + // Task resource restriction configuration. + Pids *LinuxPids `json:"pids,omitempty"` + // BlockIO restriction configuration + BlockIO *LinuxBlockIO `json:"blockIO,omitempty"` + // Hugetlb limits (in bytes). Default to reservation limits if supported. + HugepageLimits []LinuxHugepageLimit `json:"hugepageLimits,omitempty"` + // Network restriction configuration + Network *LinuxNetwork `json:"network,omitempty"` + // Rdma resource restriction configuration. + // Limits are a set of key value pairs that define RDMA resource limits, + // where the key is device name and value is resource limits. + Rdma map[string]LinuxRdma `json:"rdma,omitempty"` + // Unified resources. + Unified map[string]string `json:"unified,omitempty"` +} + +// LinuxDevice represents the mknod information for a Linux special device file +type LinuxDevice struct { + // Path to the device. + Path string `json:"path"` + // Device type, block, char, etc. + Type string `json:"type"` + // Major is the device's major number. + Major int64 `json:"major"` + // Minor is the device's minor number. + Minor int64 `json:"minor"` + // FileMode permission bits for the device. + FileMode *os.FileMode `json:"fileMode,omitempty"` + // UID of the device. + UID *uint32 `json:"uid,omitempty"` + // Gid of the device. + GID *uint32 `json:"gid,omitempty"` +} + +// LinuxDeviceCgroup represents a device rule for the devices specified to +// the device controller +type LinuxDeviceCgroup struct { + // Allow or deny + Allow bool `json:"allow"` + // Device type, block, char, etc. + Type string `json:"type,omitempty"` + // Major is the device's major number. + Major *int64 `json:"major,omitempty"` + // Minor is the device's minor number. + Minor *int64 `json:"minor,omitempty"` + // Cgroup access permissions format, rwm. + Access string `json:"access,omitempty"` +} + +// LinuxPersonalityDomain refers to a personality domain. +type LinuxPersonalityDomain string + +// LinuxPersonalityFlag refers to an additional personality flag. None are currently defined. +type LinuxPersonalityFlag string + +// Define domain and flags for Personality +const ( + // PerLinux is the standard Linux personality + PerLinux LinuxPersonalityDomain = "LINUX" + // PerLinux32 sets personality to 32 bit + PerLinux32 LinuxPersonalityDomain = "LINUX32" +) + +// LinuxPersonality represents the Linux personality syscall input +type LinuxPersonality struct { + // Domain for the personality + Domain LinuxPersonalityDomain `json:"domain"` + // Additional flags + Flags []LinuxPersonalityFlag `json:"flags,omitempty"` +} + +// Solaris contains platform-specific configuration for Solaris application containers. +type Solaris struct { + // SMF FMRI which should go "online" before we start the container process. + Milestone string `json:"milestone,omitempty"` + // Maximum set of privileges any process in this container can obtain. + LimitPriv string `json:"limitpriv,omitempty"` + // The maximum amount of shared memory allowed for this container. + MaxShmMemory string `json:"maxShmMemory,omitempty"` + // Specification for automatic creation of network resources for this container. + Anet []SolarisAnet `json:"anet,omitempty"` + // Set limit on the amount of CPU time that can be used by container. + CappedCPU *SolarisCappedCPU `json:"cappedCPU,omitempty"` + // The physical and swap caps on the memory that can be used by this container. + CappedMemory *SolarisCappedMemory `json:"cappedMemory,omitempty"` +} + +// SolarisCappedCPU allows users to set limit on the amount of CPU time that can be used by container. +type SolarisCappedCPU struct { + Ncpus string `json:"ncpus,omitempty"` +} + +// SolarisCappedMemory allows users to set the physical and swap caps on the memory that can be used by this container. +type SolarisCappedMemory struct { + Physical string `json:"physical,omitempty"` + Swap string `json:"swap,omitempty"` +} + +// SolarisAnet provides the specification for automatic creation of network resources for this container. +type SolarisAnet struct { + // Specify a name for the automatically created VNIC datalink. + Linkname string `json:"linkname,omitempty"` + // Specify the link over which the VNIC will be created. + Lowerlink string `json:"lowerLink,omitempty"` + // The set of IP addresses that the container can use. + Allowedaddr string `json:"allowedAddress,omitempty"` + // Specifies whether allowedAddress limitation is to be applied to the VNIC. + Configallowedaddr string `json:"configureAllowedAddress,omitempty"` + // The value of the optional default router. + Defrouter string `json:"defrouter,omitempty"` + // Enable one or more types of link protection. + Linkprotection string `json:"linkProtection,omitempty"` + // Set the VNIC's macAddress + Macaddress string `json:"macAddress,omitempty"` +} + +// Windows defines the runtime configuration for Windows based containers, including Hyper-V containers. +type Windows struct { + // LayerFolders contains a list of absolute paths to directories containing image layers. + LayerFolders []string `json:"layerFolders"` + // Devices are the list of devices to be mapped into the container. + Devices []WindowsDevice `json:"devices,omitempty"` + // Resources contains information for handling resource constraints for the container. + Resources *WindowsResources `json:"resources,omitempty"` + // CredentialSpec contains a JSON object describing a group Managed Service Account (gMSA) specification. + CredentialSpec interface{} `json:"credentialSpec,omitempty"` + // Servicing indicates if the container is being started in a mode to apply a Windows Update servicing operation. + Servicing bool `json:"servicing,omitempty"` + // IgnoreFlushesDuringBoot indicates if the container is being started in a mode where disk writes are not flushed during its boot process. + IgnoreFlushesDuringBoot bool `json:"ignoreFlushesDuringBoot,omitempty"` + // HyperV contains information for running a container with Hyper-V isolation. + HyperV *WindowsHyperV `json:"hyperv,omitempty"` + // Network restriction configuration. + Network *WindowsNetwork `json:"network,omitempty"` +} + +// WindowsDevice represents information about a host device to be mapped into the container. +type WindowsDevice struct { + // Device identifier: interface class GUID, etc. + ID string `json:"id"` + // Device identifier type: "class", etc. + IDType string `json:"idType"` +} + +// WindowsResources has container runtime resource constraints for containers running on Windows. +type WindowsResources struct { + // Memory restriction configuration. + Memory *WindowsMemoryResources `json:"memory,omitempty"` + // CPU resource restriction configuration. + CPU *WindowsCPUResources `json:"cpu,omitempty"` + // Storage restriction configuration. + Storage *WindowsStorageResources `json:"storage,omitempty"` +} + +// WindowsMemoryResources contains memory resource management settings. +type WindowsMemoryResources struct { + // Memory limit in bytes. + Limit *uint64 `json:"limit,omitempty"` +} + +// WindowsCPUResources contains CPU resource management settings. +type WindowsCPUResources struct { + // Count is the number of CPUs available to the container. It represents the + // fraction of the configured processor `count` in a container in relation + // to the processors available in the host. The fraction ultimately + // determines the portion of processor cycles that the threads in a + // container can use during each scheduling interval, as the number of + // cycles per 10,000 cycles. + Count *uint64 `json:"count,omitempty"` + // Shares limits the share of processor time given to the container relative + // to other workloads on the processor. The processor `shares` (`weight` at + // the platform level) is a value between 0 and 10000. + Shares *uint16 `json:"shares,omitempty"` + // Maximum determines the portion of processor cycles that the threads in a + // container can use during each scheduling interval, as the number of + // cycles per 10,000 cycles. Set processor `maximum` to a percentage times + // 100. + Maximum *uint16 `json:"maximum,omitempty"` + // Set of CPUs to affinitize for this container. + Affinity []WindowsCPUGroupAffinity `json:"affinity,omitempty"` +} + +// Similar to _GROUP_AFFINITY struct defined in +// https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/miniport/ns-miniport-_group_affinity +type WindowsCPUGroupAffinity struct { + // CPU mask relative to this CPU group. + Mask uint64 `json:"mask,omitempty"` + // Processor group the mask refers to, as returned by GetLogicalProcessorInformationEx. + Group uint32 `json:"group,omitempty"` +} + +// WindowsStorageResources contains storage resource management settings. +type WindowsStorageResources struct { + // Specifies maximum Iops for the system drive. + Iops *uint64 `json:"iops,omitempty"` + // Specifies maximum bytes per second for the system drive. + Bps *uint64 `json:"bps,omitempty"` + // Sandbox size specifies the minimum size of the system drive in bytes. + SandboxSize *uint64 `json:"sandboxSize,omitempty"` +} + +// WindowsNetwork contains network settings for Windows containers. +type WindowsNetwork struct { + // List of HNS endpoints that the container should connect to. + EndpointList []string `json:"endpointList,omitempty"` + // Specifies if unqualified DNS name resolution is allowed. + AllowUnqualifiedDNSQuery bool `json:"allowUnqualifiedDNSQuery,omitempty"` + // Comma separated list of DNS suffixes to use for name resolution. + DNSSearchList []string `json:"DNSSearchList,omitempty"` + // Name (ID) of the container that we will share with the network stack. + NetworkSharedContainerName string `json:"networkSharedContainerName,omitempty"` + // name (ID) of the network namespace that will be used for the container. + NetworkNamespace string `json:"networkNamespace,omitempty"` +} + +// WindowsHyperV contains information for configuring a container to run with Hyper-V isolation. +type WindowsHyperV struct { + // UtilityVMPath is an optional path to the image used for the Utility VM. + UtilityVMPath string `json:"utilityVMPath,omitempty"` +} + +// VM contains information for virtual-machine-based containers. +type VM struct { + // Hypervisor specifies hypervisor-related configuration for virtual-machine-based containers. + Hypervisor VMHypervisor `json:"hypervisor,omitempty"` + // Kernel specifies kernel-related configuration for virtual-machine-based containers. + Kernel VMKernel `json:"kernel"` + // Image specifies guest image related configuration for virtual-machine-based containers. + Image VMImage `json:"image,omitempty"` +} + +// VMHypervisor contains information about the hypervisor to use for a virtual machine. +type VMHypervisor struct { + // Path is the host path to the hypervisor used to manage the virtual machine. + Path string `json:"path"` + // Parameters specifies parameters to pass to the hypervisor. + Parameters []string `json:"parameters,omitempty"` +} + +// VMKernel contains information about the kernel to use for a virtual machine. +type VMKernel struct { + // Path is the host path to the kernel used to boot the virtual machine. + Path string `json:"path"` + // Parameters specifies parameters to pass to the kernel. + Parameters []string `json:"parameters,omitempty"` + // InitRD is the host path to an initial ramdisk to be used by the kernel. + InitRD string `json:"initrd,omitempty"` +} + +// VMImage contains information about the virtual machine root image. +type VMImage struct { + // Path is the host path to the root image that the VM kernel would boot into. + Path string `json:"path"` + // Format is the root image format type (e.g. "qcow2", "raw", "vhd", etc). + Format string `json:"format"` +} + +// LinuxSeccomp represents syscall restrictions +type LinuxSeccomp struct { + DefaultAction LinuxSeccompAction `json:"defaultAction"` + DefaultErrnoRet *uint `json:"defaultErrnoRet,omitempty"` + Architectures []Arch `json:"architectures,omitempty"` + Flags []LinuxSeccompFlag `json:"flags,omitempty"` + ListenerPath string `json:"listenerPath,omitempty"` + ListenerMetadata string `json:"listenerMetadata,omitempty"` + Syscalls []LinuxSyscall `json:"syscalls,omitempty"` +} + +// Arch used for additional architectures +type Arch string + +// LinuxSeccompFlag is a flag to pass to seccomp(2). +type LinuxSeccompFlag string + +const ( + // LinuxSeccompFlagLog is a seccomp flag to request all returned + // actions except SECCOMP_RET_ALLOW to be logged. An administrator may + // override this filter flag by preventing specific actions from being + // logged via the /proc/sys/kernel/seccomp/actions_logged file. (since + // Linux 4.14) + LinuxSeccompFlagLog LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_LOG" + + // LinuxSeccompFlagSpecAllow can be used to disable Speculative Store + // Bypass mitigation. (since Linux 4.17) + LinuxSeccompFlagSpecAllow LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_SPEC_ALLOW" + + // LinuxSeccompFlagWaitKillableRecv can be used to switch to the wait + // killable semantics. (since Linux 5.19) + LinuxSeccompFlagWaitKillableRecv LinuxSeccompFlag = "SECCOMP_FILTER_FLAG_WAIT_KILLABLE_RECV" +) + +// Additional architectures permitted to be used for system calls +// By default only the native architecture of the kernel is permitted +const ( + ArchX86 Arch = "SCMP_ARCH_X86" + ArchX86_64 Arch = "SCMP_ARCH_X86_64" + ArchX32 Arch = "SCMP_ARCH_X32" + ArchARM Arch = "SCMP_ARCH_ARM" + ArchAARCH64 Arch = "SCMP_ARCH_AARCH64" + ArchMIPS Arch = "SCMP_ARCH_MIPS" + ArchMIPS64 Arch = "SCMP_ARCH_MIPS64" + ArchMIPS64N32 Arch = "SCMP_ARCH_MIPS64N32" + ArchMIPSEL Arch = "SCMP_ARCH_MIPSEL" + ArchMIPSEL64 Arch = "SCMP_ARCH_MIPSEL64" + ArchMIPSEL64N32 Arch = "SCMP_ARCH_MIPSEL64N32" + ArchPPC Arch = "SCMP_ARCH_PPC" + ArchPPC64 Arch = "SCMP_ARCH_PPC64" + ArchPPC64LE Arch = "SCMP_ARCH_PPC64LE" + ArchS390 Arch = "SCMP_ARCH_S390" + ArchS390X Arch = "SCMP_ARCH_S390X" + ArchPARISC Arch = "SCMP_ARCH_PARISC" + ArchPARISC64 Arch = "SCMP_ARCH_PARISC64" + ArchRISCV64 Arch = "SCMP_ARCH_RISCV64" + ArchLOONGARCH64 Arch = "SCMP_ARCH_LOONGARCH64" + ArchM68K Arch = "SCMP_ARCH_M68K" + ArchSH Arch = "SCMP_ARCH_SH" + ArchSHEB Arch = "SCMP_ARCH_SHEB" +) + +// LinuxSeccompAction taken upon Seccomp rule match +type LinuxSeccompAction string + +// Define actions for Seccomp rules +const ( + ActKill LinuxSeccompAction = "SCMP_ACT_KILL" + ActKillProcess LinuxSeccompAction = "SCMP_ACT_KILL_PROCESS" + ActKillThread LinuxSeccompAction = "SCMP_ACT_KILL_THREAD" + ActTrap LinuxSeccompAction = "SCMP_ACT_TRAP" + ActErrno LinuxSeccompAction = "SCMP_ACT_ERRNO" + ActTrace LinuxSeccompAction = "SCMP_ACT_TRACE" + ActAllow LinuxSeccompAction = "SCMP_ACT_ALLOW" + ActLog LinuxSeccompAction = "SCMP_ACT_LOG" + ActNotify LinuxSeccompAction = "SCMP_ACT_NOTIFY" +) + +// LinuxSeccompOperator used to match syscall arguments in Seccomp +type LinuxSeccompOperator string + +// Define operators for syscall arguments in Seccomp +const ( + OpNotEqual LinuxSeccompOperator = "SCMP_CMP_NE" + OpLessThan LinuxSeccompOperator = "SCMP_CMP_LT" + OpLessEqual LinuxSeccompOperator = "SCMP_CMP_LE" + OpEqualTo LinuxSeccompOperator = "SCMP_CMP_EQ" + OpGreaterEqual LinuxSeccompOperator = "SCMP_CMP_GE" + OpGreaterThan LinuxSeccompOperator = "SCMP_CMP_GT" + OpMaskedEqual LinuxSeccompOperator = "SCMP_CMP_MASKED_EQ" +) + +// LinuxSeccompArg used for matching specific syscall arguments in Seccomp +type LinuxSeccompArg struct { + Index uint `json:"index"` + Value uint64 `json:"value"` + ValueTwo uint64 `json:"valueTwo,omitempty"` + Op LinuxSeccompOperator `json:"op"` +} + +// LinuxSyscall is used to match a syscall in Seccomp +type LinuxSyscall struct { + Names []string `json:"names"` + Action LinuxSeccompAction `json:"action"` + ErrnoRet *uint `json:"errnoRet,omitempty"` + Args []LinuxSeccompArg `json:"args,omitempty"` +} + +// LinuxIntelRdt has container runtime resource constraints for Intel RDT CAT and MBA +// features and flags enabling Intel RDT CMT and MBM features. +// Intel RDT features are available in Linux 4.14 and newer kernel versions. +type LinuxIntelRdt struct { + // The identity for RDT Class of Service + ClosID string `json:"closID,omitempty"` + // The schema for L3 cache id and capacity bitmask (CBM) + // Format: "L3:=;=;..." + L3CacheSchema string `json:"l3CacheSchema,omitempty"` + + // The schema of memory bandwidth per L3 cache id + // Format: "MB:=bandwidth0;=bandwidth1;..." + // The unit of memory bandwidth is specified in "percentages" by + // default, and in "MBps" if MBA Software Controller is enabled. + MemBwSchema string `json:"memBwSchema,omitempty"` + + // EnableCMT is the flag to indicate if the Intel RDT CMT is enabled. CMT (Cache Monitoring Technology) supports monitoring of + // the last-level cache (LLC) occupancy for the container. + EnableCMT bool `json:"enableCMT,omitempty"` + + // EnableMBM is the flag to indicate if the Intel RDT MBM is enabled. MBM (Memory Bandwidth Monitoring) supports monitoring of + // total and local memory bandwidth for the container. + EnableMBM bool `json:"enableMBM,omitempty"` +} + +// ZOS contains platform-specific configuration for z/OS based containers. +type ZOS struct { + // Namespaces contains the namespaces that are created and/or joined by the container + Namespaces []ZOSNamespace `json:"namespaces,omitempty"` +} + +// ZOSNamespace is the configuration for a z/OS namespace +type ZOSNamespace struct { + // Type is the type of namespace + Type ZOSNamespaceType `json:"type"` + // Path is a path to an existing namespace persisted on disk that can be joined + // and is of the same type + Path string `json:"path,omitempty"` +} + +// ZOSNamespaceType is one of the z/OS namespaces +type ZOSNamespaceType string + +const ( + // PIDNamespace for isolating process IDs + ZOSPIDNamespace ZOSNamespaceType = "pid" + // MountNamespace for isolating mount points + ZOSMountNamespace ZOSNamespaceType = "mount" + // IPCNamespace for isolating System V IPC, POSIX message queues + ZOSIPCNamespace ZOSNamespaceType = "ipc" + // UTSNamespace for isolating hostname and NIS domain name + ZOSUTSNamespace ZOSNamespaceType = "uts" +) + +// LinuxSchedulerPolicy represents different scheduling policies used with the Linux Scheduler +type LinuxSchedulerPolicy string + +const ( + // SchedOther is the default scheduling policy + SchedOther LinuxSchedulerPolicy = "SCHED_OTHER" + // SchedFIFO is the First-In-First-Out scheduling policy + SchedFIFO LinuxSchedulerPolicy = "SCHED_FIFO" + // SchedRR is the Round-Robin scheduling policy + SchedRR LinuxSchedulerPolicy = "SCHED_RR" + // SchedBatch is the Batch scheduling policy + SchedBatch LinuxSchedulerPolicy = "SCHED_BATCH" + // SchedISO is the Isolation scheduling policy + SchedISO LinuxSchedulerPolicy = "SCHED_ISO" + // SchedIdle is the Idle scheduling policy + SchedIdle LinuxSchedulerPolicy = "SCHED_IDLE" + // SchedDeadline is the Deadline scheduling policy + SchedDeadline LinuxSchedulerPolicy = "SCHED_DEADLINE" +) + +// LinuxSchedulerFlag represents the flags used by the Linux Scheduler. +type LinuxSchedulerFlag string + +const ( + // SchedFlagResetOnFork represents the reset on fork scheduling flag + SchedFlagResetOnFork LinuxSchedulerFlag = "SCHED_FLAG_RESET_ON_FORK" + // SchedFlagReclaim represents the reclaim scheduling flag + SchedFlagReclaim LinuxSchedulerFlag = "SCHED_FLAG_RECLAIM" + // SchedFlagDLOverrun represents the deadline overrun scheduling flag + SchedFlagDLOverrun LinuxSchedulerFlag = "SCHED_FLAG_DL_OVERRUN" + // SchedFlagKeepPolicy represents the keep policy scheduling flag + SchedFlagKeepPolicy LinuxSchedulerFlag = "SCHED_FLAG_KEEP_POLICY" + // SchedFlagKeepParams represents the keep parameters scheduling flag + SchedFlagKeepParams LinuxSchedulerFlag = "SCHED_FLAG_KEEP_PARAMS" + // SchedFlagUtilClampMin represents the utilization clamp minimum scheduling flag + SchedFlagUtilClampMin LinuxSchedulerFlag = "SCHED_FLAG_UTIL_CLAMP_MIN" + // SchedFlagUtilClampMin represents the utilization clamp maximum scheduling flag + SchedFlagUtilClampMax LinuxSchedulerFlag = "SCHED_FLAG_UTIL_CLAMP_MAX" +) diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go new file mode 100644 index 00000000..7c010d4f --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/state.go @@ -0,0 +1,56 @@ +package specs + +// ContainerState represents the state of a container. +type ContainerState string + +const ( + // StateCreating indicates that the container is being created + StateCreating ContainerState = "creating" + + // StateCreated indicates that the runtime has finished the create operation + StateCreated ContainerState = "created" + + // StateRunning indicates that the container process has executed the + // user-specified program but has not exited + StateRunning ContainerState = "running" + + // StateStopped indicates that the container process has exited + StateStopped ContainerState = "stopped" +) + +// State holds information about the runtime state of the container. +type State struct { + // Version is the version of the specification that is supported. + Version string `json:"ociVersion"` + // ID is the container ID + ID string `json:"id"` + // Status is the runtime status of the container. + Status ContainerState `json:"status"` + // Pid is the process ID for the container process. + Pid int `json:"pid,omitempty"` + // Bundle is the path to the container's bundle directory. + Bundle string `json:"bundle"` + // Annotations are key values associated with the container. + Annotations map[string]string `json:"annotations,omitempty"` +} + +const ( + // SeccompFdName is the name of the seccomp notify file descriptor. + SeccompFdName string = "seccompFd" +) + +// ContainerProcessState holds information about the state of a container process. +type ContainerProcessState struct { + // Version is the version of the specification that is supported. + Version string `json:"ociVersion"` + // Fds is a string array containing the names of the file descriptors passed. + // The index of the name in this array corresponds to index of the file + // descriptor in the `SCM_RIGHTS` array. + Fds []string `json:"fds"` + // Pid is the process ID as seen by the runtime. + Pid int `json:"pid"` + // Opaque metadata. + Metadata string `json:"metadata,omitempty"` + // State of the container. + State State `json:"state"` +} diff --git a/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go new file mode 100644 index 00000000..23234a9c --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-spec/specs-go/version.go @@ -0,0 +1,18 @@ +package specs + +import "fmt" + +const ( + // VersionMajor is for an API incompatible changes + VersionMajor = 1 + // VersionMinor is for functionality in a backwards-compatible manner + VersionMinor = 2 + // VersionPatch is for backwards-compatible bug fixes + VersionPatch = 1 + + // VersionDev indicates development branch. Releases will be empty string. + VersionDev = "" +) + +// Version is the specification version that the package types support. +var Version = fmt.Sprintf("%d.%d.%d%s", VersionMajor, VersionMinor, VersionPatch, VersionDev) diff --git a/vendor/github.com/opencontainers/runtime-tools/LICENSE b/vendor/github.com/opencontainers/runtime-tools/LICENSE new file mode 100644 index 00000000..bdc40365 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2015 The Linux Foundation. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/config.go b/vendor/github.com/opencontainers/runtime-tools/generate/config.go new file mode 100644 index 00000000..48f281d2 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/config.go @@ -0,0 +1,194 @@ +package generate + +import ( + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +func (g *Generator) initConfig() { + if g.Config == nil { + g.Config = &rspec.Spec{} + } +} + +func (g *Generator) initConfigProcess() { + g.initConfig() + if g.Config.Process == nil { + g.Config.Process = &rspec.Process{} + } +} + +func (g *Generator) initConfigProcessConsoleSize() { + g.initConfigProcess() + if g.Config.Process.ConsoleSize == nil { + g.Config.Process.ConsoleSize = &rspec.Box{} + } +} + +func (g *Generator) initConfigProcessCapabilities() { + g.initConfigProcess() + if g.Config.Process.Capabilities == nil { + g.Config.Process.Capabilities = &rspec.LinuxCapabilities{} + } +} + +func (g *Generator) initConfigRoot() { + g.initConfig() + if g.Config.Root == nil { + g.Config.Root = &rspec.Root{} + } +} + +func (g *Generator) initConfigAnnotations() { + g.initConfig() + if g.Config.Annotations == nil { + g.Config.Annotations = make(map[string]string) + } +} + +func (g *Generator) initConfigHooks() { + g.initConfig() + if g.Config.Hooks == nil { + g.Config.Hooks = &rspec.Hooks{} + } +} + +func (g *Generator) initConfigLinux() { + g.initConfig() + if g.Config.Linux == nil { + g.Config.Linux = &rspec.Linux{} + } +} + +func (g *Generator) initConfigLinuxIntelRdt() { + g.initConfigLinux() + if g.Config.Linux.IntelRdt == nil { + g.Config.Linux.IntelRdt = &rspec.LinuxIntelRdt{} + } +} + +func (g *Generator) initConfigLinuxSysctl() { + g.initConfigLinux() + if g.Config.Linux.Sysctl == nil { + g.Config.Linux.Sysctl = make(map[string]string) + } +} + +func (g *Generator) initConfigLinuxSeccomp() { + g.initConfigLinux() + if g.Config.Linux.Seccomp == nil { + g.Config.Linux.Seccomp = &rspec.LinuxSeccomp{} + } +} + +func (g *Generator) initConfigLinuxResources() { + g.initConfigLinux() + if g.Config.Linux.Resources == nil { + g.Config.Linux.Resources = &rspec.LinuxResources{} + } +} + +func (g *Generator) initConfigLinuxResourcesBlockIO() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.BlockIO == nil { + g.Config.Linux.Resources.BlockIO = &rspec.LinuxBlockIO{} + } +} + +// InitConfigLinuxResourcesCPU initializes CPU of Linux resources +func (g *Generator) InitConfigLinuxResourcesCPU() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.CPU == nil { + g.Config.Linux.Resources.CPU = &rspec.LinuxCPU{} + } +} + +func (g *Generator) initConfigLinuxResourcesMemory() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.Memory == nil { + g.Config.Linux.Resources.Memory = &rspec.LinuxMemory{} + } +} + +func (g *Generator) initConfigLinuxResourcesNetwork() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.Network == nil { + g.Config.Linux.Resources.Network = &rspec.LinuxNetwork{} + } +} + +func (g *Generator) initConfigLinuxResourcesPids() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.Pids == nil { + g.Config.Linux.Resources.Pids = &rspec.LinuxPids{} + } +} + +func (g *Generator) initConfigLinuxResourcesUnified() { + g.initConfigLinuxResources() + if g.Config.Linux.Resources.Unified == nil { + g.Config.Linux.Resources.Unified = map[string]string{} + } +} + +func (g *Generator) initConfigSolaris() { + g.initConfig() + if g.Config.Solaris == nil { + g.Config.Solaris = &rspec.Solaris{} + } +} + +func (g *Generator) initConfigSolarisCappedCPU() { + g.initConfigSolaris() + if g.Config.Solaris.CappedCPU == nil { + g.Config.Solaris.CappedCPU = &rspec.SolarisCappedCPU{} + } +} + +func (g *Generator) initConfigSolarisCappedMemory() { + g.initConfigSolaris() + if g.Config.Solaris.CappedMemory == nil { + g.Config.Solaris.CappedMemory = &rspec.SolarisCappedMemory{} + } +} + +func (g *Generator) initConfigWindows() { + g.initConfig() + if g.Config.Windows == nil { + g.Config.Windows = &rspec.Windows{} + } +} + +func (g *Generator) initConfigWindowsNetwork() { + g.initConfigWindows() + if g.Config.Windows.Network == nil { + g.Config.Windows.Network = &rspec.WindowsNetwork{} + } +} + +func (g *Generator) initConfigWindowsHyperV() { + g.initConfigWindows() + if g.Config.Windows.HyperV == nil { + g.Config.Windows.HyperV = &rspec.WindowsHyperV{} + } +} + +func (g *Generator) initConfigWindowsResources() { + g.initConfigWindows() + if g.Config.Windows.Resources == nil { + g.Config.Windows.Resources = &rspec.WindowsResources{} + } +} + +func (g *Generator) initConfigWindowsResourcesMemory() { + g.initConfigWindowsResources() + if g.Config.Windows.Resources.Memory == nil { + g.Config.Windows.Resources.Memory = &rspec.WindowsMemoryResources{} + } +} + +func (g *Generator) initConfigVM() { + g.initConfig() + if g.Config.VM == nil { + g.Config.VM = &rspec.VM{} + } +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/generate.go b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go new file mode 100644 index 00000000..4d66b320 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/generate.go @@ -0,0 +1,1874 @@ +// Package generate implements functions generating container config files. +package generate + +import ( + "encoding/json" + "fmt" + "io" + "os" + "strings" + + rspec "github.com/opencontainers/runtime-spec/specs-go" + "github.com/opencontainers/runtime-tools/generate/seccomp" + capsCheck "github.com/opencontainers/runtime-tools/validate/capabilities" + "github.com/syndtr/gocapability/capability" +) + +var ( + // Namespaces include the names of supported namespaces. + Namespaces = []string{"network", "pid", "mount", "ipc", "uts", "user", "cgroup"} + + // we don't care about order...and this is way faster... + removeFunc = func(s []string, i int) []string { + s[i] = s[len(s)-1] + return s[:len(s)-1] + } +) + +// Generator represents a generator for a container config. +type Generator struct { + Config *rspec.Spec + HostSpecific bool + // This is used to keep a cache of the ENVs added to improve + // performance when adding a huge number of ENV variables + envMap map[string]int +} + +// ExportOptions have toggles for exporting only certain parts of the specification +type ExportOptions struct { + Seccomp bool // seccomp toggles if only seccomp should be exported +} + +// New creates a configuration Generator with the default +// configuration for the target operating system. +func New(os string) (generator Generator, err error) { + if os != "linux" && os != "solaris" && os != "windows" && os != "freebsd" { + return generator, fmt.Errorf("no defaults configured for %s", os) + } + + config := rspec.Spec{ + Version: rspec.Version, + Hostname: "mrsdalloway", + } + + if os == "windows" { + config.Process = &rspec.Process{ + Args: []string{ + "cmd", + }, + Cwd: `C:\`, + } + config.Windows = &rspec.Windows{} + } else { + config.Root = &rspec.Root{ + Path: "rootfs", + Readonly: false, + } + config.Process = &rspec.Process{ + Terminal: false, + Args: []string{ + "sh", + }, + } + } + + if os == "linux" || os == "solaris" || os == "freebsd" { + config.Process.User = rspec.User{} + config.Process.Env = []string{ + "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "TERM=xterm", + } + config.Process.Cwd = "/" + config.Process.Rlimits = []rspec.POSIXRlimit{ + { + Type: "RLIMIT_NOFILE", + Hard: uint64(1024), + Soft: uint64(1024), + }, + } + } + + if os == "linux" { + config.Process.Capabilities = &rspec.LinuxCapabilities{ + Bounding: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Permitted: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Inheritable: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Effective: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + Ambient: []string{ + "CAP_CHOWN", + "CAP_DAC_OVERRIDE", + "CAP_FSETID", + "CAP_FOWNER", + "CAP_MKNOD", + "CAP_NET_RAW", + "CAP_SETGID", + "CAP_SETUID", + "CAP_SETFCAP", + "CAP_SETPCAP", + "CAP_NET_BIND_SERVICE", + "CAP_SYS_CHROOT", + "CAP_KILL", + "CAP_AUDIT_WRITE", + }, + } + config.Mounts = []rspec.Mount{ + { + Destination: "/proc", + Type: "proc", + Source: "proc", + Options: []string{"nosuid", "noexec", "nodev"}, + }, + { + Destination: "/dev", + Type: "tmpfs", + Source: "tmpfs", + Options: []string{"nosuid", "noexec", "strictatime", "mode=755", "size=65536k"}, + }, + { + Destination: "/dev/pts", + Type: "devpts", + Source: "devpts", + Options: []string{"nosuid", "noexec", "newinstance", "ptmxmode=0666", "mode=0620", "gid=5"}, + }, + { + Destination: "/dev/shm", + Type: "tmpfs", + Source: "shm", + Options: []string{"nosuid", "noexec", "nodev", "mode=1777", "size=65536k"}, + }, + { + Destination: "/dev/mqueue", + Type: "mqueue", + Source: "mqueue", + Options: []string{"nosuid", "noexec", "nodev"}, + }, + { + Destination: "/sys", + Type: "sysfs", + Source: "sysfs", + Options: []string{"nosuid", "noexec", "nodev", "ro"}, + }, + } + config.Linux = &rspec.Linux{ + Resources: &rspec.LinuxResources{ + Devices: []rspec.LinuxDeviceCgroup{ + { + Allow: false, + Access: "rwm", + }, + }, + }, + Namespaces: []rspec.LinuxNamespace{ + { + Type: "pid", + }, + { + Type: "network", + }, + { + Type: "ipc", + }, + { + Type: "uts", + }, + { + Type: "mount", + }, + }, + Seccomp: seccomp.DefaultProfile(&config), + } + } else if os == "freebsd" { + config.Mounts = []rspec.Mount{ + { + Destination: "/dev", + Type: "devfs", + Source: "devfs", + Options: []string{"ruleset=4"}, + }, + { + Destination: "/dev/fd", + Type: "fdescfs", + Source: "fdesc", + Options: []string{}, + }, + } + } + + envCache := map[string]int{} + if config.Process != nil { + envCache = createEnvCacheMap(config.Process.Env) + } + + return Generator{Config: &config, envMap: envCache}, nil +} + +// NewFromSpec creates a configuration Generator from a given +// configuration. +func NewFromSpec(config *rspec.Spec) Generator { + envCache := map[string]int{} + if config != nil && config.Process != nil { + envCache = createEnvCacheMap(config.Process.Env) + } + + return Generator{ + Config: config, + envMap: envCache, + } +} + +// NewFromFile loads the template specified in a file into a +// configuration Generator. +func NewFromFile(path string) (Generator, error) { + cf, err := os.Open(path) + if err != nil { + if os.IsNotExist(err) { + return Generator{}, fmt.Errorf("template configuration at %s not found", path) + } + return Generator{}, err + } + defer cf.Close() + + return NewFromTemplate(cf) +} + +// NewFromTemplate loads the template from io.Reader into a +// configuration Generator. +func NewFromTemplate(r io.Reader) (Generator, error) { + var config rspec.Spec + if err := json.NewDecoder(r).Decode(&config); err != nil { + return Generator{}, err + } + + envCache := map[string]int{} + if config.Process != nil { + envCache = createEnvCacheMap(config.Process.Env) + } + + return Generator{ + Config: &config, + envMap: envCache, + }, nil +} + +// createEnvCacheMap creates a hash map with the ENV variables given by the config +func createEnvCacheMap(env []string) map[string]int { + envMap := make(map[string]int, len(env)) + for i, val := range env { + envMap[val] = i + } + return envMap +} + +// SetSpec sets the configuration in the Generator g. +// +// Deprecated: Replace with: +// +// Use generator.Config = config +func (g *Generator) SetSpec(config *rspec.Spec) { + g.Config = config +} + +// Spec gets the configuration from the Generator g. +// +// Deprecated: Replace with generator.Config. +func (g *Generator) Spec() *rspec.Spec { + return g.Config +} + +// Save writes the configuration into w. +func (g *Generator) Save(w io.Writer, exportOpts ExportOptions) (err error) { + var data []byte + + if g.Config.Linux != nil { + buf, err := json.Marshal(g.Config.Linux) + if err != nil { + return err + } + if string(buf) == "{}" { + g.Config.Linux = nil + } + } + + if exportOpts.Seccomp { + data, err = json.MarshalIndent(g.Config.Linux.Seccomp, "", "\t") + } else { + data, err = json.MarshalIndent(g.Config, "", "\t") + } + if err != nil { + return err + } + + _, err = w.Write(data) + if err != nil { + return err + } + + return nil +} + +// SaveToFile writes the configuration into a file. +func (g *Generator) SaveToFile(path string, exportOpts ExportOptions) error { + f, err := os.Create(path) + if err != nil { + return err + } + defer f.Close() + return g.Save(f, exportOpts) +} + +// SetVersion sets g.Config.Version. +func (g *Generator) SetVersion(version string) { + g.initConfig() + g.Config.Version = version +} + +// SetRootPath sets g.Config.Root.Path. +func (g *Generator) SetRootPath(path string) { + g.initConfigRoot() + g.Config.Root.Path = path +} + +// SetRootReadonly sets g.Config.Root.Readonly. +func (g *Generator) SetRootReadonly(b bool) { + g.initConfigRoot() + g.Config.Root.Readonly = b +} + +// SetHostname sets g.Config.Hostname. +func (g *Generator) SetHostname(s string) { + g.initConfig() + g.Config.Hostname = s +} + +// SetOCIVersion sets g.Config.Version. +func (g *Generator) SetOCIVersion(s string) { + g.initConfig() + g.Config.Version = s +} + +// ClearAnnotations clears g.Config.Annotations. +func (g *Generator) ClearAnnotations() { + if g.Config == nil { + return + } + g.Config.Annotations = make(map[string]string) +} + +// AddAnnotation adds an annotation into g.Config.Annotations. +func (g *Generator) AddAnnotation(key, value string) { + g.initConfigAnnotations() + g.Config.Annotations[key] = value +} + +// RemoveAnnotation remove an annotation from g.Config.Annotations. +func (g *Generator) RemoveAnnotation(key string) { + if g.Config == nil || g.Config.Annotations == nil { + return + } + delete(g.Config.Annotations, key) +} + +// RemoveHostname removes g.Config.Hostname, setting it to an empty string. +func (g *Generator) RemoveHostname() { + if g.Config == nil { + return + } + g.Config.Hostname = "" +} + +// SetProcessConsoleSize sets g.Config.Process.ConsoleSize. +func (g *Generator) SetProcessConsoleSize(width, height uint) { + g.initConfigProcessConsoleSize() + g.Config.Process.ConsoleSize.Width = width + g.Config.Process.ConsoleSize.Height = height +} + +// SetProcessUID sets g.Config.Process.User.UID. +func (g *Generator) SetProcessUID(uid uint32) { + g.initConfigProcess() + g.Config.Process.User.UID = uid +} + +// SetProcessUsername sets g.Config.Process.User.Username. +func (g *Generator) SetProcessUsername(username string) { + g.initConfigProcess() + g.Config.Process.User.Username = username +} + +// SetProcessUmask sets g.Config.Process.User.Umask. +func (g *Generator) SetProcessUmask(umask uint32) { + g.initConfigProcess() + u := umask + g.Config.Process.User.Umask = &u +} + +// SetProcessGID sets g.Config.Process.User.GID. +func (g *Generator) SetProcessGID(gid uint32) { + g.initConfigProcess() + g.Config.Process.User.GID = gid +} + +// SetProcessCwd sets g.Config.Process.Cwd. +func (g *Generator) SetProcessCwd(cwd string) { + g.initConfigProcess() + g.Config.Process.Cwd = cwd +} + +// SetProcessNoNewPrivileges sets g.Config.Process.NoNewPrivileges. +func (g *Generator) SetProcessNoNewPrivileges(b bool) { + g.initConfigProcess() + g.Config.Process.NoNewPrivileges = b +} + +// SetProcessTerminal sets g.Config.Process.Terminal. +func (g *Generator) SetProcessTerminal(b bool) { + g.initConfigProcess() + g.Config.Process.Terminal = b +} + +// SetProcessApparmorProfile sets g.Config.Process.ApparmorProfile. +func (g *Generator) SetProcessApparmorProfile(prof string) { + g.initConfigProcess() + g.Config.Process.ApparmorProfile = prof +} + +// SetProcessArgs sets g.Config.Process.Args. +func (g *Generator) SetProcessArgs(args []string) { + g.initConfigProcess() + g.Config.Process.Args = args +} + +// ClearProcessEnv clears g.Config.Process.Env. +func (g *Generator) ClearProcessEnv() { + if g.Config == nil || g.Config.Process == nil { + return + } + g.Config.Process.Env = []string{} + // Clear out the env cache map as well + g.envMap = map[string]int{} +} + +// AddProcessEnv adds name=value into g.Config.Process.Env, or replaces an +// existing entry with the given name. +func (g *Generator) AddProcessEnv(name, value string) { + if name == "" { + return + } + + g.initConfigProcess() + g.addEnv(fmt.Sprintf("%s=%s", name, value), name) +} + +// AddMultipleProcessEnv adds multiple name=value into g.Config.Process.Env, or replaces +// existing entries with the given name. +func (g *Generator) AddMultipleProcessEnv(envs []string) { + g.initConfigProcess() + + for _, val := range envs { + split := strings.SplitN(val, "=", 2) + g.addEnv(val, split[0]) + } +} + +// addEnv looks through adds ENV to the Process and checks envMap for +// any duplicates +// This is called by both AddMultipleProcessEnv and AddProcessEnv +func (g *Generator) addEnv(env, key string) { + if idx, ok := g.envMap[key]; ok { + // The ENV exists in the cache, so change its value in g.Config.Process.Env + g.Config.Process.Env[idx] = env + } else { + // else the env doesn't exist, so add it and add it's index to g.envMap + g.Config.Process.Env = append(g.Config.Process.Env, env) + g.envMap[key] = len(g.Config.Process.Env) - 1 + } +} + +// AddProcessRlimits adds rlimit into g.Config.Process.Rlimits. +func (g *Generator) AddProcessRlimits(rType string, rHard uint64, rSoft uint64) { + g.initConfigProcess() + for i, rlimit := range g.Config.Process.Rlimits { + if rlimit.Type == rType { + g.Config.Process.Rlimits[i].Hard = rHard + g.Config.Process.Rlimits[i].Soft = rSoft + return + } + } + + newRlimit := rspec.POSIXRlimit{ + Type: rType, + Hard: rHard, + Soft: rSoft, + } + g.Config.Process.Rlimits = append(g.Config.Process.Rlimits, newRlimit) +} + +// RemoveProcessRlimits removes a rlimit from g.Config.Process.Rlimits. +func (g *Generator) RemoveProcessRlimits(rType string) { + if g.Config == nil || g.Config.Process == nil { + return + } + for i, rlimit := range g.Config.Process.Rlimits { + if rlimit.Type == rType { + g.Config.Process.Rlimits = append(g.Config.Process.Rlimits[:i], g.Config.Process.Rlimits[i+1:]...) + return + } + } +} + +// ClearProcessRlimits clear g.Config.Process.Rlimits. +func (g *Generator) ClearProcessRlimits() { + if g.Config == nil || g.Config.Process == nil { + return + } + g.Config.Process.Rlimits = []rspec.POSIXRlimit{} +} + +// ClearProcessAdditionalGids clear g.Config.Process.AdditionalGids. +func (g *Generator) ClearProcessAdditionalGids() { + if g.Config == nil || g.Config.Process == nil { + return + } + g.Config.Process.User.AdditionalGids = []uint32{} +} + +// AddProcessAdditionalGid adds an additional gid into g.Config.Process.AdditionalGids. +func (g *Generator) AddProcessAdditionalGid(gid uint32) { + g.initConfigProcess() + for _, group := range g.Config.Process.User.AdditionalGids { + if group == gid { + return + } + } + g.Config.Process.User.AdditionalGids = append(g.Config.Process.User.AdditionalGids, gid) +} + +// SetProcessSelinuxLabel sets g.Config.Process.SelinuxLabel. +func (g *Generator) SetProcessSelinuxLabel(label string) { + g.initConfigProcess() + g.Config.Process.SelinuxLabel = label +} + +// SetLinuxCgroupsPath sets g.Config.Linux.CgroupsPath. +func (g *Generator) SetLinuxCgroupsPath(path string) { + g.initConfigLinux() + g.Config.Linux.CgroupsPath = path +} + +// SetLinuxIntelRdtClosID sets g.Config.Linux.IntelRdt.ClosID +func (g *Generator) SetLinuxIntelRdtClosID(clos string) { + g.initConfigLinuxIntelRdt() + g.Config.Linux.IntelRdt.ClosID = clos +} + +// SetLinuxIntelRdtL3CacheSchema sets g.Config.Linux.IntelRdt.L3CacheSchema +func (g *Generator) SetLinuxIntelRdtL3CacheSchema(schema string) { + g.initConfigLinuxIntelRdt() + g.Config.Linux.IntelRdt.L3CacheSchema = schema +} + +// SetLinuxMountLabel sets g.Config.Linux.MountLabel. +func (g *Generator) SetLinuxMountLabel(label string) { + g.initConfigLinux() + g.Config.Linux.MountLabel = label +} + +// SetProcessOOMScoreAdj sets g.Config.Process.OOMScoreAdj. +func (g *Generator) SetProcessOOMScoreAdj(adj int) { + g.initConfigProcess() + g.Config.Process.OOMScoreAdj = &adj +} + +// SetLinuxResourcesBlockIOLeafWeight sets g.Config.Linux.Resources.BlockIO.LeafWeight. +func (g *Generator) SetLinuxResourcesBlockIOLeafWeight(weight uint16) { + g.initConfigLinuxResourcesBlockIO() + g.Config.Linux.Resources.BlockIO.LeafWeight = &weight +} + +// AddLinuxResourcesBlockIOLeafWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight. +func (g *Generator) AddLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64, weight uint16) { + g.initConfigLinuxResourcesBlockIO() + for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { + if weightDevice.Major == major && weightDevice.Minor == minor { + g.Config.Linux.Resources.BlockIO.WeightDevice[i].LeafWeight = &weight + return + } + } + weightDevice := new(rspec.LinuxWeightDevice) + weightDevice.Major = major + weightDevice.Minor = minor + weightDevice.LeafWeight = &weight + g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice) +} + +// DropLinuxResourcesBlockIOLeafWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.LeafWeight +func (g *Generator) DropLinuxResourcesBlockIOLeafWeightDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { + if weightDevice.Major == major && weightDevice.Minor == minor { + if weightDevice.Weight != nil { + newWeightDevice := new(rspec.LinuxWeightDevice) + newWeightDevice.Major = major + newWeightDevice.Minor = minor + newWeightDevice.Weight = weightDevice.Weight + g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice + } else { + g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...) + } + return + } + } +} + +// SetLinuxResourcesBlockIOWeight sets g.Config.Linux.Resources.BlockIO.Weight. +func (g *Generator) SetLinuxResourcesBlockIOWeight(weight uint16) { + g.initConfigLinuxResourcesBlockIO() + g.Config.Linux.Resources.BlockIO.Weight = &weight +} + +// AddLinuxResourcesBlockIOWeightDevice adds or sets g.Config.Linux.Resources.BlockIO.WeightDevice.Weight. +func (g *Generator) AddLinuxResourcesBlockIOWeightDevice(major int64, minor int64, weight uint16) { + g.initConfigLinuxResourcesBlockIO() + for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { + if weightDevice.Major == major && weightDevice.Minor == minor { + g.Config.Linux.Resources.BlockIO.WeightDevice[i].Weight = &weight + return + } + } + weightDevice := new(rspec.LinuxWeightDevice) + weightDevice.Major = major + weightDevice.Minor = minor + weightDevice.Weight = &weight + g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice, *weightDevice) +} + +// DropLinuxResourcesBlockIOWeightDevice drops a item form g.Config.Linux.Resources.BlockIO.WeightDevice.Weight +func (g *Generator) DropLinuxResourcesBlockIOWeightDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + for i, weightDevice := range g.Config.Linux.Resources.BlockIO.WeightDevice { + if weightDevice.Major == major && weightDevice.Minor == minor { + if weightDevice.LeafWeight != nil { + newWeightDevice := new(rspec.LinuxWeightDevice) + newWeightDevice.Major = major + newWeightDevice.Minor = minor + newWeightDevice.LeafWeight = weightDevice.LeafWeight + g.Config.Linux.Resources.BlockIO.WeightDevice[i] = *newWeightDevice + } else { + g.Config.Linux.Resources.BlockIO.WeightDevice = append(g.Config.Linux.Resources.BlockIO.WeightDevice[:i], g.Config.Linux.Resources.BlockIO.WeightDevice[i+1:]...) + } + return + } + } +} + +// AddLinuxResourcesBlockIOThrottleReadBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice. +func (g *Generator) AddLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64, rate uint64) { + g.initConfigLinuxResourcesBlockIO() + throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor, rate) + g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices +} + +// DropLinuxResourcesBlockIOThrottleReadBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice. +func (g *Generator) DropLinuxResourcesBlockIOThrottleReadBpsDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice, major, minor) + g.Config.Linux.Resources.BlockIO.ThrottleReadBpsDevice = throttleDevices +} + +// AddLinuxResourcesBlockIOThrottleReadIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice. +func (g *Generator) AddLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64, rate uint64) { + g.initConfigLinuxResourcesBlockIO() + throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor, rate) + g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices +} + +// DropLinuxResourcesBlockIOThrottleReadIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice. +func (g *Generator) DropLinuxResourcesBlockIOThrottleReadIOPSDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice, major, minor) + g.Config.Linux.Resources.BlockIO.ThrottleReadIOPSDevice = throttleDevices +} + +// AddLinuxResourcesBlockIOThrottleWriteBpsDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice. +func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64, rate uint64) { + g.initConfigLinuxResourcesBlockIO() + throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor, rate) + g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices +} + +// DropLinuxResourcesBlockIOThrottleWriteBpsDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice. +func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteBpsDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice, major, minor) + g.Config.Linux.Resources.BlockIO.ThrottleWriteBpsDevice = throttleDevices +} + +// AddLinuxResourcesBlockIOThrottleWriteIOPSDevice adds or sets g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice. +func (g *Generator) AddLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64, rate uint64) { + g.initConfigLinuxResourcesBlockIO() + throttleDevices := addOrReplaceBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor, rate) + g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices +} + +// DropLinuxResourcesBlockIOThrottleWriteIOPSDevice drops a item from g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice. +func (g *Generator) DropLinuxResourcesBlockIOThrottleWriteIOPSDevice(major int64, minor int64) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.BlockIO == nil { + return + } + + throttleDevices := dropBlockIOThrottleDevice(g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice, major, minor) + g.Config.Linux.Resources.BlockIO.ThrottleWriteIOPSDevice = throttleDevices +} + +// SetLinuxResourcesCPUShares sets g.Config.Linux.Resources.CPU.Shares. +func (g *Generator) SetLinuxResourcesCPUShares(shares uint64) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.Shares = &shares +} + +// SetLinuxResourcesCPUQuota sets g.Config.Linux.Resources.CPU.Quota. +func (g *Generator) SetLinuxResourcesCPUQuota(quota int64) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.Quota = "a +} + +// SetLinuxResourcesCPUPeriod sets g.Config.Linux.Resources.CPU.Period. +func (g *Generator) SetLinuxResourcesCPUPeriod(period uint64) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.Period = &period +} + +// SetLinuxResourcesCPURealtimeRuntime sets g.Config.Linux.Resources.CPU.RealtimeRuntime. +func (g *Generator) SetLinuxResourcesCPURealtimeRuntime(time int64) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.RealtimeRuntime = &time +} + +// SetLinuxResourcesCPURealtimePeriod sets g.Config.Linux.Resources.CPU.RealtimePeriod. +func (g *Generator) SetLinuxResourcesCPURealtimePeriod(period uint64) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.RealtimePeriod = &period +} + +// SetLinuxResourcesCPUCpus sets g.Config.Linux.Resources.CPU.Cpus. +func (g *Generator) SetLinuxResourcesCPUCpus(cpus string) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.Cpus = cpus +} + +// SetLinuxResourcesCPUMems sets g.Config.Linux.Resources.CPU.Mems. +func (g *Generator) SetLinuxResourcesCPUMems(mems string) { + g.InitConfigLinuxResourcesCPU() + g.Config.Linux.Resources.CPU.Mems = mems +} + +// AddLinuxResourcesHugepageLimit adds or sets g.Config.Linux.Resources.HugepageLimits. +func (g *Generator) AddLinuxResourcesHugepageLimit(pageSize string, limit uint64) { + hugepageLimit := rspec.LinuxHugepageLimit{ + Pagesize: pageSize, + Limit: limit, + } + + g.initConfigLinuxResources() + for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits { + if pageLimit.Pagesize == pageSize { + g.Config.Linux.Resources.HugepageLimits[i].Limit = limit + return + } + } + g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits, hugepageLimit) +} + +// DropLinuxResourcesHugepageLimit drops a hugepage limit from g.Config.Linux.Resources.HugepageLimits. +func (g *Generator) DropLinuxResourcesHugepageLimit(pageSize string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil { + return + } + + for i, pageLimit := range g.Config.Linux.Resources.HugepageLimits { + if pageLimit.Pagesize == pageSize { + g.Config.Linux.Resources.HugepageLimits = append(g.Config.Linux.Resources.HugepageLimits[:i], g.Config.Linux.Resources.HugepageLimits[i+1:]...) + return + } + } +} + +// AddLinuxResourcesUnified sets the g.Config.Linux.Resources.Unified +func (g *Generator) SetLinuxResourcesUnified(unified map[string]string) { + g.initConfigLinuxResourcesUnified() + for k, v := range unified { + g.Config.Linux.Resources.Unified[k] = v + } +} + +// AddLinuxResourcesUnified adds or updates the key-value pair from g.Config.Linux.Resources.Unified +func (g *Generator) AddLinuxResourcesUnified(key, val string) { + g.initConfigLinuxResourcesUnified() + g.Config.Linux.Resources.Unified[key] = val +} + +// DropLinuxResourcesUnified drops a key-value pair from g.Config.Linux.Resources.Unified +func (g *Generator) DropLinuxResourcesUnified(key string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.Unified == nil { + return + } + delete(g.Config.Linux.Resources.Unified, key) +} + +// SetLinuxResourcesMemoryLimit sets g.Config.Linux.Resources.Memory.Limit. +func (g *Generator) SetLinuxResourcesMemoryLimit(limit int64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.Limit = &limit +} + +// SetLinuxResourcesMemoryReservation sets g.Config.Linux.Resources.Memory.Reservation. +func (g *Generator) SetLinuxResourcesMemoryReservation(reservation int64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.Reservation = &reservation +} + +// SetLinuxResourcesMemorySwap sets g.Config.Linux.Resources.Memory.Swap. +func (g *Generator) SetLinuxResourcesMemorySwap(swap int64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.Swap = &swap +} + +// SetLinuxResourcesMemoryKernel sets g.Config.Linux.Resources.Memory.Kernel. +func (g *Generator) SetLinuxResourcesMemoryKernel(kernel int64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.Kernel = &kernel +} + +// SetLinuxResourcesMemoryKernelTCP sets g.Config.Linux.Resources.Memory.KernelTCP. +func (g *Generator) SetLinuxResourcesMemoryKernelTCP(kernelTCP int64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.KernelTCP = &kernelTCP +} + +// SetLinuxResourcesMemorySwappiness sets g.Config.Linux.Resources.Memory.Swappiness. +func (g *Generator) SetLinuxResourcesMemorySwappiness(swappiness uint64) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.Swappiness = &swappiness +} + +// SetLinuxResourcesMemoryDisableOOMKiller sets g.Config.Linux.Resources.Memory.DisableOOMKiller. +func (g *Generator) SetLinuxResourcesMemoryDisableOOMKiller(disable bool) { + g.initConfigLinuxResourcesMemory() + g.Config.Linux.Resources.Memory.DisableOOMKiller = &disable +} + +// SetLinuxResourcesNetworkClassID sets g.Config.Linux.Resources.Network.ClassID. +func (g *Generator) SetLinuxResourcesNetworkClassID(classid uint32) { + g.initConfigLinuxResourcesNetwork() + g.Config.Linux.Resources.Network.ClassID = &classid +} + +// AddLinuxResourcesNetworkPriorities adds or sets g.Config.Linux.Resources.Network.Priorities. +func (g *Generator) AddLinuxResourcesNetworkPriorities(name string, prio uint32) { + g.initConfigLinuxResourcesNetwork() + for i, netPriority := range g.Config.Linux.Resources.Network.Priorities { + if netPriority.Name == name { + g.Config.Linux.Resources.Network.Priorities[i].Priority = prio + return + } + } + interfacePrio := new(rspec.LinuxInterfacePriority) + interfacePrio.Name = name + interfacePrio.Priority = prio + g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities, *interfacePrio) +} + +// DropLinuxResourcesNetworkPriorities drops one item from g.Config.Linux.Resources.Network.Priorities. +func (g *Generator) DropLinuxResourcesNetworkPriorities(name string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil || g.Config.Linux.Resources.Network == nil { + return + } + + for i, netPriority := range g.Config.Linux.Resources.Network.Priorities { + if netPriority.Name == name { + g.Config.Linux.Resources.Network.Priorities = append(g.Config.Linux.Resources.Network.Priorities[:i], g.Config.Linux.Resources.Network.Priorities[i+1:]...) + return + } + } +} + +// SetLinuxResourcesPidsLimit sets g.Config.Linux.Resources.Pids.Limit. +func (g *Generator) SetLinuxResourcesPidsLimit(limit int64) { + g.initConfigLinuxResourcesPids() + g.Config.Linux.Resources.Pids.Limit = limit +} + +// ClearLinuxSysctl clears g.Config.Linux.Sysctl. +func (g *Generator) ClearLinuxSysctl() { + if g.Config == nil || g.Config.Linux == nil { + return + } + g.Config.Linux.Sysctl = make(map[string]string) +} + +// AddLinuxSysctl adds a new sysctl config into g.Config.Linux.Sysctl. +func (g *Generator) AddLinuxSysctl(key, value string) { + g.initConfigLinuxSysctl() + g.Config.Linux.Sysctl[key] = value +} + +// RemoveLinuxSysctl removes a sysctl config from g.Config.Linux.Sysctl. +func (g *Generator) RemoveLinuxSysctl(key string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Sysctl == nil { + return + } + delete(g.Config.Linux.Sysctl, key) +} + +// ClearLinuxUIDMappings clear g.Config.Linux.UIDMappings. +func (g *Generator) ClearLinuxUIDMappings() { + if g.Config == nil || g.Config.Linux == nil { + return + } + g.Config.Linux.UIDMappings = []rspec.LinuxIDMapping{} +} + +// AddLinuxUIDMapping adds uidMap into g.Config.Linux.UIDMappings. +func (g *Generator) AddLinuxUIDMapping(hid, cid, size uint32) { + idMapping := rspec.LinuxIDMapping{ + HostID: hid, + ContainerID: cid, + Size: size, + } + + g.initConfigLinux() + g.Config.Linux.UIDMappings = append(g.Config.Linux.UIDMappings, idMapping) +} + +// ClearLinuxGIDMappings clear g.Config.Linux.GIDMappings. +func (g *Generator) ClearLinuxGIDMappings() { + if g.Config == nil || g.Config.Linux == nil { + return + } + g.Config.Linux.GIDMappings = []rspec.LinuxIDMapping{} +} + +// AddLinuxGIDMapping adds gidMap into g.Config.Linux.GIDMappings. +func (g *Generator) AddLinuxGIDMapping(hid, cid, size uint32) { + idMapping := rspec.LinuxIDMapping{ + HostID: hid, + ContainerID: cid, + Size: size, + } + + g.initConfigLinux() + g.Config.Linux.GIDMappings = append(g.Config.Linux.GIDMappings, idMapping) +} + +// SetLinuxRootPropagation sets g.Config.Linux.RootfsPropagation. +func (g *Generator) SetLinuxRootPropagation(rp string) error { + switch rp { + case "": + case "private": + case "rprivate": + case "slave": + case "rslave": + case "shared": + case "rshared": + case "unbindable": + case "runbindable": + default: + return fmt.Errorf("rootfs-propagation %q must be empty or one of (r)private|(r)slave|(r)shared|(r)unbindable", rp) + } + g.initConfigLinux() + g.Config.Linux.RootfsPropagation = rp + return nil +} + +// ClearPreStartHooks clear g.Config.Hooks.Prestart. +func (g *Generator) ClearPreStartHooks() { + if g.Config == nil || g.Config.Hooks == nil { + return + } + g.Config.Hooks.Prestart = []rspec.Hook{} +} + +// AddPreStartHook add a prestart hook into g.Config.Hooks.Prestart. +func (g *Generator) AddPreStartHook(preStartHook rspec.Hook) { + g.initConfigHooks() + g.Config.Hooks.Prestart = append(g.Config.Hooks.Prestart, preStartHook) +} + +// ClearPostStopHooks clear g.Config.Hooks.Poststop. +func (g *Generator) ClearPostStopHooks() { + if g.Config == nil || g.Config.Hooks == nil { + return + } + g.Config.Hooks.Poststop = []rspec.Hook{} +} + +// AddPostStopHook adds a poststop hook into g.Config.Hooks.Poststop. +func (g *Generator) AddPostStopHook(postStopHook rspec.Hook) { + g.initConfigHooks() + g.Config.Hooks.Poststop = append(g.Config.Hooks.Poststop, postStopHook) +} + +// ClearPostStartHooks clear g.Config.Hooks.Poststart. +func (g *Generator) ClearPostStartHooks() { + if g.Config == nil || g.Config.Hooks == nil { + return + } + g.Config.Hooks.Poststart = []rspec.Hook{} +} + +// AddPostStartHook adds a poststart hook into g.Config.Hooks.Poststart. +func (g *Generator) AddPostStartHook(postStartHook rspec.Hook) { + g.initConfigHooks() + g.Config.Hooks.Poststart = append(g.Config.Hooks.Poststart, postStartHook) +} + +// AddMount adds a mount into g.Config.Mounts. +func (g *Generator) AddMount(mnt rspec.Mount) { + g.initConfig() + + g.Config.Mounts = append(g.Config.Mounts, mnt) +} + +// RemoveMount removes a mount point on the dest directory +func (g *Generator) RemoveMount(dest string) { + g.initConfig() + + for index, mount := range g.Config.Mounts { + if mount.Destination == dest { + g.Config.Mounts = append(g.Config.Mounts[:index], g.Config.Mounts[index+1:]...) + return + } + } +} + +// Mounts returns the list of mounts +func (g *Generator) Mounts() []rspec.Mount { + g.initConfig() + + return g.Config.Mounts +} + +// ClearMounts clear g.Config.Mounts +func (g *Generator) ClearMounts() { + if g.Config == nil { + return + } + g.Config.Mounts = []rspec.Mount{} +} + +// SetupPrivileged sets up the privilege-related fields inside g.Config. +func (g *Generator) SetupPrivileged(privileged bool) { + if privileged { // Add all capabilities in privileged mode. + var finalCapList []string + for _, cap := range capability.List() { + if g.HostSpecific && cap > capsCheck.LastCap() { + continue + } + finalCapList = append(finalCapList, fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String()))) + } + g.initConfigLinux() + g.initConfigProcessCapabilities() + g.ClearProcessCapabilities() + g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, finalCapList...) + g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, finalCapList...) + g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, finalCapList...) + g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, finalCapList...) + g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, finalCapList...) + g.Config.Process.SelinuxLabel = "" + g.Config.Process.ApparmorProfile = "" + g.Config.Linux.Seccomp = nil + } +} + +// ClearProcessCapabilities clear g.Config.Process.Capabilities. +func (g *Generator) ClearProcessCapabilities() { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return + } + g.Config.Process.Capabilities.Bounding = []string{} + g.Config.Process.Capabilities.Effective = []string{} + g.Config.Process.Capabilities.Inheritable = []string{} + g.Config.Process.Capabilities.Permitted = []string{} + g.Config.Process.Capabilities.Ambient = []string{} +} + +// AddProcessCapability adds a process capability into all 5 capability sets. +func (g *Generator) AddProcessCapability(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundAmbient, foundBounding, foundEffective, foundInheritable, foundPermitted bool + for _, cap := range g.Config.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + foundAmbient = true + break + } + } + if !foundAmbient { + g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, cp) + } + + for _, cap := range g.Config.Process.Capabilities.Bounding { + if strings.ToUpper(cap) == cp { + foundBounding = true + break + } + } + if !foundBounding { + g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, cp) + } + + for _, cap := range g.Config.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + foundEffective = true + break + } + } + if !foundEffective { + g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, cp) + } + + for _, cap := range g.Config.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + foundInheritable = true + break + } + } + if !foundInheritable { + g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, cp) + } + + for _, cap := range g.Config.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + foundPermitted = true + break + } + } + if !foundPermitted { + g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, cp) + } + + return nil +} + +// AddProcessCapabilityAmbient adds a process capability into g.Config.Process.Capabilities.Ambient. +func (g *Generator) AddProcessCapabilityAmbient(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundAmbient bool + for _, cap := range g.Config.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + foundAmbient = true + break + } + } + + if !foundAmbient { + g.Config.Process.Capabilities.Ambient = append(g.Config.Process.Capabilities.Ambient, cp) + } + + return nil +} + +// AddProcessCapabilityBounding adds a process capability into g.Config.Process.Capabilities.Bounding. +func (g *Generator) AddProcessCapabilityBounding(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundBounding bool + for _, cap := range g.Config.Process.Capabilities.Bounding { + if strings.ToUpper(cap) == cp { + foundBounding = true + break + } + } + if !foundBounding { + g.Config.Process.Capabilities.Bounding = append(g.Config.Process.Capabilities.Bounding, cp) + } + + return nil +} + +// AddProcessCapabilityEffective adds a process capability into g.Config.Process.Capabilities.Effective. +func (g *Generator) AddProcessCapabilityEffective(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundEffective bool + for _, cap := range g.Config.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + foundEffective = true + break + } + } + if !foundEffective { + g.Config.Process.Capabilities.Effective = append(g.Config.Process.Capabilities.Effective, cp) + } + + return nil +} + +// AddProcessCapabilityInheritable adds a process capability into g.Config.Process.Capabilities.Inheritable. +func (g *Generator) AddProcessCapabilityInheritable(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundInheritable bool + for _, cap := range g.Config.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + foundInheritable = true + break + } + } + if !foundInheritable { + g.Config.Process.Capabilities.Inheritable = append(g.Config.Process.Capabilities.Inheritable, cp) + } + + return nil +} + +// AddProcessCapabilityPermitted adds a process capability into g.Config.Process.Capabilities.Permitted. +func (g *Generator) AddProcessCapabilityPermitted(c string) error { + cp := strings.ToUpper(c) + if err := capsCheck.CapValid(cp, g.HostSpecific); err != nil { + return err + } + + g.initConfigProcessCapabilities() + + var foundPermitted bool + for _, cap := range g.Config.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + foundPermitted = true + break + } + } + if !foundPermitted { + g.Config.Process.Capabilities.Permitted = append(g.Config.Process.Capabilities.Permitted, cp) + } + + return nil +} + +// DropProcessCapability drops a process capability from all 5 capability sets. +func (g *Generator) DropProcessCapability(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Ambient = removeFunc(g.Config.Process.Capabilities.Ambient, i) + } + } + for i, cap := range g.Config.Process.Capabilities.Bounding { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Bounding = removeFunc(g.Config.Process.Capabilities.Bounding, i) + } + } + for i, cap := range g.Config.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Effective = removeFunc(g.Config.Process.Capabilities.Effective, i) + } + } + for i, cap := range g.Config.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Inheritable = removeFunc(g.Config.Process.Capabilities.Inheritable, i) + } + } + for i, cap := range g.Config.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Permitted = removeFunc(g.Config.Process.Capabilities.Permitted, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +// DropProcessCapabilityAmbient drops a process capability from g.Config.Process.Capabilities.Ambient. +func (g *Generator) DropProcessCapabilityAmbient(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Ambient { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Ambient = removeFunc(g.Config.Process.Capabilities.Ambient, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +// DropProcessCapabilityBounding drops a process capability from g.Config.Process.Capabilities.Bounding. +func (g *Generator) DropProcessCapabilityBounding(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Bounding { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Bounding = removeFunc(g.Config.Process.Capabilities.Bounding, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +// DropProcessCapabilityEffective drops a process capability from g.Config.Process.Capabilities.Effective. +func (g *Generator) DropProcessCapabilityEffective(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Effective { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Effective = removeFunc(g.Config.Process.Capabilities.Effective, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +// DropProcessCapabilityInheritable drops a process capability from g.Config.Process.Capabilities.Inheritable. +func (g *Generator) DropProcessCapabilityInheritable(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Inheritable { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Inheritable = removeFunc(g.Config.Process.Capabilities.Inheritable, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +// DropProcessCapabilityPermitted drops a process capability from g.Config.Process.Capabilities.Permitted. +func (g *Generator) DropProcessCapabilityPermitted(c string) error { + if g.Config == nil || g.Config.Process == nil || g.Config.Process.Capabilities == nil { + return nil + } + + cp := strings.ToUpper(c) + for i, cap := range g.Config.Process.Capabilities.Permitted { + if strings.ToUpper(cap) == cp { + g.Config.Process.Capabilities.Permitted = removeFunc(g.Config.Process.Capabilities.Permitted, i) + } + } + + return capsCheck.CapValid(cp, false) +} + +func mapStrToNamespace(ns string, path string) (rspec.LinuxNamespace, error) { + switch ns { + case "network": + return rspec.LinuxNamespace{Type: rspec.NetworkNamespace, Path: path}, nil + case "pid": + return rspec.LinuxNamespace{Type: rspec.PIDNamespace, Path: path}, nil + case "mount": + return rspec.LinuxNamespace{Type: rspec.MountNamespace, Path: path}, nil + case "ipc": + return rspec.LinuxNamespace{Type: rspec.IPCNamespace, Path: path}, nil + case "uts": + return rspec.LinuxNamespace{Type: rspec.UTSNamespace, Path: path}, nil + case "user": + return rspec.LinuxNamespace{Type: rspec.UserNamespace, Path: path}, nil + case "cgroup": + return rspec.LinuxNamespace{Type: rspec.CgroupNamespace, Path: path}, nil + default: + return rspec.LinuxNamespace{}, fmt.Errorf("unrecognized namespace %q", ns) + } +} + +// ClearLinuxNamespaces clear g.Config.Linux.Namespaces. +func (g *Generator) ClearLinuxNamespaces() { + if g.Config == nil || g.Config.Linux == nil { + return + } + g.Config.Linux.Namespaces = []rspec.LinuxNamespace{} +} + +// AddOrReplaceLinuxNamespace adds or replaces a namespace inside +// g.Config.Linux.Namespaces. +func (g *Generator) AddOrReplaceLinuxNamespace(ns string, path string) error { + namespace, err := mapStrToNamespace(ns, path) + if err != nil { + return err + } + + g.initConfigLinux() + for i, ns := range g.Config.Linux.Namespaces { + if ns.Type == namespace.Type { + g.Config.Linux.Namespaces[i] = namespace + return nil + } + } + g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces, namespace) + return nil +} + +// RemoveLinuxNamespace removes a namespace from g.Config.Linux.Namespaces. +func (g *Generator) RemoveLinuxNamespace(ns string) error { + namespace, err := mapStrToNamespace(ns, "") + if err != nil { + return err + } + + if g.Config == nil || g.Config.Linux == nil { + return nil + } + for i, ns := range g.Config.Linux.Namespaces { + if ns.Type == namespace.Type { + g.Config.Linux.Namespaces = append(g.Config.Linux.Namespaces[:i], g.Config.Linux.Namespaces[i+1:]...) + return nil + } + } + return nil +} + +// AddDevice - add a device into g.Config.Linux.Devices +func (g *Generator) AddDevice(device rspec.LinuxDevice) { + g.initConfigLinux() + + for i, dev := range g.Config.Linux.Devices { + if dev.Path == device.Path { + g.Config.Linux.Devices[i] = device + return + } + } + + g.Config.Linux.Devices = append(g.Config.Linux.Devices, device) +} + +// RemoveDevice remove a device from g.Config.Linux.Devices +func (g *Generator) RemoveDevice(path string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil { + return + } + + for i, device := range g.Config.Linux.Devices { + if device.Path == path { + g.Config.Linux.Devices = append(g.Config.Linux.Devices[:i], g.Config.Linux.Devices[i+1:]...) + return + } + } +} + +// ClearLinuxDevices clears g.Config.Linux.Devices +func (g *Generator) ClearLinuxDevices() { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Devices == nil { + return + } + + g.Config.Linux.Devices = []rspec.LinuxDevice{} +} + +// AddLinuxResourcesDevice - add a device into g.Config.Linux.Resources.Devices +func (g *Generator) AddLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + g.initConfigLinuxResources() + + device := rspec.LinuxDeviceCgroup{ + Allow: allow, + Type: devType, + Access: access, + Major: major, + Minor: minor, + } + g.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices, device) +} + +// RemoveLinuxResourcesDevice - remove a device from g.Config.Linux.Resources.Devices +func (g *Generator) RemoveLinuxResourcesDevice(allow bool, devType string, major, minor *int64, access string) { + if g.Config == nil || g.Config.Linux == nil || g.Config.Linux.Resources == nil { + return + } + for i, device := range g.Config.Linux.Resources.Devices { + if device.Allow == allow && + (devType == device.Type || (devType != "" && device.Type != "" && devType == device.Type)) && + (access == device.Access || (access != "" && device.Access != "" && access == device.Access)) && + (major == device.Major || (major != nil && device.Major != nil && *major == *device.Major)) && + (minor == device.Minor || (minor != nil && device.Minor != nil && *minor == *device.Minor)) { + + g.Config.Linux.Resources.Devices = append(g.Config.Linux.Resources.Devices[:i], g.Config.Linux.Resources.Devices[i+1:]...) + return + } + } +} + +// SetSyscallAction adds rules for syscalls with the specified action +func (g *Generator) SetSyscallAction(arguments seccomp.SyscallOpts) error { + g.initConfigLinuxSeccomp() + return seccomp.ParseSyscallFlag(arguments, g.Config.Linux.Seccomp) +} + +// SetDefaultSeccompAction sets the default action for all syscalls not defined +// and then removes any syscall rules with this action already specified. +func (g *Generator) SetDefaultSeccompAction(action string) error { + g.initConfigLinuxSeccomp() + return seccomp.ParseDefaultAction(action, g.Config.Linux.Seccomp) +} + +// SetDefaultSeccompActionForce only sets the default action for all syscalls not defined +func (g *Generator) SetDefaultSeccompActionForce(action string) error { + g.initConfigLinuxSeccomp() + return seccomp.ParseDefaultActionForce(action, g.Config.Linux.Seccomp) +} + +// SetDomainName sets g.Config.Domainname +func (g *Generator) SetDomainName(domain string) { + g.initConfig() + g.Config.Domainname = domain +} + +// SetSeccompArchitecture sets the supported seccomp architectures +func (g *Generator) SetSeccompArchitecture(architecture string) error { + g.initConfigLinuxSeccomp() + return seccomp.ParseArchitectureFlag(architecture, g.Config.Linux.Seccomp) +} + +// RemoveSeccompRule removes rules for any specified syscalls +func (g *Generator) RemoveSeccompRule(arguments string) error { + g.initConfigLinuxSeccomp() + return seccomp.RemoveAction(arguments, g.Config.Linux.Seccomp) +} + +// RemoveAllSeccompRules removes all syscall rules +func (g *Generator) RemoveAllSeccompRules() error { + g.initConfigLinuxSeccomp() + return seccomp.RemoveAllSeccompRules(g.Config.Linux.Seccomp) +} + +// AddLinuxMaskedPaths adds masked paths into g.Config.Linux.MaskedPaths. +func (g *Generator) AddLinuxMaskedPaths(path string) { + g.initConfigLinux() + g.Config.Linux.MaskedPaths = append(g.Config.Linux.MaskedPaths, path) +} + +// AddLinuxReadonlyPaths adds readonly paths into g.Config.Linux.MaskedPaths. +func (g *Generator) AddLinuxReadonlyPaths(path string) { + g.initConfigLinux() + g.Config.Linux.ReadonlyPaths = append(g.Config.Linux.ReadonlyPaths, path) +} + +func addOrReplaceBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64, rate uint64) []rspec.LinuxThrottleDevice { + throttleDevices := tmpList + for i, throttleDevice := range throttleDevices { + if throttleDevice.Major == major && throttleDevice.Minor == minor { + throttleDevices[i].Rate = rate + return throttleDevices + } + } + throttleDevice := new(rspec.LinuxThrottleDevice) + throttleDevice.Major = major + throttleDevice.Minor = minor + throttleDevice.Rate = rate + throttleDevices = append(throttleDevices, *throttleDevice) + + return throttleDevices +} + +func dropBlockIOThrottleDevice(tmpList []rspec.LinuxThrottleDevice, major int64, minor int64) []rspec.LinuxThrottleDevice { + throttleDevices := tmpList + for i, throttleDevice := range throttleDevices { + if throttleDevice.Major == major && throttleDevice.Minor == minor { + throttleDevices = append(throttleDevices[:i], throttleDevices[i+1:]...) + return throttleDevices + } + } + + return throttleDevices +} + +// AddSolarisAnet adds network into g.Config.Solaris.Anet +func (g *Generator) AddSolarisAnet(anet rspec.SolarisAnet) { + g.initConfigSolaris() + g.Config.Solaris.Anet = append(g.Config.Solaris.Anet, anet) +} + +// SetSolarisCappedCPUNcpus sets g.Config.Solaris.CappedCPU.Ncpus +func (g *Generator) SetSolarisCappedCPUNcpus(ncpus string) { + g.initConfigSolarisCappedCPU() + g.Config.Solaris.CappedCPU.Ncpus = ncpus +} + +// SetSolarisCappedMemoryPhysical sets g.Config.Solaris.CappedMemory.Physical +func (g *Generator) SetSolarisCappedMemoryPhysical(physical string) { + g.initConfigSolarisCappedMemory() + g.Config.Solaris.CappedMemory.Physical = physical +} + +// SetSolarisCappedMemorySwap sets g.Config.Solaris.CappedMemory.Swap +func (g *Generator) SetSolarisCappedMemorySwap(swap string) { + g.initConfigSolarisCappedMemory() + g.Config.Solaris.CappedMemory.Swap = swap +} + +// SetSolarisLimitPriv sets g.Config.Solaris.LimitPriv +func (g *Generator) SetSolarisLimitPriv(limitPriv string) { + g.initConfigSolaris() + g.Config.Solaris.LimitPriv = limitPriv +} + +// SetSolarisMaxShmMemory sets g.Config.Solaris.MaxShmMemory +func (g *Generator) SetSolarisMaxShmMemory(memory string) { + g.initConfigSolaris() + g.Config.Solaris.MaxShmMemory = memory +} + +// SetSolarisMilestone sets g.Config.Solaris.Milestone +func (g *Generator) SetSolarisMilestone(milestone string) { + g.initConfigSolaris() + g.Config.Solaris.Milestone = milestone +} + +// SetVMHypervisorPath sets g.Config.VM.Hypervisor.Path +func (g *Generator) SetVMHypervisorPath(path string) error { + if !strings.HasPrefix(path, "/") { + return fmt.Errorf("hypervisorPath %v is not an absolute path", path) + } + g.initConfigVM() + g.Config.VM.Hypervisor.Path = path + return nil +} + +// SetVMHypervisorParameters sets g.Config.VM.Hypervisor.Parameters +func (g *Generator) SetVMHypervisorParameters(parameters []string) { + g.initConfigVM() + g.Config.VM.Hypervisor.Parameters = parameters +} + +// SetVMKernelPath sets g.Config.VM.Kernel.Path +func (g *Generator) SetVMKernelPath(path string) error { + if !strings.HasPrefix(path, "/") { + return fmt.Errorf("kernelPath %v is not an absolute path", path) + } + g.initConfigVM() + g.Config.VM.Kernel.Path = path + return nil +} + +// SetVMKernelParameters sets g.Config.VM.Kernel.Parameters +func (g *Generator) SetVMKernelParameters(parameters []string) { + g.initConfigVM() + g.Config.VM.Kernel.Parameters = parameters +} + +// SetVMKernelInitRD sets g.Config.VM.Kernel.InitRD +func (g *Generator) SetVMKernelInitRD(initrd string) error { + if !strings.HasPrefix(initrd, "/") { + return fmt.Errorf("kernelInitrd %v is not an absolute path", initrd) + } + g.initConfigVM() + g.Config.VM.Kernel.InitRD = initrd + return nil +} + +// SetVMImagePath sets g.Config.VM.Image.Path +func (g *Generator) SetVMImagePath(path string) error { + if !strings.HasPrefix(path, "/") { + return fmt.Errorf("imagePath %v is not an absolute path", path) + } + g.initConfigVM() + g.Config.VM.Image.Path = path + return nil +} + +// SetVMImageFormat sets g.Config.VM.Image.Format +func (g *Generator) SetVMImageFormat(format string) error { + switch format { + case "raw": + case "qcow2": + case "vdi": + case "vmdk": + case "vhd": + default: + return fmt.Errorf("Commonly supported formats are: raw, qcow2, vdi, vmdk, vhd") + } + g.initConfigVM() + g.Config.VM.Image.Format = format + return nil +} + +// SetWindowsHypervUntilityVMPath sets g.Config.Windows.HyperV.UtilityVMPath. +func (g *Generator) SetWindowsHypervUntilityVMPath(path string) { + g.initConfigWindowsHyperV() + g.Config.Windows.HyperV.UtilityVMPath = path +} + +// SetWindowsIgnoreFlushesDuringBoot sets g.Config.Windows.IgnoreFlushesDuringBoot. +func (g *Generator) SetWindowsIgnoreFlushesDuringBoot(ignore bool) { + g.initConfigWindows() + g.Config.Windows.IgnoreFlushesDuringBoot = ignore +} + +// AddWindowsLayerFolders adds layer folders into g.Config.Windows.LayerFolders. +func (g *Generator) AddWindowsLayerFolders(folder string) { + g.initConfigWindows() + g.Config.Windows.LayerFolders = append(g.Config.Windows.LayerFolders, folder) +} + +// AddWindowsDevices adds or sets g.Config.Windwos.Devices +func (g *Generator) AddWindowsDevices(id, idType string) error { + if idType != "class" { + return fmt.Errorf("Invalid idType value: %s. Windows only supports a value of class", idType) + } + device := rspec.WindowsDevice{ + ID: id, + IDType: idType, + } + + g.initConfigWindows() + for i, device := range g.Config.Windows.Devices { + if device.ID == id { + g.Config.Windows.Devices[i].IDType = idType + return nil + } + } + g.Config.Windows.Devices = append(g.Config.Windows.Devices, device) + return nil +} + +// SetWindowsNetwork sets g.Config.Windows.Network. +func (g *Generator) SetWindowsNetwork(network rspec.WindowsNetwork) { + g.initConfigWindows() + g.Config.Windows.Network = &network +} + +// SetWindowsNetworkAllowUnqualifiedDNSQuery sets g.Config.Windows.Network.AllowUnqualifiedDNSQuery +func (g *Generator) SetWindowsNetworkAllowUnqualifiedDNSQuery(setting bool) { + g.initConfigWindowsNetwork() + g.Config.Windows.Network.AllowUnqualifiedDNSQuery = setting +} + +// SetWindowsNetworkNamespace sets g.Config.Windows.Network.NetworkNamespace +func (g *Generator) SetWindowsNetworkNamespace(path string) { + g.initConfigWindowsNetwork() + g.Config.Windows.Network.NetworkNamespace = path +} + +// SetWindowsResourcesCPU sets g.Config.Windows.Resources.CPU. +func (g *Generator) SetWindowsResourcesCPU(cpu rspec.WindowsCPUResources) { + g.initConfigWindowsResources() + g.Config.Windows.Resources.CPU = &cpu +} + +// SetWindowsResourcesMemoryLimit sets g.Config.Windows.Resources.Memory.Limit. +func (g *Generator) SetWindowsResourcesMemoryLimit(limit uint64) { + g.initConfigWindowsResourcesMemory() + g.Config.Windows.Resources.Memory.Limit = &limit +} + +// SetWindowsResourcesStorage sets g.Config.Windows.Resources.Storage. +func (g *Generator) SetWindowsResourcesStorage(storage rspec.WindowsStorageResources) { + g.initConfigWindowsResources() + g.Config.Windows.Resources.Storage = &storage +} + +// SetWindowsServicing sets g.Config.Windows.Servicing. +func (g *Generator) SetWindowsServicing(servicing bool) { + g.initConfigWindows() + g.Config.Windows.Servicing = servicing +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go new file mode 100644 index 00000000..f28d8f58 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/consts.go @@ -0,0 +1,7 @@ +package seccomp + +const ( + seccompOverwrite = "overwrite" + seccompAppend = "append" + nothing = "nothing" +) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go new file mode 100644 index 00000000..25daf075 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_action.go @@ -0,0 +1,135 @@ +package seccomp + +import ( + "fmt" + "strconv" + "strings" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// SyscallOpts contain options for parsing syscall rules +type SyscallOpts struct { + Action string + Syscall string + Index string + Value string + ValueTwo string + Operator string +} + +// ParseSyscallFlag takes a SyscallOpts struct and the seccomp configuration +// and sets the new syscall rule accordingly +func ParseSyscallFlag(args SyscallOpts, config *rspec.LinuxSeccomp) error { + var arguments []string + if args.Index != "" && args.Value != "" && args.ValueTwo != "" && args.Operator != "" { + arguments = []string{args.Action, args.Syscall, args.Index, args.Value, + args.ValueTwo, args.Operator} + } else { + arguments = []string{args.Action, args.Syscall} + } + + action, _ := parseAction(arguments[0]) + if action == config.DefaultAction && args.argsAreEmpty() { + // default already set, no need to make changes + return nil + } + + var newSyscall rspec.LinuxSyscall + numOfArgs := len(arguments) + if numOfArgs == 6 || numOfArgs == 2 { + argStruct, err := parseArguments(arguments[1:]) + if err != nil { + return err + } + newSyscall = newSyscallStruct(arguments[1], action, argStruct) + } else { + return fmt.Errorf("incorrect number of arguments to ParseSyscall: %d", numOfArgs) + } + + descison, err := decideCourseOfAction(&newSyscall, config.Syscalls) + if err != nil { + return err + } + delimDescison := strings.Split(descison, ":") + + if delimDescison[0] == seccompAppend { + config.Syscalls = append(config.Syscalls, newSyscall) + } + + if delimDescison[0] == seccompOverwrite { + indexForOverwrite, err := strconv.ParseInt(delimDescison[1], 10, 32) + if err != nil { + return err + } + config.Syscalls[indexForOverwrite] = newSyscall + } + + return nil +} + +var actions = map[string]rspec.LinuxSeccompAction{ + "allow": rspec.ActAllow, + "errno": rspec.ActErrno, + "kill": rspec.ActKill, + "trace": rspec.ActTrace, + "trap": rspec.ActTrap, +} + +// Take passed action, return the SCMP_ACT_ version of it +func parseAction(action string) (rspec.LinuxSeccompAction, error) { + a, ok := actions[action] + if !ok { + return "", fmt.Errorf("unrecognized action: %s", action) + } + return a, nil +} + +// ParseDefaultAction sets the default action of the seccomp configuration +// and then removes any rules that were already specified with this action +func ParseDefaultAction(action string, config *rspec.LinuxSeccomp) error { + if action == "" { + return nil + } + + defaultAction, err := parseAction(action) + if err != nil { + return err + } + config.DefaultAction = defaultAction + err = RemoveAllMatchingRules(config, defaultAction) + if err != nil { + return err + } + return nil +} + +// ParseDefaultActionForce simply sets the default action of the seccomp configuration +func ParseDefaultActionForce(action string, config *rspec.LinuxSeccomp) error { + if action == "" { + return nil + } + + defaultAction, err := parseAction(action) + if err != nil { + return err + } + config.DefaultAction = defaultAction + return nil +} + +func newSyscallStruct(name string, action rspec.LinuxSeccompAction, args []rspec.LinuxSeccompArg) rspec.LinuxSyscall { + syscallStruct := rspec.LinuxSyscall{ + Names: []string{name}, + Action: action, + Args: args, + } + return syscallStruct +} + +func (s SyscallOpts) argsAreEmpty() bool { + return (s.Index == "" && + s.Value == "" && + s.ValueTwo == "" && + s.Operator == "") +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go new file mode 100644 index 00000000..9b2bdfd2 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_architecture.go @@ -0,0 +1,55 @@ +package seccomp + +import ( + "fmt" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// ParseArchitectureFlag takes the raw string passed with the --arch flag, parses it +// and updates the Seccomp config accordingly +func ParseArchitectureFlag(architectureArg string, config *rspec.LinuxSeccomp) error { + correctedArch, err := parseArch(architectureArg) + if err != nil { + return err + } + + shouldAppend := true + for _, alreadySpecified := range config.Architectures { + if correctedArch == alreadySpecified { + shouldAppend = false + } + } + if shouldAppend { + config.Architectures = append(config.Architectures, correctedArch) + } + return nil +} + +func parseArch(arch string) (rspec.Arch, error) { + arches := map[string]rspec.Arch{ + "x86": rspec.ArchX86, + "amd64": rspec.ArchX86_64, + "x32": rspec.ArchX32, + "arm": rspec.ArchARM, + "arm64": rspec.ArchAARCH64, + "mips": rspec.ArchMIPS, + "mips64": rspec.ArchMIPS64, + "mips64n32": rspec.ArchMIPS64N32, + "mipsel": rspec.ArchMIPSEL, + "mipsel64": rspec.ArchMIPSEL64, + "mipsel64n32": rspec.ArchMIPSEL64N32, + "parisc": rspec.ArchPARISC, + "parisc64": rspec.ArchPARISC64, + "ppc": rspec.ArchPPC, + "ppc64": rspec.ArchPPC64, + "ppc64le": rspec.ArchPPC64LE, + "s390": rspec.ArchS390, + "s390x": rspec.ArchS390X, + } + a, ok := arches[arch] + if !ok { + return "", fmt.Errorf("unrecognized architecture: %s", arch) + } + return a, nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go new file mode 100644 index 00000000..2b4c394e --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_arguments.go @@ -0,0 +1,73 @@ +package seccomp + +import ( + "fmt" + "strconv" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// parseArguments takes a list of arguments (delimArgs). It parses and fills out +// the argument information and returns a slice of arg structs +func parseArguments(delimArgs []string) ([]rspec.LinuxSeccompArg, error) { + nilArgSlice := []rspec.LinuxSeccompArg{} + numberOfArgs := len(delimArgs) + + // No parameters passed with syscall + if numberOfArgs == 1 { + return nilArgSlice, nil + } + + // Correct number of parameters passed with syscall + if numberOfArgs == 5 { + syscallIndex, err := strconv.ParseUint(delimArgs[1], 10, 0) + if err != nil { + return nilArgSlice, err + } + + syscallValue, err := strconv.ParseUint(delimArgs[2], 10, 64) + if err != nil { + return nilArgSlice, err + } + + syscallValueTwo, err := strconv.ParseUint(delimArgs[3], 10, 64) + if err != nil { + return nilArgSlice, err + } + + syscallOp, err := parseOperator(delimArgs[4]) + if err != nil { + return nilArgSlice, err + } + + argStruct := rspec.LinuxSeccompArg{ + Index: uint(syscallIndex), + Value: syscallValue, + ValueTwo: syscallValueTwo, + Op: syscallOp, + } + + argSlice := []rspec.LinuxSeccompArg{} + argSlice = append(argSlice, argStruct) + return argSlice, nil + } + + return nilArgSlice, fmt.Errorf("incorrect number of arguments passed with syscall: %d", numberOfArgs) +} + +func parseOperator(operator string) (rspec.LinuxSeccompOperator, error) { + operators := map[string]rspec.LinuxSeccompOperator{ + "NE": rspec.OpNotEqual, + "LT": rspec.OpLessThan, + "LE": rspec.OpLessEqual, + "EQ": rspec.OpEqualTo, + "GE": rspec.OpGreaterEqual, + "GT": rspec.OpGreaterThan, + "ME": rspec.OpMaskedEqual, + } + o, ok := operators[operator] + if !ok { + return "", fmt.Errorf("unrecognized operator: %s", operator) + } + return o, nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go new file mode 100644 index 00000000..59537d49 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/parse_remove.go @@ -0,0 +1,52 @@ +package seccomp + +import ( + "fmt" + "reflect" + "strings" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// RemoveAction takes the argument string that was passed with the --remove flag, +// parses it, and updates the Seccomp config accordingly +func RemoveAction(arguments string, config *rspec.LinuxSeccomp) error { + if config == nil { + return fmt.Errorf("Cannot remove action from nil Seccomp pointer") + } + + syscallsToRemove := strings.Split(arguments, ",") + + for counter, syscallStruct := range config.Syscalls { + if reflect.DeepEqual(syscallsToRemove, syscallStruct.Names) { + config.Syscalls = append(config.Syscalls[:counter], config.Syscalls[counter+1:]...) + } + } + + return nil +} + +// RemoveAllSeccompRules removes all seccomp syscall rules +func RemoveAllSeccompRules(config *rspec.LinuxSeccomp) error { + if config == nil { + return fmt.Errorf("Cannot remove action from nil Seccomp pointer") + } + newSyscallSlice := []rspec.LinuxSyscall{} + config.Syscalls = newSyscallSlice + return nil +} + +// RemoveAllMatchingRules will remove any syscall rules that match the specified action +func RemoveAllMatchingRules(config *rspec.LinuxSeccomp, seccompAction rspec.LinuxSeccompAction) error { + if config == nil { + return fmt.Errorf("Cannot remove action from nil Seccomp pointer") + } + + for _, syscall := range config.Syscalls { + if reflect.DeepEqual(syscall.Action, seccompAction) { + RemoveAction(strings.Join(syscall.Names, ","), config) + } + } + + return nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go new file mode 100644 index 00000000..345a32a6 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default.go @@ -0,0 +1,606 @@ +package seccomp + +import ( + "runtime" + + "github.com/opencontainers/runtime-spec/specs-go" + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +func arches() []rspec.Arch { + native := runtime.GOARCH + + switch native { + case "amd64": + return []rspec.Arch{rspec.ArchX86_64, rspec.ArchX86, rspec.ArchX32} + case "arm64": + return []rspec.Arch{rspec.ArchARM, rspec.ArchAARCH64} + case "mips64": + return []rspec.Arch{rspec.ArchMIPS, rspec.ArchMIPS64, rspec.ArchMIPS64N32} + case "mips64n32": + return []rspec.Arch{rspec.ArchMIPS, rspec.ArchMIPS64, rspec.ArchMIPS64N32} + case "mipsel64": + return []rspec.Arch{rspec.ArchMIPSEL, rspec.ArchMIPSEL64, rspec.ArchMIPSEL64N32} + case "mipsel64n32": + return []rspec.Arch{rspec.ArchMIPSEL, rspec.ArchMIPSEL64, rspec.ArchMIPSEL64N32} + case "s390x": + return []rspec.Arch{rspec.ArchS390, rspec.ArchS390X} + default: + return []rspec.Arch{} + } +} + +// DefaultProfile defines the whitelist for the default seccomp profile. +func DefaultProfile(rs *specs.Spec) *rspec.LinuxSeccomp { + + syscalls := []rspec.LinuxSyscall{ + { + Names: []string{ + "accept", + "accept4", + "access", + "alarm", + "bind", + "brk", + "capget", + "capset", + "chdir", + "chmod", + "chown", + "chown32", + "clock_getres", + "clock_gettime", + "clock_nanosleep", + "close", + "connect", + "copy_file_range", + "creat", + "dup", + "dup2", + "dup3", + "epoll_create", + "epoll_create1", + "epoll_ctl", + "epoll_ctl_old", + "epoll_pwait", + "epoll_wait", + "epoll_wait_old", + "eventfd", + "eventfd2", + "execve", + "execveat", + "exit", + "exit_group", + "faccessat", + "fadvise64", + "fadvise64_64", + "fallocate", + "fanotify_mark", + "fchdir", + "fchmod", + "fchmodat", + "fchown", + "fchown32", + "fchownat", + "fcntl", + "fcntl64", + "fdatasync", + "fgetxattr", + "flistxattr", + "flock", + "fork", + "fremovexattr", + "fsetxattr", + "fstat", + "fstat64", + "fstatat64", + "fstatfs", + "fstatfs64", + "fsync", + "ftruncate", + "ftruncate64", + "futex", + "futimesat", + "getcpu", + "getcwd", + "getdents", + "getdents64", + "getegid", + "getegid32", + "geteuid", + "geteuid32", + "getgid", + "getgid32", + "getgroups", + "getgroups32", + "getitimer", + "getpeername", + "getpgid", + "getpgrp", + "getpid", + "getppid", + "getpriority", + "getrandom", + "getresgid", + "getresgid32", + "getresuid", + "getresuid32", + "getrlimit", + "get_robust_list", + "getrusage", + "getsid", + "getsockname", + "getsockopt", + "get_thread_area", + "gettid", + "gettimeofday", + "getuid", + "getuid32", + "getxattr", + "inotify_add_watch", + "inotify_init", + "inotify_init1", + "inotify_rm_watch", + "io_cancel", + "ioctl", + "io_destroy", + "io_getevents", + "ioprio_get", + "ioprio_set", + "io_setup", + "io_submit", + "ipc", + "kill", + "landlock_add_rule", + "landlock_create_ruleset", + "landlock_restrict_self", + "lchown", + "lchown32", + "lgetxattr", + "link", + "linkat", + "listen", + "listxattr", + "llistxattr", + "_llseek", + "lremovexattr", + "lseek", + "lsetxattr", + "lstat", + "lstat64", + "madvise", + "memfd_create", + "mincore", + "mkdir", + "mkdirat", + "mknod", + "mknodat", + "mlock", + "mlock2", + "mlockall", + "mmap", + "mmap2", + "mprotect", + "mq_getsetattr", + "mq_notify", + "mq_open", + "mq_timedreceive", + "mq_timedsend", + "mq_unlink", + "mremap", + "msgctl", + "msgget", + "msgrcv", + "msgsnd", + "msync", + "munlock", + "munlockall", + "munmap", + "nanosleep", + "newfstatat", + "_newselect", + "open", + "openat", + "pause", + "pipe", + "pipe2", + "poll", + "ppoll", + "prctl", + "pread64", + "preadv", + "prlimit64", + "pselect6", + "pwrite64", + "pwritev", + "read", + "readahead", + "readlink", + "readlinkat", + "readv", + "recv", + "recvfrom", + "recvmmsg", + "recvmsg", + "remap_file_pages", + "removexattr", + "rename", + "renameat", + "renameat2", + "restart_syscall", + "rmdir", + "rt_sigaction", + "rt_sigpending", + "rt_sigprocmask", + "rt_sigqueueinfo", + "rt_sigreturn", + "rt_sigsuspend", + "rt_sigtimedwait", + "rt_tgsigqueueinfo", + "sched_getaffinity", + "sched_getattr", + "sched_getparam", + "sched_get_priority_max", + "sched_get_priority_min", + "sched_getscheduler", + "sched_rr_get_interval", + "sched_setaffinity", + "sched_setattr", + "sched_setparam", + "sched_setscheduler", + "sched_yield", + "seccomp", + "select", + "semctl", + "semget", + "semop", + "semtimedop", + "send", + "sendfile", + "sendfile64", + "sendmmsg", + "sendmsg", + "sendto", + "setfsgid", + "setfsgid32", + "setfsuid", + "setfsuid32", + "setgid", + "setgid32", + "setgroups", + "setgroups32", + "setitimer", + "setpgid", + "setpriority", + "setregid", + "setregid32", + "setresgid", + "setresgid32", + "setresuid", + "setresuid32", + "setreuid", + "setreuid32", + "setrlimit", + "set_robust_list", + "setsid", + "setsockopt", + "set_thread_area", + "set_tid_address", + "setuid", + "setuid32", + "setxattr", + "shmat", + "shmctl", + "shmdt", + "shmget", + "shutdown", + "sigaltstack", + "signalfd", + "signalfd4", + "sigreturn", + "socket", + "socketcall", + "socketpair", + "splice", + "stat", + "stat64", + "statfs", + "statfs64", + "statx", + "symlink", + "symlinkat", + "sync", + "sync_file_range", + "syncfs", + "sysinfo", + "syslog", + "tee", + "tgkill", + "time", + "timer_create", + "timer_delete", + "timerfd_create", + "timerfd_gettime", + "timerfd_settime", + "timer_getoverrun", + "timer_gettime", + "timer_settime", + "times", + "tkill", + "truncate", + "truncate64", + "ugetrlimit", + "umask", + "uname", + "unlink", + "unlinkat", + "utime", + "utimensat", + "utimes", + "vfork", + "vmsplice", + "wait4", + "waitid", + "waitpid", + "write", + "writev", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + { + Names: []string{"personality"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ + { + Index: 0, + Value: 0x0, + Op: rspec.OpEqualTo, + }, + }, + }, + { + Names: []string{"personality"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ + { + Index: 0, + Value: 0x0008, + Op: rspec.OpEqualTo, + }, + }, + }, + { + Names: []string{"personality"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ + { + Index: 0, + Value: 0xffffffff, + Op: rspec.OpEqualTo, + }, + }, + }, + } + var sysCloneFlagsIndex uint + + capSysAdmin := false + caps := make(map[string]bool) + + for _, cap := range rs.Process.Capabilities.Bounding { + caps[cap] = true + } + for _, cap := range rs.Process.Capabilities.Effective { + caps[cap] = true + } + for _, cap := range rs.Process.Capabilities.Inheritable { + caps[cap] = true + } + for _, cap := range rs.Process.Capabilities.Permitted { + caps[cap] = true + } + for _, cap := range rs.Process.Capabilities.Ambient { + caps[cap] = true + } + + for cap := range caps { + switch cap { + case "CAP_DAC_READ_SEARCH": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"open_by_handle_at"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_ADMIN": + capSysAdmin = true + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "bpf", + "clone", + "fanotify_init", + "lookup_dcookie", + "mount", + "name_to_handle_at", + "perf_event_open", + "setdomainname", + "sethostname", + "setns", + "umount", + "umount2", + "unshare", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_BOOT": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"reboot"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_CHROOT": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"chroot"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_MODULE": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "delete_module", + "init_module", + "finit_module", + "query_module", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_PACCT": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"acct"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_PTRACE": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "kcmp", + "process_vm_readv", + "process_vm_writev", + "ptrace", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_RAWIO": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "iopl", + "ioperm", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_TIME": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "settimeofday", + "stime", + "adjtimex", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "CAP_SYS_TTY_CONFIG": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"vhangup"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + } + } + + if !capSysAdmin { + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"clone"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ + { + Index: sysCloneFlagsIndex, + Value: CloneNewNS | CloneNewUTS | CloneNewIPC | CloneNewUser | CloneNewPID | CloneNewNet | CloneNewCgroup, + ValueTwo: 0, + Op: rspec.OpMaskedEqual, + }, + }, + }, + }...) + + } + + arch := runtime.GOARCH + switch arch { + case "arm", "arm64": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "breakpoint", + "cacheflush", + "set_tls", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "amd64", "x32": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"arch_prctl"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + fallthrough + case "x86": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"modify_ldt"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + case "s390", "s390x": + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{ + "s390_pci_mmio_read", + "s390_pci_mmio_write", + "s390_runtime_instr", + }, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{}, + }, + }...) + /* Flags parameter of the clone syscall is the 2nd on s390 */ + syscalls = append(syscalls, []rspec.LinuxSyscall{ + { + Names: []string{"clone"}, + Action: rspec.ActAllow, + Args: []rspec.LinuxSeccompArg{ + { + Index: 1, + Value: 2080505856, + ValueTwo: 0, + Op: rspec.OpMaskedEqual, + }, + }, + }, + }...) + } + + return &rspec.LinuxSeccomp{ + DefaultAction: rspec.ActErrno, + Architectures: arches(), + Syscalls: syscalls, + } +} diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go new file mode 100644 index 00000000..5ca9a6da --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_linux.go @@ -0,0 +1,17 @@ +//go:build linux +// +build linux + +package seccomp + +import "golang.org/x/sys/unix" + +// System values passed through on linux +const ( + CloneNewIPC = unix.CLONE_NEWIPC + CloneNewNet = unix.CLONE_NEWNET + CloneNewNS = unix.CLONE_NEWNS + CloneNewPID = unix.CLONE_NEWPID + CloneNewUser = unix.CLONE_NEWUSER + CloneNewUTS = unix.CLONE_NEWUTS + CloneNewCgroup = unix.CLONE_NEWCGROUP +) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go new file mode 100644 index 00000000..b8c1bc26 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/seccomp_default_unsupported.go @@ -0,0 +1,16 @@ +//go:build !linux +// +build !linux + +package seccomp + +// These are copied from linux/amd64 syscall values, as a reference for other +// platforms to have access to +const ( + CloneNewIPC = 0x8000000 + CloneNewNet = 0x40000000 + CloneNewNS = 0x20000 + CloneNewPID = 0x20000000 + CloneNewUser = 0x10000000 + CloneNewUTS = 0x4000000 + CloneNewCgroup = 0x02000000 +) diff --git a/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go new file mode 100644 index 00000000..5e84653a --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/generate/seccomp/syscall_compare.go @@ -0,0 +1,124 @@ +package seccomp + +import ( + "fmt" + "reflect" + "strconv" + "strings" + + rspec "github.com/opencontainers/runtime-spec/specs-go" +) + +// Determine if a new syscall rule should be appended, overwrite an existing rule +// or if no action should be taken at all +func decideCourseOfAction(newSyscall *rspec.LinuxSyscall, syscalls []rspec.LinuxSyscall) (string, error) { + ruleForSyscallAlreadyExists := false + + var sliceOfDeterminedActions []string + for i, syscall := range syscalls { + if sameName(&syscall, newSyscall) { + ruleForSyscallAlreadyExists = true + + if identical(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing) + } + + if sameAction(newSyscall, &syscall) { + if bothHaveArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) + } + if onlyOneHasArgs(newSyscall, &syscall) { + if firstParamOnlyHasArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) + } else { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, nothing) + } + } + } + + if !sameAction(newSyscall, &syscall) { + if bothHaveArgs(newSyscall, &syscall) { + if sameArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) + } + if !sameArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) + } + } + if onlyOneHasArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) + } + if neitherHasArgs(newSyscall, &syscall) { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, "overwrite:"+strconv.Itoa(i)) + } + } + } + } + + if !ruleForSyscallAlreadyExists { + sliceOfDeterminedActions = append(sliceOfDeterminedActions, seccompAppend) + } + + // Nothing has highest priority + for _, determinedAction := range sliceOfDeterminedActions { + if determinedAction == nothing { + return determinedAction, nil + } + } + + // Overwrite has second highest priority + for _, determinedAction := range sliceOfDeterminedActions { + if strings.Contains(determinedAction, seccompOverwrite) { + return determinedAction, nil + } + } + + // Append has the lowest priority + for _, determinedAction := range sliceOfDeterminedActions { + if determinedAction == seccompAppend { + return determinedAction, nil + } + } + + return "", fmt.Errorf("Trouble determining action: %s", sliceOfDeterminedActions) +} + +func hasArguments(config *rspec.LinuxSyscall) bool { + nilSyscall := new(rspec.LinuxSyscall) + return !sameArgs(nilSyscall, config) +} + +func identical(config1, config2 *rspec.LinuxSyscall) bool { + return reflect.DeepEqual(config1, config2) +} + +func sameName(config1, config2 *rspec.LinuxSyscall) bool { + return reflect.DeepEqual(config1.Names, config2.Names) +} + +func sameAction(config1, config2 *rspec.LinuxSyscall) bool { + return config1.Action == config2.Action +} + +func sameArgs(config1, config2 *rspec.LinuxSyscall) bool { + return reflect.DeepEqual(config1.Args, config2.Args) +} + +func bothHaveArgs(config1, config2 *rspec.LinuxSyscall) bool { + return hasArguments(config1) && hasArguments(config2) +} + +func onlyOneHasArgs(config1, config2 *rspec.LinuxSyscall) bool { + conf1 := hasArguments(config1) + conf2 := hasArguments(config2) + + return (conf1 && !conf2) || (!conf1 && conf2) +} + +func neitherHasArgs(config1, config2 *rspec.LinuxSyscall) bool { + return !hasArguments(config1) && !hasArguments(config2) +} + +func firstParamOnlyHasArgs(config1, config2 *rspec.LinuxSyscall) bool { + return !hasArguments(config1) && hasArguments(config2) +} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go new file mode 100644 index 00000000..7fa47b77 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate.go @@ -0,0 +1,31 @@ +package capabilities + +import ( + "fmt" + "strings" + + "github.com/syndtr/gocapability/capability" +) + +// CapValid checks whether a capability is valid +func CapValid(c string, hostSpecific bool) error { + isValid := false + + if !strings.HasPrefix(c, "CAP_") { + return fmt.Errorf("capability %s must start with CAP_", c) + } + for _, cap := range capability.List() { + if c == fmt.Sprintf("CAP_%s", strings.ToUpper(cap.String())) { + if hostSpecific && cap > LastCap() { + return fmt.Errorf("%s is not supported on the current host", c) + } + isValid = true + break + } + } + + if !isValid { + return fmt.Errorf("invalid capability: %s", c) + } + return nil +} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_linux.go b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_linux.go new file mode 100644 index 00000000..f6cb0d55 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_linux.go @@ -0,0 +1,16 @@ +package capabilities + +import ( + "github.com/syndtr/gocapability/capability" +) + +// LastCap return last cap of system +func LastCap() capability.Cap { + last := capability.CAP_LAST_CAP + // hack for RHEL6 which has no /proc/sys/kernel/cap_last_cap + if last == capability.Cap(63) { + last = capability.CAP_BLOCK_SUSPEND + } + + return last +} diff --git a/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_unsupported.go b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_unsupported.go new file mode 100644 index 00000000..e4aed632 --- /dev/null +++ b/vendor/github.com/opencontainers/runtime-tools/validate/capabilities/validate_unsupported.go @@ -0,0 +1,13 @@ +//go:build !linux +// +build !linux + +package capabilities + +import ( + "github.com/syndtr/gocapability/capability" +) + +// LastCap return last cap of system +func LastCap() capability.Cap { + return capability.Cap(-1) +} diff --git a/vendor/github.com/sirupsen/logrus/.gitignore b/vendor/github.com/sirupsen/logrus/.gitignore new file mode 100644 index 00000000..1fb13abe --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.gitignore @@ -0,0 +1,4 @@ +logrus +vendor + +.idea/ diff --git a/vendor/github.com/sirupsen/logrus/.golangci.yml b/vendor/github.com/sirupsen/logrus/.golangci.yml new file mode 100644 index 00000000..65dc2850 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.golangci.yml @@ -0,0 +1,40 @@ +run: + # do not run on test files yet + tests: false + +# all available settings of specific linters +linters-settings: + errcheck: + # report about not checking of errors in type assetions: `a := b.(MyStruct)`; + # default is false: such cases aren't reported by default. + check-type-assertions: false + + # report about assignment of errors to blank identifier: `num, _ := strconv.Atoi(numStr)`; + # default is false: such cases aren't reported by default. + check-blank: false + + lll: + line-length: 100 + tab-width: 4 + + prealloc: + simple: false + range-loops: false + for-loops: false + + whitespace: + multi-if: false # Enforces newlines (or comments) after every multi-line if statement + multi-func: false # Enforces newlines (or comments) after every multi-line function signature + +linters: + enable: + - megacheck + - govet + disable: + - maligned + - prealloc + disable-all: false + presets: + - bugs + - unused + fast: false diff --git a/vendor/github.com/sirupsen/logrus/.travis.yml b/vendor/github.com/sirupsen/logrus/.travis.yml new file mode 100644 index 00000000..c1dbd5a3 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/.travis.yml @@ -0,0 +1,15 @@ +language: go +go_import_path: github.com/sirupsen/logrus +git: + depth: 1 +env: + - GO111MODULE=on +go: 1.15.x +os: linux +install: + - ./travis/install.sh +script: + - cd ci + - go run mage.go -v -w ../ crossBuild + - go run mage.go -v -w ../ lint + - go run mage.go -v -w ../ test diff --git a/vendor/github.com/sirupsen/logrus/CHANGELOG.md b/vendor/github.com/sirupsen/logrus/CHANGELOG.md new file mode 100644 index 00000000..7567f612 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/CHANGELOG.md @@ -0,0 +1,259 @@ +# 1.8.1 +Code quality: + * move magefile in its own subdir/submodule to remove magefile dependency on logrus consumer + * improve timestamp format documentation + +Fixes: + * fix race condition on logger hooks + + +# 1.8.0 + +Correct versioning number replacing v1.7.1. + +# 1.7.1 + +Beware this release has introduced a new public API and its semver is therefore incorrect. + +Code quality: + * use go 1.15 in travis + * use magefile as task runner + +Fixes: + * small fixes about new go 1.13 error formatting system + * Fix for long time race condiction with mutating data hooks + +Features: + * build support for zos + +# 1.7.0 +Fixes: + * the dependency toward a windows terminal library has been removed + +Features: + * a new buffer pool management API has been added + * a set of `Fn()` functions have been added + +# 1.6.0 +Fixes: + * end of line cleanup + * revert the entry concurrency bug fix whic leads to deadlock under some circumstances + * update dependency on go-windows-terminal-sequences to fix a crash with go 1.14 + +Features: + * add an option to the `TextFormatter` to completely disable fields quoting + +# 1.5.0 +Code quality: + * add golangci linter run on travis + +Fixes: + * add mutex for hooks concurrent access on `Entry` data + * caller function field for go1.14 + * fix build issue for gopherjs target + +Feature: + * add an hooks/writer sub-package whose goal is to split output on different stream depending on the trace level + * add a `DisableHTMLEscape` option in the `JSONFormatter` + * add `ForceQuote` and `PadLevelText` options in the `TextFormatter` + +# 1.4.2 + * Fixes build break for plan9, nacl, solaris +# 1.4.1 +This new release introduces: + * Enhance TextFormatter to not print caller information when they are empty (#944) + * Remove dependency on golang.org/x/crypto (#932, #943) + +Fixes: + * Fix Entry.WithContext method to return a copy of the initial entry (#941) + +# 1.4.0 +This new release introduces: + * Add `DeferExitHandler`, similar to `RegisterExitHandler` but prepending the handler to the list of handlers (semantically like `defer`) (#848). + * Add `CallerPrettyfier` to `JSONFormatter` and `TextFormatter` (#909, #911) + * Add `Entry.WithContext()` and `Entry.Context`, to set a context on entries to be used e.g. in hooks (#919). + +Fixes: + * Fix wrong method calls `Logger.Print` and `Logger.Warningln` (#893). + * Update `Entry.Logf` to not do string formatting unless the log level is enabled (#903) + * Fix infinite recursion on unknown `Level.String()` (#907) + * Fix race condition in `getCaller` (#916). + + +# 1.3.0 +This new release introduces: + * Log, Logf, Logln functions for Logger and Entry that take a Level + +Fixes: + * Building prometheus node_exporter on AIX (#840) + * Race condition in TextFormatter (#468) + * Travis CI import path (#868) + * Remove coloured output on Windows (#862) + * Pointer to func as field in JSONFormatter (#870) + * Properly marshal Levels (#873) + +# 1.2.0 +This new release introduces: + * A new method `SetReportCaller` in the `Logger` to enable the file, line and calling function from which the trace has been issued + * A new trace level named `Trace` whose level is below `Debug` + * A configurable exit function to be called upon a Fatal trace + * The `Level` object now implements `encoding.TextUnmarshaler` interface + +# 1.1.1 +This is a bug fix release. + * fix the build break on Solaris + * don't drop a whole trace in JSONFormatter when a field param is a function pointer which can not be serialized + +# 1.1.0 +This new release introduces: + * several fixes: + * a fix for a race condition on entry formatting + * proper cleanup of previously used entries before putting them back in the pool + * the extra new line at the end of message in text formatter has been removed + * a new global public API to check if a level is activated: IsLevelEnabled + * the following methods have been added to the Logger object + * IsLevelEnabled + * SetFormatter + * SetOutput + * ReplaceHooks + * introduction of go module + * an indent configuration for the json formatter + * output colour support for windows + * the field sort function is now configurable for text formatter + * the CLICOLOR and CLICOLOR\_FORCE environment variable support in text formater + +# 1.0.6 + +This new release introduces: + * a new api WithTime which allows to easily force the time of the log entry + which is mostly useful for logger wrapper + * a fix reverting the immutability of the entry given as parameter to the hooks + a new configuration field of the json formatter in order to put all the fields + in a nested dictionnary + * a new SetOutput method in the Logger + * a new configuration of the textformatter to configure the name of the default keys + * a new configuration of the text formatter to disable the level truncation + +# 1.0.5 + +* Fix hooks race (#707) +* Fix panic deadlock (#695) + +# 1.0.4 + +* Fix race when adding hooks (#612) +* Fix terminal check in AppEngine (#635) + +# 1.0.3 + +* Replace example files with testable examples + +# 1.0.2 + +* bug: quote non-string values in text formatter (#583) +* Make (*Logger) SetLevel a public method + +# 1.0.1 + +* bug: fix escaping in text formatter (#575) + +# 1.0.0 + +* Officially changed name to lower-case +* bug: colors on Windows 10 (#541) +* bug: fix race in accessing level (#512) + +# 0.11.5 + +* feature: add writer and writerlevel to entry (#372) + +# 0.11.4 + +* bug: fix undefined variable on solaris (#493) + +# 0.11.3 + +* formatter: configure quoting of empty values (#484) +* formatter: configure quoting character (default is `"`) (#484) +* bug: fix not importing io correctly in non-linux environments (#481) + +# 0.11.2 + +* bug: fix windows terminal detection (#476) + +# 0.11.1 + +* bug: fix tty detection with custom out (#471) + +# 0.11.0 + +* performance: Use bufferpool to allocate (#370) +* terminal: terminal detection for app-engine (#343) +* feature: exit handler (#375) + +# 0.10.0 + +* feature: Add a test hook (#180) +* feature: `ParseLevel` is now case-insensitive (#326) +* feature: `FieldLogger` interface that generalizes `Logger` and `Entry` (#308) +* performance: avoid re-allocations on `WithFields` (#335) + +# 0.9.0 + +* logrus/text_formatter: don't emit empty msg +* logrus/hooks/airbrake: move out of main repository +* logrus/hooks/sentry: move out of main repository +* logrus/hooks/papertrail: move out of main repository +* logrus/hooks/bugsnag: move out of main repository +* logrus/core: run tests with `-race` +* logrus/core: detect TTY based on `stderr` +* logrus/core: support `WithError` on logger +* logrus/core: Solaris support + +# 0.8.7 + +* logrus/core: fix possible race (#216) +* logrus/doc: small typo fixes and doc improvements + + +# 0.8.6 + +* hooks/raven: allow passing an initialized client + +# 0.8.5 + +* logrus/core: revert #208 + +# 0.8.4 + +* formatter/text: fix data race (#218) + +# 0.8.3 + +* logrus/core: fix entry log level (#208) +* logrus/core: improve performance of text formatter by 40% +* logrus/core: expose `LevelHooks` type +* logrus/core: add support for DragonflyBSD and NetBSD +* formatter/text: print structs more verbosely + +# 0.8.2 + +* logrus: fix more Fatal family functions + +# 0.8.1 + +* logrus: fix not exiting on `Fatalf` and `Fatalln` + +# 0.8.0 + +* logrus: defaults to stderr instead of stdout +* hooks/sentry: add special field for `*http.Request` +* formatter/text: ignore Windows for colors + +# 0.7.3 + +* formatter/\*: allow configuration of timestamp layout + +# 0.7.2 + +* formatter/text: Add configuration option for time format (#158) diff --git a/vendor/github.com/sirupsen/logrus/LICENSE b/vendor/github.com/sirupsen/logrus/LICENSE new file mode 100644 index 00000000..f090cb42 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Simon Eskildsen + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/vendor/github.com/sirupsen/logrus/README.md b/vendor/github.com/sirupsen/logrus/README.md new file mode 100644 index 00000000..d1d4a85f --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/README.md @@ -0,0 +1,515 @@ +# Logrus :walrus: [![Build Status](https://github.com/sirupsen/logrus/workflows/CI/badge.svg)](https://github.com/sirupsen/logrus/actions?query=workflow%3ACI) [![Build Status](https://travis-ci.org/sirupsen/logrus.svg?branch=master)](https://travis-ci.org/sirupsen/logrus) [![Go Reference](https://pkg.go.dev/badge/github.com/sirupsen/logrus.svg)](https://pkg.go.dev/github.com/sirupsen/logrus) + +Logrus is a structured logger for Go (golang), completely API compatible with +the standard library logger. + +**Logrus is in maintenance-mode.** We will not be introducing new features. It's +simply too hard to do in a way that won't break many people's projects, which is +the last thing you want from your Logging library (again...). + +This does not mean Logrus is dead. Logrus will continue to be maintained for +security, (backwards compatible) bug fixes, and performance (where we are +limited by the interface). + +I believe Logrus' biggest contribution is to have played a part in today's +widespread use of structured logging in Golang. There doesn't seem to be a +reason to do a major, breaking iteration into Logrus V2, since the fantastic Go +community has built those independently. Many fantastic alternatives have sprung +up. Logrus would look like those, had it been re-designed with what we know +about structured logging in Go today. Check out, for example, +[Zerolog][zerolog], [Zap][zap], and [Apex][apex]. + +[zerolog]: https://github.com/rs/zerolog +[zap]: https://github.com/uber-go/zap +[apex]: https://github.com/apex/log + +**Seeing weird case-sensitive problems?** It's in the past been possible to +import Logrus as both upper- and lower-case. Due to the Go package environment, +this caused issues in the community and we needed a standard. Some environments +experienced problems with the upper-case variant, so the lower-case was decided. +Everything using `logrus` will need to use the lower-case: +`github.com/sirupsen/logrus`. Any package that isn't, should be changed. + +To fix Glide, see [these +comments](https://github.com/sirupsen/logrus/issues/553#issuecomment-306591437). +For an in-depth explanation of the casing issue, see [this +comment](https://github.com/sirupsen/logrus/issues/570#issuecomment-313933276). + +Nicely color-coded in development (when a TTY is attached, otherwise just +plain text): + +![Colored](http://i.imgur.com/PY7qMwd.png) + +With `log.SetFormatter(&log.JSONFormatter{})`, for easy parsing by logstash +or Splunk: + +```text +{"animal":"walrus","level":"info","msg":"A group of walrus emerges from the +ocean","size":10,"time":"2014-03-10 19:57:38.562264131 -0400 EDT"} + +{"level":"warning","msg":"The group's number increased tremendously!", +"number":122,"omg":true,"time":"2014-03-10 19:57:38.562471297 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"A giant walrus appears!", +"size":10,"time":"2014-03-10 19:57:38.562500591 -0400 EDT"} + +{"animal":"walrus","level":"info","msg":"Tremendously sized cow enters the ocean.", +"size":9,"time":"2014-03-10 19:57:38.562527896 -0400 EDT"} + +{"level":"fatal","msg":"The ice breaks!","number":100,"omg":true, +"time":"2014-03-10 19:57:38.562543128 -0400 EDT"} +``` + +With the default `log.SetFormatter(&log.TextFormatter{})` when a TTY is not +attached, the output is compatible with the +[logfmt](http://godoc.org/github.com/kr/logfmt) format: + +```text +time="2015-03-26T01:27:38-04:00" level=debug msg="Started observing beach" animal=walrus number=8 +time="2015-03-26T01:27:38-04:00" level=info msg="A group of walrus emerges from the ocean" animal=walrus size=10 +time="2015-03-26T01:27:38-04:00" level=warning msg="The group's number increased tremendously!" number=122 omg=true +time="2015-03-26T01:27:38-04:00" level=debug msg="Temperature changes" temperature=-4 +time="2015-03-26T01:27:38-04:00" level=panic msg="It's over 9000!" animal=orca size=9009 +time="2015-03-26T01:27:38-04:00" level=fatal msg="The ice breaks!" err=&{0x2082280c0 map[animal:orca size:9009] 2015-03-26 01:27:38.441574009 -0400 EDT panic It's over 9000!} number=100 omg=true +``` +To ensure this behaviour even if a TTY is attached, set your formatter as follows: + +```go + log.SetFormatter(&log.TextFormatter{ + DisableColors: true, + FullTimestamp: true, + }) +``` + +#### Logging Method Name + +If you wish to add the calling method as a field, instruct the logger via: +```go +log.SetReportCaller(true) +``` +This adds the caller as 'method' like so: + +```json +{"animal":"penguin","level":"fatal","method":"github.com/sirupsen/arcticcreatures.migrate","msg":"a penguin swims by", +"time":"2014-03-10 19:57:38.562543129 -0400 EDT"} +``` + +```text +time="2015-03-26T01:27:38-04:00" level=fatal method=github.com/sirupsen/arcticcreatures.migrate msg="a penguin swims by" animal=penguin +``` +Note that this does add measurable overhead - the cost will depend on the version of Go, but is +between 20 and 40% in recent tests with 1.6 and 1.7. You can validate this in your +environment via benchmarks: +``` +go test -bench=.*CallerTracing +``` + + +#### Case-sensitivity + +The organization's name was changed to lower-case--and this will not be changed +back. If you are getting import conflicts due to case sensitivity, please use +the lower-case import: `github.com/sirupsen/logrus`. + +#### Example + +The simplest way to use Logrus is simply the package-level exported logger: + +```go +package main + +import ( + log "github.com/sirupsen/logrus" +) + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + }).Info("A walrus appears") +} +``` + +Note that it's completely api-compatible with the stdlib logger, so you can +replace your `log` imports everywhere with `log "github.com/sirupsen/logrus"` +and you'll now have the flexibility of Logrus. You can customize it all you +want: + +```go +package main + +import ( + "os" + log "github.com/sirupsen/logrus" +) + +func init() { + // Log as JSON instead of the default ASCII formatter. + log.SetFormatter(&log.JSONFormatter{}) + + // Output to stdout instead of the default stderr + // Can be any io.Writer, see below for File example + log.SetOutput(os.Stdout) + + // Only log the warning severity or above. + log.SetLevel(log.WarnLevel) +} + +func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") + + log.WithFields(log.Fields{ + "omg": true, + "number": 122, + }).Warn("The group's number increased tremendously!") + + log.WithFields(log.Fields{ + "omg": true, + "number": 100, + }).Fatal("The ice breaks!") + + // A common pattern is to re-use fields between logging statements by re-using + // the logrus.Entry returned from WithFields() + contextLogger := log.WithFields(log.Fields{ + "common": "this is a common field", + "other": "I also should be logged always", + }) + + contextLogger.Info("I'll be logged with common and other field") + contextLogger.Info("Me too") +} +``` + +For more advanced usage such as logging to multiple locations from the same +application, you can also create an instance of the `logrus` Logger: + +```go +package main + +import ( + "os" + "github.com/sirupsen/logrus" +) + +// Create a new instance of the logger. You can have any number of instances. +var log = logrus.New() + +func main() { + // The API for setting attributes is a little different than the package level + // exported logger. See Godoc. + log.Out = os.Stdout + + // You could set this to any `io.Writer` such as a file + // file, err := os.OpenFile("logrus.log", os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) + // if err == nil { + // log.Out = file + // } else { + // log.Info("Failed to log to file, using default stderr") + // } + + log.WithFields(logrus.Fields{ + "animal": "walrus", + "size": 10, + }).Info("A group of walrus emerges from the ocean") +} +``` + +#### Fields + +Logrus encourages careful, structured logging through logging fields instead of +long, unparseable error messages. For example, instead of: `log.Fatalf("Failed +to send event %s to topic %s with key %d")`, you should log the much more +discoverable: + +```go +log.WithFields(log.Fields{ + "event": event, + "topic": topic, + "key": key, +}).Fatal("Failed to send event") +``` + +We've found this API forces you to think about logging in a way that produces +much more useful logging messages. We've been in countless situations where just +a single added field to a log statement that was already there would've saved us +hours. The `WithFields` call is optional. + +In general, with Logrus using any of the `printf`-family functions should be +seen as a hint you should add a field, however, you can still use the +`printf`-family functions with Logrus. + +#### Default Fields + +Often it's helpful to have fields _always_ attached to log statements in an +application or parts of one. For example, you may want to always log the +`request_id` and `user_ip` in the context of a request. Instead of writing +`log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip})` on +every line, you can create a `logrus.Entry` to pass around instead: + +```go +requestLogger := log.WithFields(log.Fields{"request_id": request_id, "user_ip": user_ip}) +requestLogger.Info("something happened on that request") # will log request_id and user_ip +requestLogger.Warn("something not great happened") +``` + +#### Hooks + +You can add hooks for logging levels. For example to send errors to an exception +tracking service on `Error`, `Fatal` and `Panic`, info to StatsD or log to +multiple places simultaneously, e.g. syslog. + +Logrus comes with [built-in hooks](hooks/). Add those, or your custom hook, in +`init`: + +```go +import ( + log "github.com/sirupsen/logrus" + "gopkg.in/gemnasium/logrus-airbrake-hook.v2" // the package is named "airbrake" + logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" + "log/syslog" +) + +func init() { + + // Use the Airbrake hook to report errors that have Error severity or above to + // an exception tracker. You can create custom hooks, see the Hooks section. + log.AddHook(airbrake.NewHook(123, "xyz", "production")) + + hook, err := logrus_syslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") + if err != nil { + log.Error("Unable to connect to local syslog daemon") + } else { + log.AddHook(hook) + } +} +``` +Note: Syslog hook also support connecting to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). For the detail, please check the [syslog hook README](hooks/syslog/README.md). + +A list of currently known service hooks can be found in this wiki [page](https://github.com/sirupsen/logrus/wiki/Hooks) + + +#### Level logging + +Logrus has seven logging levels: Trace, Debug, Info, Warning, Error, Fatal and Panic. + +```go +log.Trace("Something very low level.") +log.Debug("Useful debugging information.") +log.Info("Something noteworthy happened!") +log.Warn("You should probably take a look at this.") +log.Error("Something failed but I'm not quitting.") +// Calls os.Exit(1) after logging +log.Fatal("Bye.") +// Calls panic() after logging +log.Panic("I'm bailing.") +``` + +You can set the logging level on a `Logger`, then it will only log entries with +that severity or anything above it: + +```go +// Will log anything that is info or above (warn, error, fatal, panic). Default. +log.SetLevel(log.InfoLevel) +``` + +It may be useful to set `log.Level = logrus.DebugLevel` in a debug or verbose +environment if your application has that. + +Note: If you want different log levels for global (`log.SetLevel(...)`) and syslog logging, please check the [syslog hook README](hooks/syslog/README.md#different-log-levels-for-local-and-remote-logging). + +#### Entries + +Besides the fields added with `WithField` or `WithFields` some fields are +automatically added to all logging events: + +1. `time`. The timestamp when the entry was created. +2. `msg`. The logging message passed to `{Info,Warn,Error,Fatal,Panic}` after + the `AddFields` call. E.g. `Failed to send event.` +3. `level`. The logging level. E.g. `info`. + +#### Environments + +Logrus has no notion of environment. + +If you wish for hooks and formatters to only be used in specific environments, +you should handle that yourself. For example, if your application has a global +variable `Environment`, which is a string representation of the environment you +could do: + +```go +import ( + log "github.com/sirupsen/logrus" +) + +func init() { + // do something here to set environment depending on an environment variable + // or command-line flag + if Environment == "production" { + log.SetFormatter(&log.JSONFormatter{}) + } else { + // The TextFormatter is default, you don't actually have to do this. + log.SetFormatter(&log.TextFormatter{}) + } +} +``` + +This configuration is how `logrus` was intended to be used, but JSON in +production is mostly only useful if you do log aggregation with tools like +Splunk or Logstash. + +#### Formatters + +The built-in logging formatters are: + +* `logrus.TextFormatter`. Logs the event in colors if stdout is a tty, otherwise + without colors. + * *Note:* to force colored output when there is no TTY, set the `ForceColors` + field to `true`. To force no colored output even if there is a TTY set the + `DisableColors` field to `true`. For Windows, see + [github.com/mattn/go-colorable](https://github.com/mattn/go-colorable). + * When colors are enabled, levels are truncated to 4 characters by default. To disable + truncation set the `DisableLevelTruncation` field to `true`. + * When outputting to a TTY, it's often helpful to visually scan down a column where all the levels are the same width. Setting the `PadLevelText` field to `true` enables this behavior, by adding padding to the level text. + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#TextFormatter). +* `logrus.JSONFormatter`. Logs fields as JSON. + * All options are listed in the [generated docs](https://godoc.org/github.com/sirupsen/logrus#JSONFormatter). + +Third party logging formatters: + +* [`FluentdFormatter`](https://github.com/joonix/log). Formats entries that can be parsed by Kubernetes and Google Container Engine. +* [`GELF`](https://github.com/fabienm/go-logrus-formatters). Formats entries so they comply to Graylog's [GELF 1.1 specification](http://docs.graylog.org/en/2.4/pages/gelf.html). +* [`logstash`](https://github.com/bshuster-repo/logrus-logstash-hook). Logs fields as [Logstash](http://logstash.net) Events. +* [`prefixed`](https://github.com/x-cray/logrus-prefixed-formatter). Displays log entry source along with alternative layout. +* [`zalgo`](https://github.com/aybabtme/logzalgo). Invoking the Power of Zalgo. +* [`nested-logrus-formatter`](https://github.com/antonfisher/nested-logrus-formatter). Converts logrus fields to a nested structure. +* [`powerful-logrus-formatter`](https://github.com/zput/zxcTool). get fileName, log's line number and the latest function's name when print log; Sava log to files. +* [`caption-json-formatter`](https://github.com/nolleh/caption_json_formatter). logrus's message json formatter with human-readable caption added. + +You can define your formatter by implementing the `Formatter` interface, +requiring a `Format` method. `Format` takes an `*Entry`. `entry.Data` is a +`Fields` type (`map[string]interface{}`) with all your fields as well as the +default ones (see Entries section above): + +```go +type MyJSONFormatter struct { +} + +log.SetFormatter(new(MyJSONFormatter)) + +func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) { + // Note this doesn't include Time, Level and Message which are available on + // the Entry. Consult `godoc` on information about those fields or read the + // source of the official loggers. + serialized, err := json.Marshal(entry.Data) + if err != nil { + return nil, fmt.Errorf("Failed to marshal fields to JSON, %w", err) + } + return append(serialized, '\n'), nil +} +``` + +#### Logger as an `io.Writer` + +Logrus can be transformed into an `io.Writer`. That writer is the end of an `io.Pipe` and it is your responsibility to close it. + +```go +w := logger.Writer() +defer w.Close() + +srv := http.Server{ + // create a stdlib log.Logger that writes to + // logrus.Logger. + ErrorLog: log.New(w, "", 0), +} +``` + +Each line written to that writer will be printed the usual way, using formatters +and hooks. The level for those entries is `info`. + +This means that we can override the standard library logger easily: + +```go +logger := logrus.New() +logger.Formatter = &logrus.JSONFormatter{} + +// Use logrus for standard log output +// Note that `log` here references stdlib's log +// Not logrus imported under the name `log`. +log.SetOutput(logger.Writer()) +``` + +#### Rotation + +Log rotation is not provided with Logrus. Log rotation should be done by an +external program (like `logrotate(8)`) that can compress and delete old log +entries. It should not be a feature of the application-level logger. + +#### Tools + +| Tool | Description | +| ---- | ----------- | +|[Logrus Mate](https://github.com/gogap/logrus_mate)|Logrus mate is a tool for Logrus to manage loggers, you can initial logger's level, hook and formatter by config file, the logger will be generated with different configs in different environments.| +|[Logrus Viper Helper](https://github.com/heirko/go-contrib/tree/master/logrusHelper)|An Helper around Logrus to wrap with spf13/Viper to load configuration with fangs! And to simplify Logrus configuration use some behavior of [Logrus Mate](https://github.com/gogap/logrus_mate). [sample](https://github.com/heirko/iris-contrib/blob/master/middleware/logrus-logger/example) | + +#### Testing + +Logrus has a built in facility for asserting the presence of log messages. This is implemented through the `test` hook and provides: + +* decorators for existing logger (`test.NewLocal` and `test.NewGlobal`) which basically just adds the `test` hook +* a test logger (`test.NewNullLogger`) that just records log messages (and does not output any): + +```go +import( + "github.com/sirupsen/logrus" + "github.com/sirupsen/logrus/hooks/test" + "github.com/stretchr/testify/assert" + "testing" +) + +func TestSomething(t*testing.T){ + logger, hook := test.NewNullLogger() + logger.Error("Helloerror") + + assert.Equal(t, 1, len(hook.Entries)) + assert.Equal(t, logrus.ErrorLevel, hook.LastEntry().Level) + assert.Equal(t, "Helloerror", hook.LastEntry().Message) + + hook.Reset() + assert.Nil(t, hook.LastEntry()) +} +``` + +#### Fatal handlers + +Logrus can register one or more functions that will be called when any `fatal` +level message is logged. The registered handlers will be executed before +logrus performs an `os.Exit(1)`. This behavior may be helpful if callers need +to gracefully shutdown. Unlike a `panic("Something went wrong...")` call which can be intercepted with a deferred `recover` a call to `os.Exit(1)` can not be intercepted. + +``` +... +handler := func() { + // gracefully shutdown something... +} +logrus.RegisterExitHandler(handler) +... +``` + +#### Thread safety + +By default, Logger is protected by a mutex for concurrent writes. The mutex is held when calling hooks and writing logs. +If you are sure such locking is not needed, you can call logger.SetNoLock() to disable the locking. + +Situation when locking is not needed includes: + +* You have no hooks registered, or hooks calling is already thread-safe. + +* Writing to logger.Out is already thread-safe, for example: + + 1) logger.Out is protected by locks. + + 2) logger.Out is an os.File handler opened with `O_APPEND` flag, and every write is smaller than 4k. (This allows multi-thread/multi-process writing) + + (Refer to http://www.notthewizard.com/2014/06/17/are-files-appends-really-atomic/) diff --git a/vendor/github.com/sirupsen/logrus/alt_exit.go b/vendor/github.com/sirupsen/logrus/alt_exit.go new file mode 100644 index 00000000..8fd189e1 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/alt_exit.go @@ -0,0 +1,76 @@ +package logrus + +// The following code was sourced and modified from the +// https://github.com/tebeka/atexit package governed by the following license: +// +// Copyright (c) 2012 Miki Tebeka . +// +// Permission is hereby granted, free of charge, to any person obtaining a copy of +// this software and associated documentation files (the "Software"), to deal in +// the Software without restriction, including without limitation the rights to +// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +// the Software, and to permit persons to whom the Software is furnished to do so, +// subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +import ( + "fmt" + "os" +) + +var handlers = []func(){} + +func runHandler(handler func()) { + defer func() { + if err := recover(); err != nil { + fmt.Fprintln(os.Stderr, "Error: Logrus exit handler error:", err) + } + }() + + handler() +} + +func runHandlers() { + for _, handler := range handlers { + runHandler(handler) + } +} + +// Exit runs all the Logrus atexit handlers and then terminates the program using os.Exit(code) +func Exit(code int) { + runHandlers() + os.Exit(code) +} + +// RegisterExitHandler appends a Logrus Exit handler to the list of handlers, +// call logrus.Exit to invoke all handlers. The handlers will also be invoked when +// any Fatal log entry is made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func RegisterExitHandler(handler func()) { + handlers = append(handlers, handler) +} + +// DeferExitHandler prepends a Logrus Exit handler to the list of handlers, +// call logrus.Exit to invoke all handlers. The handlers will also be invoked when +// any Fatal log entry is made. +// +// This method is useful when a caller wishes to use logrus to log a fatal +// message but also needs to gracefully shutdown. An example usecase could be +// closing database connections, or sending a alert that the application is +// closing. +func DeferExitHandler(handler func()) { + handlers = append([]func(){handler}, handlers...) +} diff --git a/vendor/github.com/sirupsen/logrus/appveyor.yml b/vendor/github.com/sirupsen/logrus/appveyor.yml new file mode 100644 index 00000000..df9d65c3 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/appveyor.yml @@ -0,0 +1,14 @@ +version: "{build}" +platform: x64 +clone_folder: c:\gopath\src\github.com\sirupsen\logrus +environment: + GOPATH: c:\gopath +branches: + only: + - master +install: + - set PATH=%GOPATH%\bin;c:\go\bin;%PATH% + - go version +build_script: + - go get -t + - go test diff --git a/vendor/github.com/sirupsen/logrus/buffer_pool.go b/vendor/github.com/sirupsen/logrus/buffer_pool.go new file mode 100644 index 00000000..c7787f77 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/buffer_pool.go @@ -0,0 +1,43 @@ +package logrus + +import ( + "bytes" + "sync" +) + +var ( + bufferPool BufferPool +) + +type BufferPool interface { + Put(*bytes.Buffer) + Get() *bytes.Buffer +} + +type defaultPool struct { + pool *sync.Pool +} + +func (p *defaultPool) Put(buf *bytes.Buffer) { + p.pool.Put(buf) +} + +func (p *defaultPool) Get() *bytes.Buffer { + return p.pool.Get().(*bytes.Buffer) +} + +// SetBufferPool allows to replace the default logrus buffer pool +// to better meets the specific needs of an application. +func SetBufferPool(bp BufferPool) { + bufferPool = bp +} + +func init() { + SetBufferPool(&defaultPool{ + pool: &sync.Pool{ + New: func() interface{} { + return new(bytes.Buffer) + }, + }, + }) +} diff --git a/vendor/github.com/sirupsen/logrus/doc.go b/vendor/github.com/sirupsen/logrus/doc.go new file mode 100644 index 00000000..da67aba0 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/doc.go @@ -0,0 +1,26 @@ +/* +Package logrus is a structured logger for Go, completely API compatible with the standard library logger. + + +The simplest way to use Logrus is simply the package-level exported logger: + + package main + + import ( + log "github.com/sirupsen/logrus" + ) + + func main() { + log.WithFields(log.Fields{ + "animal": "walrus", + "number": 1, + "size": 10, + }).Info("A walrus appears") + } + +Output: + time="2015-09-07T08:48:33Z" level=info msg="A walrus appears" animal=walrus number=1 size=10 + +For a full guide visit https://github.com/sirupsen/logrus +*/ +package logrus diff --git a/vendor/github.com/sirupsen/logrus/entry.go b/vendor/github.com/sirupsen/logrus/entry.go new file mode 100644 index 00000000..71cdbbc3 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/entry.go @@ -0,0 +1,442 @@ +package logrus + +import ( + "bytes" + "context" + "fmt" + "os" + "reflect" + "runtime" + "strings" + "sync" + "time" +) + +var ( + + // qualified package name, cached at first use + logrusPackage string + + // Positions in the call stack when tracing to report the calling method + minimumCallerDepth int + + // Used for caller information initialisation + callerInitOnce sync.Once +) + +const ( + maximumCallerDepth int = 25 + knownLogrusFrames int = 4 +) + +func init() { + // start at the bottom of the stack before the package-name cache is primed + minimumCallerDepth = 1 +} + +// Defines the key when adding errors using WithError. +var ErrorKey = "error" + +// An entry is the final or intermediate Logrus logging entry. It contains all +// the fields passed with WithField{,s}. It's finally logged when Trace, Debug, +// Info, Warn, Error, Fatal or Panic is called on it. These objects can be +// reused and passed around as much as you wish to avoid field duplication. +type Entry struct { + Logger *Logger + + // Contains all the fields set by the user. + Data Fields + + // Time at which the log entry was created + Time time.Time + + // Level the log entry was logged at: Trace, Debug, Info, Warn, Error, Fatal or Panic + // This field will be set on entry firing and the value will be equal to the one in Logger struct field. + Level Level + + // Calling method, with package name + Caller *runtime.Frame + + // Message passed to Trace, Debug, Info, Warn, Error, Fatal or Panic + Message string + + // When formatter is called in entry.log(), a Buffer may be set to entry + Buffer *bytes.Buffer + + // Contains the context set by the user. Useful for hook processing etc. + Context context.Context + + // err may contain a field formatting error + err string +} + +func NewEntry(logger *Logger) *Entry { + return &Entry{ + Logger: logger, + // Default is three fields, plus one optional. Give a little extra room. + Data: make(Fields, 6), + } +} + +func (entry *Entry) Dup() *Entry { + data := make(Fields, len(entry.Data)) + for k, v := range entry.Data { + data[k] = v + } + return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, Context: entry.Context, err: entry.err} +} + +// Returns the bytes representation of this entry from the formatter. +func (entry *Entry) Bytes() ([]byte, error) { + return entry.Logger.Formatter.Format(entry) +} + +// Returns the string representation from the reader and ultimately the +// formatter. +func (entry *Entry) String() (string, error) { + serialized, err := entry.Bytes() + if err != nil { + return "", err + } + str := string(serialized) + return str, nil +} + +// Add an error as single field (using the key defined in ErrorKey) to the Entry. +func (entry *Entry) WithError(err error) *Entry { + return entry.WithField(ErrorKey, err) +} + +// Add a context to the Entry. +func (entry *Entry) WithContext(ctx context.Context) *Entry { + dataCopy := make(Fields, len(entry.Data)) + for k, v := range entry.Data { + dataCopy[k] = v + } + return &Entry{Logger: entry.Logger, Data: dataCopy, Time: entry.Time, err: entry.err, Context: ctx} +} + +// Add a single field to the Entry. +func (entry *Entry) WithField(key string, value interface{}) *Entry { + return entry.WithFields(Fields{key: value}) +} + +// Add a map of fields to the Entry. +func (entry *Entry) WithFields(fields Fields) *Entry { + data := make(Fields, len(entry.Data)+len(fields)) + for k, v := range entry.Data { + data[k] = v + } + fieldErr := entry.err + for k, v := range fields { + isErrField := false + if t := reflect.TypeOf(v); t != nil { + switch { + case t.Kind() == reflect.Func, t.Kind() == reflect.Ptr && t.Elem().Kind() == reflect.Func: + isErrField = true + } + } + if isErrField { + tmp := fmt.Sprintf("can not add field %q", k) + if fieldErr != "" { + fieldErr = entry.err + ", " + tmp + } else { + fieldErr = tmp + } + } else { + data[k] = v + } + } + return &Entry{Logger: entry.Logger, Data: data, Time: entry.Time, err: fieldErr, Context: entry.Context} +} + +// Overrides the time of the Entry. +func (entry *Entry) WithTime(t time.Time) *Entry { + dataCopy := make(Fields, len(entry.Data)) + for k, v := range entry.Data { + dataCopy[k] = v + } + return &Entry{Logger: entry.Logger, Data: dataCopy, Time: t, err: entry.err, Context: entry.Context} +} + +// getPackageName reduces a fully qualified function name to the package name +// There really ought to be to be a better way... +func getPackageName(f string) string { + for { + lastPeriod := strings.LastIndex(f, ".") + lastSlash := strings.LastIndex(f, "/") + if lastPeriod > lastSlash { + f = f[:lastPeriod] + } else { + break + } + } + + return f +} + +// getCaller retrieves the name of the first non-logrus calling function +func getCaller() *runtime.Frame { + // cache this package's fully-qualified name + callerInitOnce.Do(func() { + pcs := make([]uintptr, maximumCallerDepth) + _ = runtime.Callers(0, pcs) + + // dynamic get the package name and the minimum caller depth + for i := 0; i < maximumCallerDepth; i++ { + funcName := runtime.FuncForPC(pcs[i]).Name() + if strings.Contains(funcName, "getCaller") { + logrusPackage = getPackageName(funcName) + break + } + } + + minimumCallerDepth = knownLogrusFrames + }) + + // Restrict the lookback frames to avoid runaway lookups + pcs := make([]uintptr, maximumCallerDepth) + depth := runtime.Callers(minimumCallerDepth, pcs) + frames := runtime.CallersFrames(pcs[:depth]) + + for f, again := frames.Next(); again; f, again = frames.Next() { + pkg := getPackageName(f.Function) + + // If the caller isn't part of this package, we're done + if pkg != logrusPackage { + return &f //nolint:scopelint + } + } + + // if we got here, we failed to find the caller's context + return nil +} + +func (entry Entry) HasCaller() (has bool) { + return entry.Logger != nil && + entry.Logger.ReportCaller && + entry.Caller != nil +} + +func (entry *Entry) log(level Level, msg string) { + var buffer *bytes.Buffer + + newEntry := entry.Dup() + + if newEntry.Time.IsZero() { + newEntry.Time = time.Now() + } + + newEntry.Level = level + newEntry.Message = msg + + newEntry.Logger.mu.Lock() + reportCaller := newEntry.Logger.ReportCaller + bufPool := newEntry.getBufferPool() + newEntry.Logger.mu.Unlock() + + if reportCaller { + newEntry.Caller = getCaller() + } + + newEntry.fireHooks() + buffer = bufPool.Get() + defer func() { + newEntry.Buffer = nil + buffer.Reset() + bufPool.Put(buffer) + }() + buffer.Reset() + newEntry.Buffer = buffer + + newEntry.write() + + newEntry.Buffer = nil + + // To avoid Entry#log() returning a value that only would make sense for + // panic() to use in Entry#Panic(), we avoid the allocation by checking + // directly here. + if level <= PanicLevel { + panic(newEntry) + } +} + +func (entry *Entry) getBufferPool() (pool BufferPool) { + if entry.Logger.BufferPool != nil { + return entry.Logger.BufferPool + } + return bufferPool +} + +func (entry *Entry) fireHooks() { + var tmpHooks LevelHooks + entry.Logger.mu.Lock() + tmpHooks = make(LevelHooks, len(entry.Logger.Hooks)) + for k, v := range entry.Logger.Hooks { + tmpHooks[k] = v + } + entry.Logger.mu.Unlock() + + err := tmpHooks.Fire(entry.Level, entry) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to fire hook: %v\n", err) + } +} + +func (entry *Entry) write() { + entry.Logger.mu.Lock() + defer entry.Logger.mu.Unlock() + serialized, err := entry.Logger.Formatter.Format(entry) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to obtain reader, %v\n", err) + return + } + if _, err := entry.Logger.Out.Write(serialized); err != nil { + fmt.Fprintf(os.Stderr, "Failed to write to log, %v\n", err) + } +} + +// Log will log a message at the level given as parameter. +// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. +// For this behaviour Entry.Panic or Entry.Fatal should be used instead. +func (entry *Entry) Log(level Level, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.log(level, fmt.Sprint(args...)) + } +} + +func (entry *Entry) Trace(args ...interface{}) { + entry.Log(TraceLevel, args...) +} + +func (entry *Entry) Debug(args ...interface{}) { + entry.Log(DebugLevel, args...) +} + +func (entry *Entry) Print(args ...interface{}) { + entry.Info(args...) +} + +func (entry *Entry) Info(args ...interface{}) { + entry.Log(InfoLevel, args...) +} + +func (entry *Entry) Warn(args ...interface{}) { + entry.Log(WarnLevel, args...) +} + +func (entry *Entry) Warning(args ...interface{}) { + entry.Warn(args...) +} + +func (entry *Entry) Error(args ...interface{}) { + entry.Log(ErrorLevel, args...) +} + +func (entry *Entry) Fatal(args ...interface{}) { + entry.Log(FatalLevel, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panic(args ...interface{}) { + entry.Log(PanicLevel, args...) +} + +// Entry Printf family functions + +func (entry *Entry) Logf(level Level, format string, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.Log(level, fmt.Sprintf(format, args...)) + } +} + +func (entry *Entry) Tracef(format string, args ...interface{}) { + entry.Logf(TraceLevel, format, args...) +} + +func (entry *Entry) Debugf(format string, args ...interface{}) { + entry.Logf(DebugLevel, format, args...) +} + +func (entry *Entry) Infof(format string, args ...interface{}) { + entry.Logf(InfoLevel, format, args...) +} + +func (entry *Entry) Printf(format string, args ...interface{}) { + entry.Infof(format, args...) +} + +func (entry *Entry) Warnf(format string, args ...interface{}) { + entry.Logf(WarnLevel, format, args...) +} + +func (entry *Entry) Warningf(format string, args ...interface{}) { + entry.Warnf(format, args...) +} + +func (entry *Entry) Errorf(format string, args ...interface{}) { + entry.Logf(ErrorLevel, format, args...) +} + +func (entry *Entry) Fatalf(format string, args ...interface{}) { + entry.Logf(FatalLevel, format, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panicf(format string, args ...interface{}) { + entry.Logf(PanicLevel, format, args...) +} + +// Entry Println family functions + +func (entry *Entry) Logln(level Level, args ...interface{}) { + if entry.Logger.IsLevelEnabled(level) { + entry.Log(level, entry.sprintlnn(args...)) + } +} + +func (entry *Entry) Traceln(args ...interface{}) { + entry.Logln(TraceLevel, args...) +} + +func (entry *Entry) Debugln(args ...interface{}) { + entry.Logln(DebugLevel, args...) +} + +func (entry *Entry) Infoln(args ...interface{}) { + entry.Logln(InfoLevel, args...) +} + +func (entry *Entry) Println(args ...interface{}) { + entry.Infoln(args...) +} + +func (entry *Entry) Warnln(args ...interface{}) { + entry.Logln(WarnLevel, args...) +} + +func (entry *Entry) Warningln(args ...interface{}) { + entry.Warnln(args...) +} + +func (entry *Entry) Errorln(args ...interface{}) { + entry.Logln(ErrorLevel, args...) +} + +func (entry *Entry) Fatalln(args ...interface{}) { + entry.Logln(FatalLevel, args...) + entry.Logger.Exit(1) +} + +func (entry *Entry) Panicln(args ...interface{}) { + entry.Logln(PanicLevel, args...) +} + +// Sprintlnn => Sprint no newline. This is to get the behavior of how +// fmt.Sprintln where spaces are always added between operands, regardless of +// their type. Instead of vendoring the Sprintln implementation to spare a +// string allocation, we do the simplest thing. +func (entry *Entry) sprintlnn(args ...interface{}) string { + msg := fmt.Sprintln(args...) + return msg[:len(msg)-1] +} diff --git a/vendor/github.com/sirupsen/logrus/exported.go b/vendor/github.com/sirupsen/logrus/exported.go new file mode 100644 index 00000000..017c30ce --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/exported.go @@ -0,0 +1,270 @@ +package logrus + +import ( + "context" + "io" + "time" +) + +var ( + // std is the name of the standard logger in stdlib `log` + std = New() +) + +func StandardLogger() *Logger { + return std +} + +// SetOutput sets the standard logger output. +func SetOutput(out io.Writer) { + std.SetOutput(out) +} + +// SetFormatter sets the standard logger formatter. +func SetFormatter(formatter Formatter) { + std.SetFormatter(formatter) +} + +// SetReportCaller sets whether the standard logger will include the calling +// method as a field. +func SetReportCaller(include bool) { + std.SetReportCaller(include) +} + +// SetLevel sets the standard logger level. +func SetLevel(level Level) { + std.SetLevel(level) +} + +// GetLevel returns the standard logger level. +func GetLevel() Level { + return std.GetLevel() +} + +// IsLevelEnabled checks if the log level of the standard logger is greater than the level param +func IsLevelEnabled(level Level) bool { + return std.IsLevelEnabled(level) +} + +// AddHook adds a hook to the standard logger hooks. +func AddHook(hook Hook) { + std.AddHook(hook) +} + +// WithError creates an entry from the standard logger and adds an error to it, using the value defined in ErrorKey as key. +func WithError(err error) *Entry { + return std.WithField(ErrorKey, err) +} + +// WithContext creates an entry from the standard logger and adds a context to it. +func WithContext(ctx context.Context) *Entry { + return std.WithContext(ctx) +} + +// WithField creates an entry from the standard logger and adds a field to +// it. If you want multiple fields, use `WithFields`. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithField(key string, value interface{}) *Entry { + return std.WithField(key, value) +} + +// WithFields creates an entry from the standard logger and adds multiple +// fields to it. This is simply a helper for `WithField`, invoking it +// once for each field. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithFields(fields Fields) *Entry { + return std.WithFields(fields) +} + +// WithTime creates an entry from the standard logger and overrides the time of +// logs generated with it. +// +// Note that it doesn't log until you call Debug, Print, Info, Warn, Fatal +// or Panic on the Entry it returns. +func WithTime(t time.Time) *Entry { + return std.WithTime(t) +} + +// Trace logs a message at level Trace on the standard logger. +func Trace(args ...interface{}) { + std.Trace(args...) +} + +// Debug logs a message at level Debug on the standard logger. +func Debug(args ...interface{}) { + std.Debug(args...) +} + +// Print logs a message at level Info on the standard logger. +func Print(args ...interface{}) { + std.Print(args...) +} + +// Info logs a message at level Info on the standard logger. +func Info(args ...interface{}) { + std.Info(args...) +} + +// Warn logs a message at level Warn on the standard logger. +func Warn(args ...interface{}) { + std.Warn(args...) +} + +// Warning logs a message at level Warn on the standard logger. +func Warning(args ...interface{}) { + std.Warning(args...) +} + +// Error logs a message at level Error on the standard logger. +func Error(args ...interface{}) { + std.Error(args...) +} + +// Panic logs a message at level Panic on the standard logger. +func Panic(args ...interface{}) { + std.Panic(args...) +} + +// Fatal logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatal(args ...interface{}) { + std.Fatal(args...) +} + +// TraceFn logs a message from a func at level Trace on the standard logger. +func TraceFn(fn LogFunction) { + std.TraceFn(fn) +} + +// DebugFn logs a message from a func at level Debug on the standard logger. +func DebugFn(fn LogFunction) { + std.DebugFn(fn) +} + +// PrintFn logs a message from a func at level Info on the standard logger. +func PrintFn(fn LogFunction) { + std.PrintFn(fn) +} + +// InfoFn logs a message from a func at level Info on the standard logger. +func InfoFn(fn LogFunction) { + std.InfoFn(fn) +} + +// WarnFn logs a message from a func at level Warn on the standard logger. +func WarnFn(fn LogFunction) { + std.WarnFn(fn) +} + +// WarningFn logs a message from a func at level Warn on the standard logger. +func WarningFn(fn LogFunction) { + std.WarningFn(fn) +} + +// ErrorFn logs a message from a func at level Error on the standard logger. +func ErrorFn(fn LogFunction) { + std.ErrorFn(fn) +} + +// PanicFn logs a message from a func at level Panic on the standard logger. +func PanicFn(fn LogFunction) { + std.PanicFn(fn) +} + +// FatalFn logs a message from a func at level Fatal on the standard logger then the process will exit with status set to 1. +func FatalFn(fn LogFunction) { + std.FatalFn(fn) +} + +// Tracef logs a message at level Trace on the standard logger. +func Tracef(format string, args ...interface{}) { + std.Tracef(format, args...) +} + +// Debugf logs a message at level Debug on the standard logger. +func Debugf(format string, args ...interface{}) { + std.Debugf(format, args...) +} + +// Printf logs a message at level Info on the standard logger. +func Printf(format string, args ...interface{}) { + std.Printf(format, args...) +} + +// Infof logs a message at level Info on the standard logger. +func Infof(format string, args ...interface{}) { + std.Infof(format, args...) +} + +// Warnf logs a message at level Warn on the standard logger. +func Warnf(format string, args ...interface{}) { + std.Warnf(format, args...) +} + +// Warningf logs a message at level Warn on the standard logger. +func Warningf(format string, args ...interface{}) { + std.Warningf(format, args...) +} + +// Errorf logs a message at level Error on the standard logger. +func Errorf(format string, args ...interface{}) { + std.Errorf(format, args...) +} + +// Panicf logs a message at level Panic on the standard logger. +func Panicf(format string, args ...interface{}) { + std.Panicf(format, args...) +} + +// Fatalf logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatalf(format string, args ...interface{}) { + std.Fatalf(format, args...) +} + +// Traceln logs a message at level Trace on the standard logger. +func Traceln(args ...interface{}) { + std.Traceln(args...) +} + +// Debugln logs a message at level Debug on the standard logger. +func Debugln(args ...interface{}) { + std.Debugln(args...) +} + +// Println logs a message at level Info on the standard logger. +func Println(args ...interface{}) { + std.Println(args...) +} + +// Infoln logs a message at level Info on the standard logger. +func Infoln(args ...interface{}) { + std.Infoln(args...) +} + +// Warnln logs a message at level Warn on the standard logger. +func Warnln(args ...interface{}) { + std.Warnln(args...) +} + +// Warningln logs a message at level Warn on the standard logger. +func Warningln(args ...interface{}) { + std.Warningln(args...) +} + +// Errorln logs a message at level Error on the standard logger. +func Errorln(args ...interface{}) { + std.Errorln(args...) +} + +// Panicln logs a message at level Panic on the standard logger. +func Panicln(args ...interface{}) { + std.Panicln(args...) +} + +// Fatalln logs a message at level Fatal on the standard logger then the process will exit with status set to 1. +func Fatalln(args ...interface{}) { + std.Fatalln(args...) +} diff --git a/vendor/github.com/sirupsen/logrus/formatter.go b/vendor/github.com/sirupsen/logrus/formatter.go new file mode 100644 index 00000000..40888377 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/formatter.go @@ -0,0 +1,78 @@ +package logrus + +import "time" + +// Default key names for the default fields +const ( + defaultTimestampFormat = time.RFC3339 + FieldKeyMsg = "msg" + FieldKeyLevel = "level" + FieldKeyTime = "time" + FieldKeyLogrusError = "logrus_error" + FieldKeyFunc = "func" + FieldKeyFile = "file" +) + +// The Formatter interface is used to implement a custom Formatter. It takes an +// `Entry`. It exposes all the fields, including the default ones: +// +// * `entry.Data["msg"]`. The message passed from Info, Warn, Error .. +// * `entry.Data["time"]`. The timestamp. +// * `entry.Data["level"]. The level the entry was logged at. +// +// Any additional fields added with `WithField` or `WithFields` are also in +// `entry.Data`. Format is expected to return an array of bytes which are then +// logged to `logger.Out`. +type Formatter interface { + Format(*Entry) ([]byte, error) +} + +// This is to not silently overwrite `time`, `msg`, `func` and `level` fields when +// dumping it. If this code wasn't there doing: +// +// logrus.WithField("level", 1).Info("hello") +// +// Would just silently drop the user provided level. Instead with this code +// it'll logged as: +// +// {"level": "info", "fields.level": 1, "msg": "hello", "time": "..."} +// +// It's not exported because it's still using Data in an opinionated way. It's to +// avoid code duplication between the two default formatters. +func prefixFieldClashes(data Fields, fieldMap FieldMap, reportCaller bool) { + timeKey := fieldMap.resolve(FieldKeyTime) + if t, ok := data[timeKey]; ok { + data["fields."+timeKey] = t + delete(data, timeKey) + } + + msgKey := fieldMap.resolve(FieldKeyMsg) + if m, ok := data[msgKey]; ok { + data["fields."+msgKey] = m + delete(data, msgKey) + } + + levelKey := fieldMap.resolve(FieldKeyLevel) + if l, ok := data[levelKey]; ok { + data["fields."+levelKey] = l + delete(data, levelKey) + } + + logrusErrKey := fieldMap.resolve(FieldKeyLogrusError) + if l, ok := data[logrusErrKey]; ok { + data["fields."+logrusErrKey] = l + delete(data, logrusErrKey) + } + + // If reportCaller is not set, 'func' will not conflict. + if reportCaller { + funcKey := fieldMap.resolve(FieldKeyFunc) + if l, ok := data[funcKey]; ok { + data["fields."+funcKey] = l + } + fileKey := fieldMap.resolve(FieldKeyFile) + if l, ok := data[fileKey]; ok { + data["fields."+fileKey] = l + } + } +} diff --git a/vendor/github.com/sirupsen/logrus/hooks.go b/vendor/github.com/sirupsen/logrus/hooks.go new file mode 100644 index 00000000..3f151cdc --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/hooks.go @@ -0,0 +1,34 @@ +package logrus + +// A hook to be fired when logging on the logging levels returned from +// `Levels()` on your implementation of the interface. Note that this is not +// fired in a goroutine or a channel with workers, you should handle such +// functionality yourself if your call is non-blocking and you don't wish for +// the logging calls for levels returned from `Levels()` to block. +type Hook interface { + Levels() []Level + Fire(*Entry) error +} + +// Internal type for storing the hooks on a logger instance. +type LevelHooks map[Level][]Hook + +// Add a hook to an instance of logger. This is called with +// `log.Hooks.Add(new(MyHook))` where `MyHook` implements the `Hook` interface. +func (hooks LevelHooks) Add(hook Hook) { + for _, level := range hook.Levels() { + hooks[level] = append(hooks[level], hook) + } +} + +// Fire all the hooks for the passed level. Used by `entry.log` to fire +// appropriate hooks for a log entry. +func (hooks LevelHooks) Fire(level Level, entry *Entry) error { + for _, hook := range hooks[level] { + if err := hook.Fire(entry); err != nil { + return err + } + } + + return nil +} diff --git a/vendor/github.com/sirupsen/logrus/json_formatter.go b/vendor/github.com/sirupsen/logrus/json_formatter.go new file mode 100644 index 00000000..c96dc563 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/json_formatter.go @@ -0,0 +1,128 @@ +package logrus + +import ( + "bytes" + "encoding/json" + "fmt" + "runtime" +) + +type fieldKey string + +// FieldMap allows customization of the key names for default fields. +type FieldMap map[fieldKey]string + +func (f FieldMap) resolve(key fieldKey) string { + if k, ok := f[key]; ok { + return k + } + + return string(key) +} + +// JSONFormatter formats logs into parsable json +type JSONFormatter struct { + // TimestampFormat sets the format used for marshaling timestamps. + // The format to use is the same than for time.Format or time.Parse from the standard + // library. + // The standard Library already provides a set of predefined format. + TimestampFormat string + + // DisableTimestamp allows disabling automatic timestamps in output + DisableTimestamp bool + + // DisableHTMLEscape allows disabling html escaping in output + DisableHTMLEscape bool + + // DataKey allows users to put all the log entry parameters into a nested dictionary at a given key. + DataKey string + + // FieldMap allows users to customize the names of keys for default fields. + // As an example: + // formatter := &JSONFormatter{ + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message", + // FieldKeyFunc: "@caller", + // }, + // } + FieldMap FieldMap + + // CallerPrettyfier can be set by the user to modify the content + // of the function and file keys in the json data when ReportCaller is + // activated. If any of the returned value is the empty string the + // corresponding key will be removed from json fields. + CallerPrettyfier func(*runtime.Frame) (function string, file string) + + // PrettyPrint will indent all json logs + PrettyPrint bool +} + +// Format renders a single log entry +func (f *JSONFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields, len(entry.Data)+4) + for k, v := range entry.Data { + switch v := v.(type) { + case error: + // Otherwise errors are ignored by `encoding/json` + // https://github.com/sirupsen/logrus/issues/137 + data[k] = v.Error() + default: + data[k] = v + } + } + + if f.DataKey != "" { + newData := make(Fields, 4) + newData[f.DataKey] = data + data = newData + } + + prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + + if entry.err != "" { + data[f.FieldMap.resolve(FieldKeyLogrusError)] = entry.err + } + if !f.DisableTimestamp { + data[f.FieldMap.resolve(FieldKeyTime)] = entry.Time.Format(timestampFormat) + } + data[f.FieldMap.resolve(FieldKeyMsg)] = entry.Message + data[f.FieldMap.resolve(FieldKeyLevel)] = entry.Level.String() + if entry.HasCaller() { + funcVal := entry.Caller.Function + fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } + if funcVal != "" { + data[f.FieldMap.resolve(FieldKeyFunc)] = funcVal + } + if fileVal != "" { + data[f.FieldMap.resolve(FieldKeyFile)] = fileVal + } + } + + var b *bytes.Buffer + if entry.Buffer != nil { + b = entry.Buffer + } else { + b = &bytes.Buffer{} + } + + encoder := json.NewEncoder(b) + encoder.SetEscapeHTML(!f.DisableHTMLEscape) + if f.PrettyPrint { + encoder.SetIndent("", " ") + } + if err := encoder.Encode(data); err != nil { + return nil, fmt.Errorf("failed to marshal fields to JSON, %w", err) + } + + return b.Bytes(), nil +} diff --git a/vendor/github.com/sirupsen/logrus/logger.go b/vendor/github.com/sirupsen/logrus/logger.go new file mode 100644 index 00000000..5ff0aef6 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/logger.go @@ -0,0 +1,417 @@ +package logrus + +import ( + "context" + "io" + "os" + "sync" + "sync/atomic" + "time" +) + +// LogFunction For big messages, it can be more efficient to pass a function +// and only call it if the log level is actually enables rather than +// generating the log message and then checking if the level is enabled +type LogFunction func() []interface{} + +type Logger struct { + // The logs are `io.Copy`'d to this in a mutex. It's common to set this to a + // file, or leave it default which is `os.Stderr`. You can also set this to + // something more adventurous, such as logging to Kafka. + Out io.Writer + // Hooks for the logger instance. These allow firing events based on logging + // levels and log entries. For example, to send errors to an error tracking + // service, log to StatsD or dump the core on fatal errors. + Hooks LevelHooks + // All log entries pass through the formatter before logged to Out. The + // included formatters are `TextFormatter` and `JSONFormatter` for which + // TextFormatter is the default. In development (when a TTY is attached) it + // logs with colors, but to a file it wouldn't. You can easily implement your + // own that implements the `Formatter` interface, see the `README` or included + // formatters for examples. + Formatter Formatter + + // Flag for whether to log caller info (off by default) + ReportCaller bool + + // The logging level the logger should log at. This is typically (and defaults + // to) `logrus.Info`, which allows Info(), Warn(), Error() and Fatal() to be + // logged. + Level Level + // Used to sync writing to the log. Locking is enabled by Default + mu MutexWrap + // Reusable empty entry + entryPool sync.Pool + // Function to exit the application, defaults to `os.Exit()` + ExitFunc exitFunc + // The buffer pool used to format the log. If it is nil, the default global + // buffer pool will be used. + BufferPool BufferPool +} + +type exitFunc func(int) + +type MutexWrap struct { + lock sync.Mutex + disabled bool +} + +func (mw *MutexWrap) Lock() { + if !mw.disabled { + mw.lock.Lock() + } +} + +func (mw *MutexWrap) Unlock() { + if !mw.disabled { + mw.lock.Unlock() + } +} + +func (mw *MutexWrap) Disable() { + mw.disabled = true +} + +// Creates a new logger. Configuration should be set by changing `Formatter`, +// `Out` and `Hooks` directly on the default logger instance. You can also just +// instantiate your own: +// +// var log = &logrus.Logger{ +// Out: os.Stderr, +// Formatter: new(logrus.TextFormatter), +// Hooks: make(logrus.LevelHooks), +// Level: logrus.DebugLevel, +// } +// +// It's recommended to make this a global instance called `log`. +func New() *Logger { + return &Logger{ + Out: os.Stderr, + Formatter: new(TextFormatter), + Hooks: make(LevelHooks), + Level: InfoLevel, + ExitFunc: os.Exit, + ReportCaller: false, + } +} + +func (logger *Logger) newEntry() *Entry { + entry, ok := logger.entryPool.Get().(*Entry) + if ok { + return entry + } + return NewEntry(logger) +} + +func (logger *Logger) releaseEntry(entry *Entry) { + entry.Data = map[string]interface{}{} + logger.entryPool.Put(entry) +} + +// WithField allocates a new entry and adds a field to it. +// Debug, Print, Info, Warn, Error, Fatal or Panic must be then applied to +// this new returned entry. +// If you want multiple fields, use `WithFields`. +func (logger *Logger) WithField(key string, value interface{}) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithField(key, value) +} + +// Adds a struct of fields to the log entry. All it does is call `WithField` for +// each `Field`. +func (logger *Logger) WithFields(fields Fields) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithFields(fields) +} + +// Add an error as single field to the log entry. All it does is call +// `WithError` for the given `error`. +func (logger *Logger) WithError(err error) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithError(err) +} + +// Add a context to the log entry. +func (logger *Logger) WithContext(ctx context.Context) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithContext(ctx) +} + +// Overrides the time of the log entry. +func (logger *Logger) WithTime(t time.Time) *Entry { + entry := logger.newEntry() + defer logger.releaseEntry(entry) + return entry.WithTime(t) +} + +func (logger *Logger) Logf(level Level, format string, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Logf(level, format, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Tracef(format string, args ...interface{}) { + logger.Logf(TraceLevel, format, args...) +} + +func (logger *Logger) Debugf(format string, args ...interface{}) { + logger.Logf(DebugLevel, format, args...) +} + +func (logger *Logger) Infof(format string, args ...interface{}) { + logger.Logf(InfoLevel, format, args...) +} + +func (logger *Logger) Printf(format string, args ...interface{}) { + entry := logger.newEntry() + entry.Printf(format, args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnf(format string, args ...interface{}) { + logger.Logf(WarnLevel, format, args...) +} + +func (logger *Logger) Warningf(format string, args ...interface{}) { + logger.Warnf(format, args...) +} + +func (logger *Logger) Errorf(format string, args ...interface{}) { + logger.Logf(ErrorLevel, format, args...) +} + +func (logger *Logger) Fatalf(format string, args ...interface{}) { + logger.Logf(FatalLevel, format, args...) + logger.Exit(1) +} + +func (logger *Logger) Panicf(format string, args ...interface{}) { + logger.Logf(PanicLevel, format, args...) +} + +// Log will log a message at the level given as parameter. +// Warning: using Log at Panic or Fatal level will not respectively Panic nor Exit. +// For this behaviour Logger.Panic or Logger.Fatal should be used instead. +func (logger *Logger) Log(level Level, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Log(level, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) LogFn(level Level, fn LogFunction) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Log(level, fn()...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Trace(args ...interface{}) { + logger.Log(TraceLevel, args...) +} + +func (logger *Logger) Debug(args ...interface{}) { + logger.Log(DebugLevel, args...) +} + +func (logger *Logger) Info(args ...interface{}) { + logger.Log(InfoLevel, args...) +} + +func (logger *Logger) Print(args ...interface{}) { + entry := logger.newEntry() + entry.Print(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warn(args ...interface{}) { + logger.Log(WarnLevel, args...) +} + +func (logger *Logger) Warning(args ...interface{}) { + logger.Warn(args...) +} + +func (logger *Logger) Error(args ...interface{}) { + logger.Log(ErrorLevel, args...) +} + +func (logger *Logger) Fatal(args ...interface{}) { + logger.Log(FatalLevel, args...) + logger.Exit(1) +} + +func (logger *Logger) Panic(args ...interface{}) { + logger.Log(PanicLevel, args...) +} + +func (logger *Logger) TraceFn(fn LogFunction) { + logger.LogFn(TraceLevel, fn) +} + +func (logger *Logger) DebugFn(fn LogFunction) { + logger.LogFn(DebugLevel, fn) +} + +func (logger *Logger) InfoFn(fn LogFunction) { + logger.LogFn(InfoLevel, fn) +} + +func (logger *Logger) PrintFn(fn LogFunction) { + entry := logger.newEntry() + entry.Print(fn()...) + logger.releaseEntry(entry) +} + +func (logger *Logger) WarnFn(fn LogFunction) { + logger.LogFn(WarnLevel, fn) +} + +func (logger *Logger) WarningFn(fn LogFunction) { + logger.WarnFn(fn) +} + +func (logger *Logger) ErrorFn(fn LogFunction) { + logger.LogFn(ErrorLevel, fn) +} + +func (logger *Logger) FatalFn(fn LogFunction) { + logger.LogFn(FatalLevel, fn) + logger.Exit(1) +} + +func (logger *Logger) PanicFn(fn LogFunction) { + logger.LogFn(PanicLevel, fn) +} + +func (logger *Logger) Logln(level Level, args ...interface{}) { + if logger.IsLevelEnabled(level) { + entry := logger.newEntry() + entry.Logln(level, args...) + logger.releaseEntry(entry) + } +} + +func (logger *Logger) Traceln(args ...interface{}) { + logger.Logln(TraceLevel, args...) +} + +func (logger *Logger) Debugln(args ...interface{}) { + logger.Logln(DebugLevel, args...) +} + +func (logger *Logger) Infoln(args ...interface{}) { + logger.Logln(InfoLevel, args...) +} + +func (logger *Logger) Println(args ...interface{}) { + entry := logger.newEntry() + entry.Println(args...) + logger.releaseEntry(entry) +} + +func (logger *Logger) Warnln(args ...interface{}) { + logger.Logln(WarnLevel, args...) +} + +func (logger *Logger) Warningln(args ...interface{}) { + logger.Warnln(args...) +} + +func (logger *Logger) Errorln(args ...interface{}) { + logger.Logln(ErrorLevel, args...) +} + +func (logger *Logger) Fatalln(args ...interface{}) { + logger.Logln(FatalLevel, args...) + logger.Exit(1) +} + +func (logger *Logger) Panicln(args ...interface{}) { + logger.Logln(PanicLevel, args...) +} + +func (logger *Logger) Exit(code int) { + runHandlers() + if logger.ExitFunc == nil { + logger.ExitFunc = os.Exit + } + logger.ExitFunc(code) +} + +//When file is opened with appending mode, it's safe to +//write concurrently to a file (within 4k message on Linux). +//In these cases user can choose to disable the lock. +func (logger *Logger) SetNoLock() { + logger.mu.Disable() +} + +func (logger *Logger) level() Level { + return Level(atomic.LoadUint32((*uint32)(&logger.Level))) +} + +// SetLevel sets the logger level. +func (logger *Logger) SetLevel(level Level) { + atomic.StoreUint32((*uint32)(&logger.Level), uint32(level)) +} + +// GetLevel returns the logger level. +func (logger *Logger) GetLevel() Level { + return logger.level() +} + +// AddHook adds a hook to the logger hooks. +func (logger *Logger) AddHook(hook Hook) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Hooks.Add(hook) +} + +// IsLevelEnabled checks if the log level of the logger is greater than the level param +func (logger *Logger) IsLevelEnabled(level Level) bool { + return logger.level() >= level +} + +// SetFormatter sets the logger formatter. +func (logger *Logger) SetFormatter(formatter Formatter) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Formatter = formatter +} + +// SetOutput sets the logger output. +func (logger *Logger) SetOutput(output io.Writer) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.Out = output +} + +func (logger *Logger) SetReportCaller(reportCaller bool) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.ReportCaller = reportCaller +} + +// ReplaceHooks replaces the logger hooks and returns the old ones +func (logger *Logger) ReplaceHooks(hooks LevelHooks) LevelHooks { + logger.mu.Lock() + oldHooks := logger.Hooks + logger.Hooks = hooks + logger.mu.Unlock() + return oldHooks +} + +// SetBufferPool sets the logger buffer pool. +func (logger *Logger) SetBufferPool(pool BufferPool) { + logger.mu.Lock() + defer logger.mu.Unlock() + logger.BufferPool = pool +} diff --git a/vendor/github.com/sirupsen/logrus/logrus.go b/vendor/github.com/sirupsen/logrus/logrus.go new file mode 100644 index 00000000..2f16224c --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/logrus.go @@ -0,0 +1,186 @@ +package logrus + +import ( + "fmt" + "log" + "strings" +) + +// Fields type, used to pass to `WithFields`. +type Fields map[string]interface{} + +// Level type +type Level uint32 + +// Convert the Level to a string. E.g. PanicLevel becomes "panic". +func (level Level) String() string { + if b, err := level.MarshalText(); err == nil { + return string(b) + } else { + return "unknown" + } +} + +// ParseLevel takes a string level and returns the Logrus log level constant. +func ParseLevel(lvl string) (Level, error) { + switch strings.ToLower(lvl) { + case "panic": + return PanicLevel, nil + case "fatal": + return FatalLevel, nil + case "error": + return ErrorLevel, nil + case "warn", "warning": + return WarnLevel, nil + case "info": + return InfoLevel, nil + case "debug": + return DebugLevel, nil + case "trace": + return TraceLevel, nil + } + + var l Level + return l, fmt.Errorf("not a valid logrus Level: %q", lvl) +} + +// UnmarshalText implements encoding.TextUnmarshaler. +func (level *Level) UnmarshalText(text []byte) error { + l, err := ParseLevel(string(text)) + if err != nil { + return err + } + + *level = l + + return nil +} + +func (level Level) MarshalText() ([]byte, error) { + switch level { + case TraceLevel: + return []byte("trace"), nil + case DebugLevel: + return []byte("debug"), nil + case InfoLevel: + return []byte("info"), nil + case WarnLevel: + return []byte("warning"), nil + case ErrorLevel: + return []byte("error"), nil + case FatalLevel: + return []byte("fatal"), nil + case PanicLevel: + return []byte("panic"), nil + } + + return nil, fmt.Errorf("not a valid logrus level %d", level) +} + +// A constant exposing all logging levels +var AllLevels = []Level{ + PanicLevel, + FatalLevel, + ErrorLevel, + WarnLevel, + InfoLevel, + DebugLevel, + TraceLevel, +} + +// These are the different logging levels. You can set the logging level to log +// on your instance of logger, obtained with `logrus.New()`. +const ( + // PanicLevel level, highest level of severity. Logs and then calls panic with the + // message passed to Debug, Info, ... + PanicLevel Level = iota + // FatalLevel level. Logs and then calls `logger.Exit(1)`. It will exit even if the + // logging level is set to Panic. + FatalLevel + // ErrorLevel level. Logs. Used for errors that should definitely be noted. + // Commonly used for hooks to send errors to an error tracking service. + ErrorLevel + // WarnLevel level. Non-critical entries that deserve eyes. + WarnLevel + // InfoLevel level. General operational entries about what's going on inside the + // application. + InfoLevel + // DebugLevel level. Usually only enabled when debugging. Very verbose logging. + DebugLevel + // TraceLevel level. Designates finer-grained informational events than the Debug. + TraceLevel +) + +// Won't compile if StdLogger can't be realized by a log.Logger +var ( + _ StdLogger = &log.Logger{} + _ StdLogger = &Entry{} + _ StdLogger = &Logger{} +) + +// StdLogger is what your logrus-enabled library should take, that way +// it'll accept a stdlib logger and a logrus logger. There's no standard +// interface, this is the closest we get, unfortunately. +type StdLogger interface { + Print(...interface{}) + Printf(string, ...interface{}) + Println(...interface{}) + + Fatal(...interface{}) + Fatalf(string, ...interface{}) + Fatalln(...interface{}) + + Panic(...interface{}) + Panicf(string, ...interface{}) + Panicln(...interface{}) +} + +// The FieldLogger interface generalizes the Entry and Logger types +type FieldLogger interface { + WithField(key string, value interface{}) *Entry + WithFields(fields Fields) *Entry + WithError(err error) *Entry + + Debugf(format string, args ...interface{}) + Infof(format string, args ...interface{}) + Printf(format string, args ...interface{}) + Warnf(format string, args ...interface{}) + Warningf(format string, args ...interface{}) + Errorf(format string, args ...interface{}) + Fatalf(format string, args ...interface{}) + Panicf(format string, args ...interface{}) + + Debug(args ...interface{}) + Info(args ...interface{}) + Print(args ...interface{}) + Warn(args ...interface{}) + Warning(args ...interface{}) + Error(args ...interface{}) + Fatal(args ...interface{}) + Panic(args ...interface{}) + + Debugln(args ...interface{}) + Infoln(args ...interface{}) + Println(args ...interface{}) + Warnln(args ...interface{}) + Warningln(args ...interface{}) + Errorln(args ...interface{}) + Fatalln(args ...interface{}) + Panicln(args ...interface{}) + + // IsDebugEnabled() bool + // IsInfoEnabled() bool + // IsWarnEnabled() bool + // IsErrorEnabled() bool + // IsFatalEnabled() bool + // IsPanicEnabled() bool +} + +// Ext1FieldLogger (the first extension to FieldLogger) is superfluous, it is +// here for consistancy. Do not use. Use Logger or Entry instead. +type Ext1FieldLogger interface { + FieldLogger + Tracef(format string, args ...interface{}) + Trace(args ...interface{}) + Traceln(args ...interface{}) +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go new file mode 100644 index 00000000..2403de98 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_appengine.go @@ -0,0 +1,11 @@ +// +build appengine + +package logrus + +import ( + "io" +) + +func checkIfTerminal(w io.Writer) bool { + return true +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go new file mode 100644 index 00000000..49978998 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_bsd.go @@ -0,0 +1,13 @@ +// +build darwin dragonfly freebsd netbsd openbsd +// +build !js + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TIOCGETA + +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) + return err == nil +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_js.go b/vendor/github.com/sirupsen/logrus/terminal_check_js.go new file mode 100644 index 00000000..ebdae3ec --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_js.go @@ -0,0 +1,7 @@ +// +build js + +package logrus + +func isTerminal(fd int) bool { + return false +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go new file mode 100644 index 00000000..97af92c6 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_no_terminal.go @@ -0,0 +1,11 @@ +// +build js nacl plan9 + +package logrus + +import ( + "io" +) + +func checkIfTerminal(w io.Writer) bool { + return false +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go new file mode 100644 index 00000000..3293fb3c --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_notappengine.go @@ -0,0 +1,17 @@ +// +build !appengine,!js,!windows,!nacl,!plan9 + +package logrus + +import ( + "io" + "os" +) + +func checkIfTerminal(w io.Writer) bool { + switch v := w.(type) { + case *os.File: + return isTerminal(int(v.Fd())) + default: + return false + } +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go new file mode 100644 index 00000000..f6710b3b --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_solaris.go @@ -0,0 +1,11 @@ +package logrus + +import ( + "golang.org/x/sys/unix" +) + +// IsTerminal returns true if the given file descriptor is a terminal. +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermio(fd, unix.TCGETA) + return err == nil +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_unix.go b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go new file mode 100644 index 00000000..04748b85 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_unix.go @@ -0,0 +1,13 @@ +// +build linux aix zos +// +build !js + +package logrus + +import "golang.org/x/sys/unix" + +const ioctlReadTermios = unix.TCGETS + +func isTerminal(fd int) bool { + _, err := unix.IoctlGetTermios(fd, ioctlReadTermios) + return err == nil +} diff --git a/vendor/github.com/sirupsen/logrus/terminal_check_windows.go b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go new file mode 100644 index 00000000..2879eb50 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/terminal_check_windows.go @@ -0,0 +1,27 @@ +// +build !appengine,!js,windows + +package logrus + +import ( + "io" + "os" + + "golang.org/x/sys/windows" +) + +func checkIfTerminal(w io.Writer) bool { + switch v := w.(type) { + case *os.File: + handle := windows.Handle(v.Fd()) + var mode uint32 + if err := windows.GetConsoleMode(handle, &mode); err != nil { + return false + } + mode |= windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING + if err := windows.SetConsoleMode(handle, mode); err != nil { + return false + } + return true + } + return false +} diff --git a/vendor/github.com/sirupsen/logrus/text_formatter.go b/vendor/github.com/sirupsen/logrus/text_formatter.go new file mode 100644 index 00000000..be2c6efe --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/text_formatter.go @@ -0,0 +1,339 @@ +package logrus + +import ( + "bytes" + "fmt" + "os" + "runtime" + "sort" + "strconv" + "strings" + "sync" + "time" + "unicode/utf8" +) + +const ( + red = 31 + yellow = 33 + blue = 36 + gray = 37 +) + +var baseTimestamp time.Time + +func init() { + baseTimestamp = time.Now() +} + +// TextFormatter formats logs into text +type TextFormatter struct { + // Set to true to bypass checking for a TTY before outputting colors. + ForceColors bool + + // Force disabling colors. + DisableColors bool + + // Force quoting of all values + ForceQuote bool + + // DisableQuote disables quoting for all values. + // DisableQuote will have a lower priority than ForceQuote. + // If both of them are set to true, quote will be forced on all values. + DisableQuote bool + + // Override coloring based on CLICOLOR and CLICOLOR_FORCE. - https://bixense.com/clicolors/ + EnvironmentOverrideColors bool + + // Disable timestamp logging. useful when output is redirected to logging + // system that already adds timestamps. + DisableTimestamp bool + + // Enable logging the full timestamp when a TTY is attached instead of just + // the time passed since beginning of execution. + FullTimestamp bool + + // TimestampFormat to use for display when a full timestamp is printed. + // The format to use is the same than for time.Format or time.Parse from the standard + // library. + // The standard Library already provides a set of predefined format. + TimestampFormat string + + // The fields are sorted by default for a consistent output. For applications + // that log extremely frequently and don't use the JSON formatter this may not + // be desired. + DisableSorting bool + + // The keys sorting function, when uninitialized it uses sort.Strings. + SortingFunc func([]string) + + // Disables the truncation of the level text to 4 characters. + DisableLevelTruncation bool + + // PadLevelText Adds padding the level text so that all the levels output at the same length + // PadLevelText is a superset of the DisableLevelTruncation option + PadLevelText bool + + // QuoteEmptyFields will wrap empty fields in quotes if true + QuoteEmptyFields bool + + // Whether the logger's out is to a terminal + isTerminal bool + + // FieldMap allows users to customize the names of keys for default fields. + // As an example: + // formatter := &TextFormatter{ + // FieldMap: FieldMap{ + // FieldKeyTime: "@timestamp", + // FieldKeyLevel: "@level", + // FieldKeyMsg: "@message"}} + FieldMap FieldMap + + // CallerPrettyfier can be set by the user to modify the content + // of the function and file keys in the data when ReportCaller is + // activated. If any of the returned value is the empty string the + // corresponding key will be removed from fields. + CallerPrettyfier func(*runtime.Frame) (function string, file string) + + terminalInitOnce sync.Once + + // The max length of the level text, generated dynamically on init + levelTextMaxLength int +} + +func (f *TextFormatter) init(entry *Entry) { + if entry.Logger != nil { + f.isTerminal = checkIfTerminal(entry.Logger.Out) + } + // Get the max length of the level text + for _, level := range AllLevels { + levelTextLength := utf8.RuneCount([]byte(level.String())) + if levelTextLength > f.levelTextMaxLength { + f.levelTextMaxLength = levelTextLength + } + } +} + +func (f *TextFormatter) isColored() bool { + isColored := f.ForceColors || (f.isTerminal && (runtime.GOOS != "windows")) + + if f.EnvironmentOverrideColors { + switch force, ok := os.LookupEnv("CLICOLOR_FORCE"); { + case ok && force != "0": + isColored = true + case ok && force == "0", os.Getenv("CLICOLOR") == "0": + isColored = false + } + } + + return isColored && !f.DisableColors +} + +// Format renders a single log entry +func (f *TextFormatter) Format(entry *Entry) ([]byte, error) { + data := make(Fields) + for k, v := range entry.Data { + data[k] = v + } + prefixFieldClashes(data, f.FieldMap, entry.HasCaller()) + keys := make([]string, 0, len(data)) + for k := range data { + keys = append(keys, k) + } + + var funcVal, fileVal string + + fixedKeys := make([]string, 0, 4+len(data)) + if !f.DisableTimestamp { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyTime)) + } + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLevel)) + if entry.Message != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyMsg)) + } + if entry.err != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyLogrusError)) + } + if entry.HasCaller() { + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } else { + funcVal = entry.Caller.Function + fileVal = fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + } + + if funcVal != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFunc)) + } + if fileVal != "" { + fixedKeys = append(fixedKeys, f.FieldMap.resolve(FieldKeyFile)) + } + } + + if !f.DisableSorting { + if f.SortingFunc == nil { + sort.Strings(keys) + fixedKeys = append(fixedKeys, keys...) + } else { + if !f.isColored() { + fixedKeys = append(fixedKeys, keys...) + f.SortingFunc(fixedKeys) + } else { + f.SortingFunc(keys) + } + } + } else { + fixedKeys = append(fixedKeys, keys...) + } + + var b *bytes.Buffer + if entry.Buffer != nil { + b = entry.Buffer + } else { + b = &bytes.Buffer{} + } + + f.terminalInitOnce.Do(func() { f.init(entry) }) + + timestampFormat := f.TimestampFormat + if timestampFormat == "" { + timestampFormat = defaultTimestampFormat + } + if f.isColored() { + f.printColored(b, entry, keys, data, timestampFormat) + } else { + + for _, key := range fixedKeys { + var value interface{} + switch { + case key == f.FieldMap.resolve(FieldKeyTime): + value = entry.Time.Format(timestampFormat) + case key == f.FieldMap.resolve(FieldKeyLevel): + value = entry.Level.String() + case key == f.FieldMap.resolve(FieldKeyMsg): + value = entry.Message + case key == f.FieldMap.resolve(FieldKeyLogrusError): + value = entry.err + case key == f.FieldMap.resolve(FieldKeyFunc) && entry.HasCaller(): + value = funcVal + case key == f.FieldMap.resolve(FieldKeyFile) && entry.HasCaller(): + value = fileVal + default: + value = data[key] + } + f.appendKeyValue(b, key, value) + } + } + + b.WriteByte('\n') + return b.Bytes(), nil +} + +func (f *TextFormatter) printColored(b *bytes.Buffer, entry *Entry, keys []string, data Fields, timestampFormat string) { + var levelColor int + switch entry.Level { + case DebugLevel, TraceLevel: + levelColor = gray + case WarnLevel: + levelColor = yellow + case ErrorLevel, FatalLevel, PanicLevel: + levelColor = red + case InfoLevel: + levelColor = blue + default: + levelColor = blue + } + + levelText := strings.ToUpper(entry.Level.String()) + if !f.DisableLevelTruncation && !f.PadLevelText { + levelText = levelText[0:4] + } + if f.PadLevelText { + // Generates the format string used in the next line, for example "%-6s" or "%-7s". + // Based on the max level text length. + formatString := "%-" + strconv.Itoa(f.levelTextMaxLength) + "s" + // Formats the level text by appending spaces up to the max length, for example: + // - "INFO " + // - "WARNING" + levelText = fmt.Sprintf(formatString, levelText) + } + + // Remove a single newline if it already exists in the message to keep + // the behavior of logrus text_formatter the same as the stdlib log package + entry.Message = strings.TrimSuffix(entry.Message, "\n") + + caller := "" + if entry.HasCaller() { + funcVal := fmt.Sprintf("%s()", entry.Caller.Function) + fileVal := fmt.Sprintf("%s:%d", entry.Caller.File, entry.Caller.Line) + + if f.CallerPrettyfier != nil { + funcVal, fileVal = f.CallerPrettyfier(entry.Caller) + } + + if fileVal == "" { + caller = funcVal + } else if funcVal == "" { + caller = fileVal + } else { + caller = fileVal + " " + funcVal + } + } + + switch { + case f.DisableTimestamp: + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m%s %-44s ", levelColor, levelText, caller, entry.Message) + case !f.FullTimestamp: + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%04d]%s %-44s ", levelColor, levelText, int(entry.Time.Sub(baseTimestamp)/time.Second), caller, entry.Message) + default: + fmt.Fprintf(b, "\x1b[%dm%s\x1b[0m[%s]%s %-44s ", levelColor, levelText, entry.Time.Format(timestampFormat), caller, entry.Message) + } + for _, k := range keys { + v := data[k] + fmt.Fprintf(b, " \x1b[%dm%s\x1b[0m=", levelColor, k) + f.appendValue(b, v) + } +} + +func (f *TextFormatter) needsQuoting(text string) bool { + if f.ForceQuote { + return true + } + if f.QuoteEmptyFields && len(text) == 0 { + return true + } + if f.DisableQuote { + return false + } + for _, ch := range text { + if !((ch >= 'a' && ch <= 'z') || + (ch >= 'A' && ch <= 'Z') || + (ch >= '0' && ch <= '9') || + ch == '-' || ch == '.' || ch == '_' || ch == '/' || ch == '@' || ch == '^' || ch == '+') { + return true + } + } + return false +} + +func (f *TextFormatter) appendKeyValue(b *bytes.Buffer, key string, value interface{}) { + if b.Len() > 0 { + b.WriteByte(' ') + } + b.WriteString(key) + b.WriteByte('=') + f.appendValue(b, value) +} + +func (f *TextFormatter) appendValue(b *bytes.Buffer, value interface{}) { + stringVal, ok := value.(string) + if !ok { + stringVal = fmt.Sprint(value) + } + + if !f.needsQuoting(stringVal) { + b.WriteString(stringVal) + } else { + b.WriteString(fmt.Sprintf("%q", stringVal)) + } +} diff --git a/vendor/github.com/sirupsen/logrus/writer.go b/vendor/github.com/sirupsen/logrus/writer.go new file mode 100644 index 00000000..074fd4b8 --- /dev/null +++ b/vendor/github.com/sirupsen/logrus/writer.go @@ -0,0 +1,102 @@ +package logrus + +import ( + "bufio" + "io" + "runtime" + "strings" +) + +// Writer at INFO level. See WriterLevel for details. +func (logger *Logger) Writer() *io.PipeWriter { + return logger.WriterLevel(InfoLevel) +} + +// WriterLevel returns an io.Writer that can be used to write arbitrary text to +// the logger at the given log level. Each line written to the writer will be +// printed in the usual way using formatters and hooks. The writer is part of an +// io.Pipe and it is the callers responsibility to close the writer when done. +// This can be used to override the standard library logger easily. +func (logger *Logger) WriterLevel(level Level) *io.PipeWriter { + return NewEntry(logger).WriterLevel(level) +} + +// Writer returns an io.Writer that writes to the logger at the info log level +func (entry *Entry) Writer() *io.PipeWriter { + return entry.WriterLevel(InfoLevel) +} + +// WriterLevel returns an io.Writer that writes to the logger at the given log level +func (entry *Entry) WriterLevel(level Level) *io.PipeWriter { + reader, writer := io.Pipe() + + var printFunc func(args ...interface{}) + + // Determine which log function to use based on the specified log level + switch level { + case TraceLevel: + printFunc = entry.Trace + case DebugLevel: + printFunc = entry.Debug + case InfoLevel: + printFunc = entry.Info + case WarnLevel: + printFunc = entry.Warn + case ErrorLevel: + printFunc = entry.Error + case FatalLevel: + printFunc = entry.Fatal + case PanicLevel: + printFunc = entry.Panic + default: + printFunc = entry.Print + } + + // Start a new goroutine to scan the input and write it to the logger using the specified print function. + // It splits the input into chunks of up to 64KB to avoid buffer overflows. + go entry.writerScanner(reader, printFunc) + + // Set a finalizer function to close the writer when it is garbage collected + runtime.SetFinalizer(writer, writerFinalizer) + + return writer +} + +// writerScanner scans the input from the reader and writes it to the logger +func (entry *Entry) writerScanner(reader *io.PipeReader, printFunc func(args ...interface{})) { + scanner := bufio.NewScanner(reader) + + // Set the buffer size to the maximum token size to avoid buffer overflows + scanner.Buffer(make([]byte, bufio.MaxScanTokenSize), bufio.MaxScanTokenSize) + + // Define a split function to split the input into chunks of up to 64KB + chunkSize := bufio.MaxScanTokenSize // 64KB + splitFunc := func(data []byte, atEOF bool) (int, []byte, error) { + if len(data) >= chunkSize { + return chunkSize, data[:chunkSize], nil + } + + return bufio.ScanLines(data, atEOF) + } + + // Use the custom split function to split the input + scanner.Split(splitFunc) + + // Scan the input and write it to the logger using the specified print function + for scanner.Scan() { + printFunc(strings.TrimRight(scanner.Text(), "\r\n")) + } + + // If there was an error while scanning the input, log an error + if err := scanner.Err(); err != nil { + entry.Errorf("Error while reading from Writer: %s", err) + } + + // Close the reader when we are done + reader.Close() +} + +// WriterFinalizer is a finalizer function that closes then given writer when it is garbage collected +func writerFinalizer(writer *io.PipeWriter) { + writer.Close() +} diff --git a/vendor/github.com/syndtr/gocapability/LICENSE b/vendor/github.com/syndtr/gocapability/LICENSE new file mode 100644 index 00000000..80dd96de --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/LICENSE @@ -0,0 +1,24 @@ +Copyright 2013 Suryandaru Triandana +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above copyright +notice, this list of conditions and the following disclaimer in the +documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/vendor/github.com/syndtr/gocapability/capability/capability.go b/vendor/github.com/syndtr/gocapability/capability/capability.go new file mode 100644 index 00000000..61a90775 --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/capability.go @@ -0,0 +1,133 @@ +// Copyright (c) 2013, Suryandaru Triandana +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// Package capability provides utilities for manipulating POSIX capabilities. +package capability + +type Capabilities interface { + // Get check whether a capability present in the given + // capabilities set. The 'which' value should be one of EFFECTIVE, + // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. + Get(which CapType, what Cap) bool + + // Empty check whether all capability bits of the given capabilities + // set are zero. The 'which' value should be one of EFFECTIVE, + // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. + Empty(which CapType) bool + + // Full check whether all capability bits of the given capabilities + // set are one. The 'which' value should be one of EFFECTIVE, + // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. + Full(which CapType) bool + + // Set sets capabilities of the given capabilities sets. The + // 'which' value should be one or combination (OR'ed) of EFFECTIVE, + // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. + Set(which CapType, caps ...Cap) + + // Unset unsets capabilities of the given capabilities sets. The + // 'which' value should be one or combination (OR'ed) of EFFECTIVE, + // PERMITTED, INHERITABLE, BOUNDING or AMBIENT. + Unset(which CapType, caps ...Cap) + + // Fill sets all bits of the given capabilities kind to one. The + // 'kind' value should be one or combination (OR'ed) of CAPS, + // BOUNDS or AMBS. + Fill(kind CapType) + + // Clear sets all bits of the given capabilities kind to zero. The + // 'kind' value should be one or combination (OR'ed) of CAPS, + // BOUNDS or AMBS. + Clear(kind CapType) + + // String return current capabilities state of the given capabilities + // set as string. The 'which' value should be one of EFFECTIVE, + // PERMITTED, INHERITABLE BOUNDING or AMBIENT + StringCap(which CapType) string + + // String return current capabilities state as string. + String() string + + // Load load actual capabilities value. This will overwrite all + // outstanding changes. + Load() error + + // Apply apply the capabilities settings, so all changes will take + // effect. + Apply(kind CapType) error +} + +// NewPid initializes a new Capabilities object for given pid when +// it is nonzero, or for the current process if pid is 0. +// +// Deprecated: Replace with NewPid2. For example, replace: +// +// c, err := NewPid(0) +// if err != nil { +// return err +// } +// +// with: +// +// c, err := NewPid2(0) +// if err != nil { +// return err +// } +// err = c.Load() +// if err != nil { +// return err +// } +func NewPid(pid int) (Capabilities, error) { + c, err := newPid(pid) + if err != nil { + return c, err + } + err = c.Load() + return c, err +} + +// NewPid2 initializes a new Capabilities object for given pid when +// it is nonzero, or for the current process if pid is 0. This +// does not load the process's current capabilities; to do that you +// must call Load explicitly. +func NewPid2(pid int) (Capabilities, error) { + return newPid(pid) +} + +// NewFile initializes a new Capabilities object for given file path. +// +// Deprecated: Replace with NewFile2. For example, replace: +// +// c, err := NewFile(path) +// if err != nil { +// return err +// } +// +// with: +// +// c, err := NewFile2(path) +// if err != nil { +// return err +// } +// err = c.Load() +// if err != nil { +// return err +// } +func NewFile(path string) (Capabilities, error) { + c, err := newFile(path) + if err != nil { + return c, err + } + err = c.Load() + return c, err +} + +// NewFile2 creates a new initialized Capabilities object for given +// file path. This does not load the process's current capabilities; +// to do that you must call Load explicitly. +func NewFile2(path string) (Capabilities, error) { + return newFile(path) +} diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_linux.go b/vendor/github.com/syndtr/gocapability/capability/capability_linux.go new file mode 100644 index 00000000..1567dc81 --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/capability_linux.go @@ -0,0 +1,642 @@ +// Copyright (c) 2013, Suryandaru Triandana +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package capability + +import ( + "bufio" + "errors" + "fmt" + "io" + "os" + "strings" + "syscall" +) + +var errUnknownVers = errors.New("unknown capability version") + +const ( + linuxCapVer1 = 0x19980330 + linuxCapVer2 = 0x20071026 + linuxCapVer3 = 0x20080522 +) + +var ( + capVers uint32 + capLastCap Cap +) + +func init() { + var hdr capHeader + capget(&hdr, nil) + capVers = hdr.version + + if initLastCap() == nil { + CAP_LAST_CAP = capLastCap + if capLastCap > 31 { + capUpperMask = (uint32(1) << (uint(capLastCap) - 31)) - 1 + } else { + capUpperMask = 0 + } + } +} + +func initLastCap() error { + if capLastCap != 0 { + return nil + } + + f, err := os.Open("/proc/sys/kernel/cap_last_cap") + if err != nil { + return err + } + defer f.Close() + + var b []byte = make([]byte, 11) + _, err = f.Read(b) + if err != nil { + return err + } + + fmt.Sscanf(string(b), "%d", &capLastCap) + + return nil +} + +func mkStringCap(c Capabilities, which CapType) (ret string) { + for i, first := Cap(0), true; i <= CAP_LAST_CAP; i++ { + if !c.Get(which, i) { + continue + } + if first { + first = false + } else { + ret += ", " + } + ret += i.String() + } + return +} + +func mkString(c Capabilities, max CapType) (ret string) { + ret = "{" + for i := CapType(1); i <= max; i <<= 1 { + ret += " " + i.String() + "=\"" + if c.Empty(i) { + ret += "empty" + } else if c.Full(i) { + ret += "full" + } else { + ret += c.StringCap(i) + } + ret += "\"" + } + ret += " }" + return +} + +func newPid(pid int) (c Capabilities, err error) { + switch capVers { + case linuxCapVer1: + p := new(capsV1) + p.hdr.version = capVers + p.hdr.pid = int32(pid) + c = p + case linuxCapVer2, linuxCapVer3: + p := new(capsV3) + p.hdr.version = capVers + p.hdr.pid = int32(pid) + c = p + default: + err = errUnknownVers + return + } + return +} + +type capsV1 struct { + hdr capHeader + data capData +} + +func (c *capsV1) Get(which CapType, what Cap) bool { + if what > 32 { + return false + } + + switch which { + case EFFECTIVE: + return (1< 32 { + continue + } + + if which&EFFECTIVE != 0 { + c.data.effective |= 1 << uint(what) + } + if which&PERMITTED != 0 { + c.data.permitted |= 1 << uint(what) + } + if which&INHERITABLE != 0 { + c.data.inheritable |= 1 << uint(what) + } + } +} + +func (c *capsV1) Unset(which CapType, caps ...Cap) { + for _, what := range caps { + if what > 32 { + continue + } + + if which&EFFECTIVE != 0 { + c.data.effective &= ^(1 << uint(what)) + } + if which&PERMITTED != 0 { + c.data.permitted &= ^(1 << uint(what)) + } + if which&INHERITABLE != 0 { + c.data.inheritable &= ^(1 << uint(what)) + } + } +} + +func (c *capsV1) Fill(kind CapType) { + if kind&CAPS == CAPS { + c.data.effective = 0x7fffffff + c.data.permitted = 0x7fffffff + c.data.inheritable = 0 + } +} + +func (c *capsV1) Clear(kind CapType) { + if kind&CAPS == CAPS { + c.data.effective = 0 + c.data.permitted = 0 + c.data.inheritable = 0 + } +} + +func (c *capsV1) StringCap(which CapType) (ret string) { + return mkStringCap(c, which) +} + +func (c *capsV1) String() (ret string) { + return mkString(c, BOUNDING) +} + +func (c *capsV1) Load() (err error) { + return capget(&c.hdr, &c.data) +} + +func (c *capsV1) Apply(kind CapType) error { + if kind&CAPS == CAPS { + return capset(&c.hdr, &c.data) + } + return nil +} + +type capsV3 struct { + hdr capHeader + data [2]capData + bounds [2]uint32 + ambient [2]uint32 +} + +func (c *capsV3) Get(which CapType, what Cap) bool { + var i uint + if what > 31 { + i = uint(what) >> 5 + what %= 32 + } + + switch which { + case EFFECTIVE: + return (1< 31 { + i = uint(what) >> 5 + what %= 32 + } + + if which&EFFECTIVE != 0 { + c.data[i].effective |= 1 << uint(what) + } + if which&PERMITTED != 0 { + c.data[i].permitted |= 1 << uint(what) + } + if which&INHERITABLE != 0 { + c.data[i].inheritable |= 1 << uint(what) + } + if which&BOUNDING != 0 { + c.bounds[i] |= 1 << uint(what) + } + if which&AMBIENT != 0 { + c.ambient[i] |= 1 << uint(what) + } + } +} + +func (c *capsV3) Unset(which CapType, caps ...Cap) { + for _, what := range caps { + var i uint + if what > 31 { + i = uint(what) >> 5 + what %= 32 + } + + if which&EFFECTIVE != 0 { + c.data[i].effective &= ^(1 << uint(what)) + } + if which&PERMITTED != 0 { + c.data[i].permitted &= ^(1 << uint(what)) + } + if which&INHERITABLE != 0 { + c.data[i].inheritable &= ^(1 << uint(what)) + } + if which&BOUNDING != 0 { + c.bounds[i] &= ^(1 << uint(what)) + } + if which&AMBIENT != 0 { + c.ambient[i] &= ^(1 << uint(what)) + } + } +} + +func (c *capsV3) Fill(kind CapType) { + if kind&CAPS == CAPS { + c.data[0].effective = 0xffffffff + c.data[0].permitted = 0xffffffff + c.data[0].inheritable = 0 + c.data[1].effective = 0xffffffff + c.data[1].permitted = 0xffffffff + c.data[1].inheritable = 0 + } + + if kind&BOUNDS == BOUNDS { + c.bounds[0] = 0xffffffff + c.bounds[1] = 0xffffffff + } + if kind&AMBS == AMBS { + c.ambient[0] = 0xffffffff + c.ambient[1] = 0xffffffff + } +} + +func (c *capsV3) Clear(kind CapType) { + if kind&CAPS == CAPS { + c.data[0].effective = 0 + c.data[0].permitted = 0 + c.data[0].inheritable = 0 + c.data[1].effective = 0 + c.data[1].permitted = 0 + c.data[1].inheritable = 0 + } + + if kind&BOUNDS == BOUNDS { + c.bounds[0] = 0 + c.bounds[1] = 0 + } + if kind&AMBS == AMBS { + c.ambient[0] = 0 + c.ambient[1] = 0 + } +} + +func (c *capsV3) StringCap(which CapType) (ret string) { + return mkStringCap(c, which) +} + +func (c *capsV3) String() (ret string) { + return mkString(c, BOUNDING) +} + +func (c *capsV3) Load() (err error) { + err = capget(&c.hdr, &c.data[0]) + if err != nil { + return + } + + var status_path string + + if c.hdr.pid == 0 { + status_path = fmt.Sprintf("/proc/self/status") + } else { + status_path = fmt.Sprintf("/proc/%d/status", c.hdr.pid) + } + + f, err := os.Open(status_path) + if err != nil { + return + } + b := bufio.NewReader(f) + for { + line, e := b.ReadString('\n') + if e != nil { + if e != io.EOF { + err = e + } + break + } + if strings.HasPrefix(line, "CapB") { + fmt.Sscanf(line[4:], "nd: %08x%08x", &c.bounds[1], &c.bounds[0]) + continue + } + if strings.HasPrefix(line, "CapA") { + fmt.Sscanf(line[4:], "mb: %08x%08x", &c.ambient[1], &c.ambient[0]) + continue + } + } + f.Close() + + return +} + +func (c *capsV3) Apply(kind CapType) (err error) { + if kind&BOUNDS == BOUNDS { + var data [2]capData + err = capget(&c.hdr, &data[0]) + if err != nil { + return + } + if (1< 31 { + if c.data.version == 1 { + return false + } + i = uint(what) >> 5 + what %= 32 + } + + switch which { + case EFFECTIVE: + return (1< 31 { + if c.data.version == 1 { + continue + } + i = uint(what) >> 5 + what %= 32 + } + + if which&EFFECTIVE != 0 { + c.data.effective[i] |= 1 << uint(what) + } + if which&PERMITTED != 0 { + c.data.data[i].permitted |= 1 << uint(what) + } + if which&INHERITABLE != 0 { + c.data.data[i].inheritable |= 1 << uint(what) + } + } +} + +func (c *capsFile) Unset(which CapType, caps ...Cap) { + for _, what := range caps { + var i uint + if what > 31 { + if c.data.version == 1 { + continue + } + i = uint(what) >> 5 + what %= 32 + } + + if which&EFFECTIVE != 0 { + c.data.effective[i] &= ^(1 << uint(what)) + } + if which&PERMITTED != 0 { + c.data.data[i].permitted &= ^(1 << uint(what)) + } + if which&INHERITABLE != 0 { + c.data.data[i].inheritable &= ^(1 << uint(what)) + } + } +} + +func (c *capsFile) Fill(kind CapType) { + if kind&CAPS == CAPS { + c.data.effective[0] = 0xffffffff + c.data.data[0].permitted = 0xffffffff + c.data.data[0].inheritable = 0 + if c.data.version == 2 { + c.data.effective[1] = 0xffffffff + c.data.data[1].permitted = 0xffffffff + c.data.data[1].inheritable = 0 + } + } +} + +func (c *capsFile) Clear(kind CapType) { + if kind&CAPS == CAPS { + c.data.effective[0] = 0 + c.data.data[0].permitted = 0 + c.data.data[0].inheritable = 0 + if c.data.version == 2 { + c.data.effective[1] = 0 + c.data.data[1].permitted = 0 + c.data.data[1].inheritable = 0 + } + } +} + +func (c *capsFile) StringCap(which CapType) (ret string) { + return mkStringCap(c, which) +} + +func (c *capsFile) String() (ret string) { + return mkString(c, INHERITABLE) +} + +func (c *capsFile) Load() (err error) { + return getVfsCap(c.path, &c.data) +} + +func (c *capsFile) Apply(kind CapType) (err error) { + if kind&CAPS == CAPS { + return setVfsCap(c.path, &c.data) + } + return +} diff --git a/vendor/github.com/syndtr/gocapability/capability/capability_noop.go b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go new file mode 100644 index 00000000..9bb3070c --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/capability_noop.go @@ -0,0 +1,19 @@ +// Copyright (c) 2013, Suryandaru Triandana +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// +build !linux + +package capability + +import "errors" + +func newPid(pid int) (Capabilities, error) { + return nil, errors.New("not supported") +} + +func newFile(path string) (Capabilities, error) { + return nil, errors.New("not supported") +} diff --git a/vendor/github.com/syndtr/gocapability/capability/enum.go b/vendor/github.com/syndtr/gocapability/capability/enum.go new file mode 100644 index 00000000..ad107853 --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/enum.go @@ -0,0 +1,309 @@ +// Copyright (c) 2013, Suryandaru Triandana +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package capability + +type CapType uint + +func (c CapType) String() string { + switch c { + case EFFECTIVE: + return "effective" + case PERMITTED: + return "permitted" + case INHERITABLE: + return "inheritable" + case BOUNDING: + return "bounding" + case CAPS: + return "caps" + case AMBIENT: + return "ambient" + } + return "unknown" +} + +const ( + EFFECTIVE CapType = 1 << iota + PERMITTED + INHERITABLE + BOUNDING + AMBIENT + + CAPS = EFFECTIVE | PERMITTED | INHERITABLE + BOUNDS = BOUNDING + AMBS = AMBIENT +) + +//go:generate go run enumgen/gen.go +type Cap int + +// POSIX-draft defined capabilities and Linux extensions. +// +// Defined in https://github.com/torvalds/linux/blob/master/include/uapi/linux/capability.h +const ( + // In a system with the [_POSIX_CHOWN_RESTRICTED] option defined, this + // overrides the restriction of changing file ownership and group + // ownership. + CAP_CHOWN = Cap(0) + + // Override all DAC access, including ACL execute access if + // [_POSIX_ACL] is defined. Excluding DAC access covered by + // CAP_LINUX_IMMUTABLE. + CAP_DAC_OVERRIDE = Cap(1) + + // Overrides all DAC restrictions regarding read and search on files + // and directories, including ACL restrictions if [_POSIX_ACL] is + // defined. Excluding DAC access covered by CAP_LINUX_IMMUTABLE. + CAP_DAC_READ_SEARCH = Cap(2) + + // Overrides all restrictions about allowed operations on files, where + // file owner ID must be equal to the user ID, except where CAP_FSETID + // is applicable. It doesn't override MAC and DAC restrictions. + CAP_FOWNER = Cap(3) + + // Overrides the following restrictions that the effective user ID + // shall match the file owner ID when setting the S_ISUID and S_ISGID + // bits on that file; that the effective group ID (or one of the + // supplementary group IDs) shall match the file owner ID when setting + // the S_ISGID bit on that file; that the S_ISUID and S_ISGID bits are + // cleared on successful return from chown(2) (not implemented). + CAP_FSETID = Cap(4) + + // Overrides the restriction that the real or effective user ID of a + // process sending a signal must match the real or effective user ID + // of the process receiving the signal. + CAP_KILL = Cap(5) + + // Allows setgid(2) manipulation + // Allows setgroups(2) + // Allows forged gids on socket credentials passing. + CAP_SETGID = Cap(6) + + // Allows set*uid(2) manipulation (including fsuid). + // Allows forged pids on socket credentials passing. + CAP_SETUID = Cap(7) + + // Linux-specific capabilities + + // Without VFS support for capabilities: + // Transfer any capability in your permitted set to any pid, + // remove any capability in your permitted set from any pid + // With VFS support for capabilities (neither of above, but) + // Add any capability from current's capability bounding set + // to the current process' inheritable set + // Allow taking bits out of capability bounding set + // Allow modification of the securebits for a process + CAP_SETPCAP = Cap(8) + + // Allow modification of S_IMMUTABLE and S_APPEND file attributes + CAP_LINUX_IMMUTABLE = Cap(9) + + // Allows binding to TCP/UDP sockets below 1024 + // Allows binding to ATM VCIs below 32 + CAP_NET_BIND_SERVICE = Cap(10) + + // Allow broadcasting, listen to multicast + CAP_NET_BROADCAST = Cap(11) + + // Allow interface configuration + // Allow administration of IP firewall, masquerading and accounting + // Allow setting debug option on sockets + // Allow modification of routing tables + // Allow setting arbitrary process / process group ownership on + // sockets + // Allow binding to any address for transparent proxying (also via NET_RAW) + // Allow setting TOS (type of service) + // Allow setting promiscuous mode + // Allow clearing driver statistics + // Allow multicasting + // Allow read/write of device-specific registers + // Allow activation of ATM control sockets + CAP_NET_ADMIN = Cap(12) + + // Allow use of RAW sockets + // Allow use of PACKET sockets + // Allow binding to any address for transparent proxying (also via NET_ADMIN) + CAP_NET_RAW = Cap(13) + + // Allow locking of shared memory segments + // Allow mlock and mlockall (which doesn't really have anything to do + // with IPC) + CAP_IPC_LOCK = Cap(14) + + // Override IPC ownership checks + CAP_IPC_OWNER = Cap(15) + + // Insert and remove kernel modules - modify kernel without limit + CAP_SYS_MODULE = Cap(16) + + // Allow ioperm/iopl access + // Allow sending USB messages to any device via /proc/bus/usb + CAP_SYS_RAWIO = Cap(17) + + // Allow use of chroot() + CAP_SYS_CHROOT = Cap(18) + + // Allow ptrace() of any process + CAP_SYS_PTRACE = Cap(19) + + // Allow configuration of process accounting + CAP_SYS_PACCT = Cap(20) + + // Allow configuration of the secure attention key + // Allow administration of the random device + // Allow examination and configuration of disk quotas + // Allow setting the domainname + // Allow setting the hostname + // Allow calling bdflush() + // Allow mount() and umount(), setting up new smb connection + // Allow some autofs root ioctls + // Allow nfsservctl + // Allow VM86_REQUEST_IRQ + // Allow to read/write pci config on alpha + // Allow irix_prctl on mips (setstacksize) + // Allow flushing all cache on m68k (sys_cacheflush) + // Allow removing semaphores + // Used instead of CAP_CHOWN to "chown" IPC message queues, semaphores + // and shared memory + // Allow locking/unlocking of shared memory segment + // Allow turning swap on/off + // Allow forged pids on socket credentials passing + // Allow setting readahead and flushing buffers on block devices + // Allow setting geometry in floppy driver + // Allow turning DMA on/off in xd driver + // Allow administration of md devices (mostly the above, but some + // extra ioctls) + // Allow tuning the ide driver + // Allow access to the nvram device + // Allow administration of apm_bios, serial and bttv (TV) device + // Allow manufacturer commands in isdn CAPI support driver + // Allow reading non-standardized portions of pci configuration space + // Allow DDI debug ioctl on sbpcd driver + // Allow setting up serial ports + // Allow sending raw qic-117 commands + // Allow enabling/disabling tagged queuing on SCSI controllers and sending + // arbitrary SCSI commands + // Allow setting encryption key on loopback filesystem + // Allow setting zone reclaim policy + // Allow everything under CAP_BPF and CAP_PERFMON for backward compatibility + CAP_SYS_ADMIN = Cap(21) + + // Allow use of reboot() + CAP_SYS_BOOT = Cap(22) + + // Allow raising priority and setting priority on other (different + // UID) processes + // Allow use of FIFO and round-robin (realtime) scheduling on own + // processes and setting the scheduling algorithm used by another + // process. + // Allow setting cpu affinity on other processes + CAP_SYS_NICE = Cap(23) + + // Override resource limits. Set resource limits. + // Override quota limits. + // Override reserved space on ext2 filesystem + // Modify data journaling mode on ext3 filesystem (uses journaling + // resources) + // NOTE: ext2 honors fsuid when checking for resource overrides, so + // you can override using fsuid too + // Override size restrictions on IPC message queues + // Allow more than 64hz interrupts from the real-time clock + // Override max number of consoles on console allocation + // Override max number of keymaps + // Control memory reclaim behavior + CAP_SYS_RESOURCE = Cap(24) + + // Allow manipulation of system clock + // Allow irix_stime on mips + // Allow setting the real-time clock + CAP_SYS_TIME = Cap(25) + + // Allow configuration of tty devices + // Allow vhangup() of tty + CAP_SYS_TTY_CONFIG = Cap(26) + + // Allow the privileged aspects of mknod() + CAP_MKNOD = Cap(27) + + // Allow taking of leases on files + CAP_LEASE = Cap(28) + + CAP_AUDIT_WRITE = Cap(29) + CAP_AUDIT_CONTROL = Cap(30) + CAP_SETFCAP = Cap(31) + + // Override MAC access. + // The base kernel enforces no MAC policy. + // An LSM may enforce a MAC policy, and if it does and it chooses + // to implement capability based overrides of that policy, this is + // the capability it should use to do so. + CAP_MAC_OVERRIDE = Cap(32) + + // Allow MAC configuration or state changes. + // The base kernel requires no MAC configuration. + // An LSM may enforce a MAC policy, and if it does and it chooses + // to implement capability based checks on modifications to that + // policy or the data required to maintain it, this is the + // capability it should use to do so. + CAP_MAC_ADMIN = Cap(33) + + // Allow configuring the kernel's syslog (printk behaviour) + CAP_SYSLOG = Cap(34) + + // Allow triggering something that will wake the system + CAP_WAKE_ALARM = Cap(35) + + // Allow preventing system suspends + CAP_BLOCK_SUSPEND = Cap(36) + + // Allow reading the audit log via multicast netlink socket + CAP_AUDIT_READ = Cap(37) + + // Allow system performance and observability privileged operations + // using perf_events, i915_perf and other kernel subsystems + CAP_PERFMON = Cap(38) + + // CAP_BPF allows the following BPF operations: + // - Creating all types of BPF maps + // - Advanced verifier features + // - Indirect variable access + // - Bounded loops + // - BPF to BPF function calls + // - Scalar precision tracking + // - Larger complexity limits + // - Dead code elimination + // - And potentially other features + // - Loading BPF Type Format (BTF) data + // - Retrieve xlated and JITed code of BPF programs + // - Use bpf_spin_lock() helper + // + // CAP_PERFMON relaxes the verifier checks further: + // - BPF progs can use of pointer-to-integer conversions + // - speculation attack hardening measures are bypassed + // - bpf_probe_read to read arbitrary kernel memory is allowed + // - bpf_trace_printk to print kernel memory is allowed + // + // CAP_SYS_ADMIN is required to use bpf_probe_write_user. + // + // CAP_SYS_ADMIN is required to iterate system wide loaded + // programs, maps, links, BTFs and convert their IDs to file descriptors. + // + // CAP_PERFMON and CAP_BPF are required to load tracing programs. + // CAP_NET_ADMIN and CAP_BPF are required to load networking programs. + CAP_BPF = Cap(39) + + // Allow checkpoint/restore related operations. + // Introduced in kernel 5.9 + CAP_CHECKPOINT_RESTORE = Cap(40) +) + +var ( + // Highest valid capability of the running kernel. + CAP_LAST_CAP = Cap(63) + + capUpperMask = ^uint32(0) +) diff --git a/vendor/github.com/syndtr/gocapability/capability/enum_gen.go b/vendor/github.com/syndtr/gocapability/capability/enum_gen.go new file mode 100644 index 00000000..2ff9bf4d --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/enum_gen.go @@ -0,0 +1,138 @@ +// generated file; DO NOT EDIT - use go generate in directory with source + +package capability + +func (c Cap) String() string { + switch c { + case CAP_CHOWN: + return "chown" + case CAP_DAC_OVERRIDE: + return "dac_override" + case CAP_DAC_READ_SEARCH: + return "dac_read_search" + case CAP_FOWNER: + return "fowner" + case CAP_FSETID: + return "fsetid" + case CAP_KILL: + return "kill" + case CAP_SETGID: + return "setgid" + case CAP_SETUID: + return "setuid" + case CAP_SETPCAP: + return "setpcap" + case CAP_LINUX_IMMUTABLE: + return "linux_immutable" + case CAP_NET_BIND_SERVICE: + return "net_bind_service" + case CAP_NET_BROADCAST: + return "net_broadcast" + case CAP_NET_ADMIN: + return "net_admin" + case CAP_NET_RAW: + return "net_raw" + case CAP_IPC_LOCK: + return "ipc_lock" + case CAP_IPC_OWNER: + return "ipc_owner" + case CAP_SYS_MODULE: + return "sys_module" + case CAP_SYS_RAWIO: + return "sys_rawio" + case CAP_SYS_CHROOT: + return "sys_chroot" + case CAP_SYS_PTRACE: + return "sys_ptrace" + case CAP_SYS_PACCT: + return "sys_pacct" + case CAP_SYS_ADMIN: + return "sys_admin" + case CAP_SYS_BOOT: + return "sys_boot" + case CAP_SYS_NICE: + return "sys_nice" + case CAP_SYS_RESOURCE: + return "sys_resource" + case CAP_SYS_TIME: + return "sys_time" + case CAP_SYS_TTY_CONFIG: + return "sys_tty_config" + case CAP_MKNOD: + return "mknod" + case CAP_LEASE: + return "lease" + case CAP_AUDIT_WRITE: + return "audit_write" + case CAP_AUDIT_CONTROL: + return "audit_control" + case CAP_SETFCAP: + return "setfcap" + case CAP_MAC_OVERRIDE: + return "mac_override" + case CAP_MAC_ADMIN: + return "mac_admin" + case CAP_SYSLOG: + return "syslog" + case CAP_WAKE_ALARM: + return "wake_alarm" + case CAP_BLOCK_SUSPEND: + return "block_suspend" + case CAP_AUDIT_READ: + return "audit_read" + case CAP_PERFMON: + return "perfmon" + case CAP_BPF: + return "bpf" + case CAP_CHECKPOINT_RESTORE: + return "checkpoint_restore" + } + return "unknown" +} + +// List returns list of all supported capabilities +func List() []Cap { + return []Cap{ + CAP_CHOWN, + CAP_DAC_OVERRIDE, + CAP_DAC_READ_SEARCH, + CAP_FOWNER, + CAP_FSETID, + CAP_KILL, + CAP_SETGID, + CAP_SETUID, + CAP_SETPCAP, + CAP_LINUX_IMMUTABLE, + CAP_NET_BIND_SERVICE, + CAP_NET_BROADCAST, + CAP_NET_ADMIN, + CAP_NET_RAW, + CAP_IPC_LOCK, + CAP_IPC_OWNER, + CAP_SYS_MODULE, + CAP_SYS_RAWIO, + CAP_SYS_CHROOT, + CAP_SYS_PTRACE, + CAP_SYS_PACCT, + CAP_SYS_ADMIN, + CAP_SYS_BOOT, + CAP_SYS_NICE, + CAP_SYS_RESOURCE, + CAP_SYS_TIME, + CAP_SYS_TTY_CONFIG, + CAP_MKNOD, + CAP_LEASE, + CAP_AUDIT_WRITE, + CAP_AUDIT_CONTROL, + CAP_SETFCAP, + CAP_MAC_OVERRIDE, + CAP_MAC_ADMIN, + CAP_SYSLOG, + CAP_WAKE_ALARM, + CAP_BLOCK_SUSPEND, + CAP_AUDIT_READ, + CAP_PERFMON, + CAP_BPF, + CAP_CHECKPOINT_RESTORE, + } +} diff --git a/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go b/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go new file mode 100644 index 00000000..3d2bf692 --- /dev/null +++ b/vendor/github.com/syndtr/gocapability/capability/syscall_linux.go @@ -0,0 +1,154 @@ +// Copyright (c) 2013, Suryandaru Triandana +// All rights reserved. +// +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +package capability + +import ( + "syscall" + "unsafe" +) + +type capHeader struct { + version uint32 + pid int32 +} + +type capData struct { + effective uint32 + permitted uint32 + inheritable uint32 +} + +func capget(hdr *capHeader, data *capData) (err error) { + _, _, e1 := syscall.Syscall(syscall.SYS_CAPGET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) + if e1 != 0 { + err = e1 + } + return +} + +func capset(hdr *capHeader, data *capData) (err error) { + _, _, e1 := syscall.Syscall(syscall.SYS_CAPSET, uintptr(unsafe.Pointer(hdr)), uintptr(unsafe.Pointer(data)), 0) + if e1 != 0 { + err = e1 + } + return +} + +// not yet in syscall +const ( + pr_CAP_AMBIENT = 47 + pr_CAP_AMBIENT_IS_SET = uintptr(1) + pr_CAP_AMBIENT_RAISE = uintptr(2) + pr_CAP_AMBIENT_LOWER = uintptr(3) + pr_CAP_AMBIENT_CLEAR_ALL = uintptr(4) +) + +func prctl(option int, arg2, arg3, arg4, arg5 uintptr) (err error) { + _, _, e1 := syscall.Syscall6(syscall.SYS_PRCTL, uintptr(option), arg2, arg3, arg4, arg5, 0) + if e1 != 0 { + err = e1 + } + return +} + +const ( + vfsXattrName = "security.capability" + + vfsCapVerMask = 0xff000000 + vfsCapVer1 = 0x01000000 + vfsCapVer2 = 0x02000000 + + vfsCapFlagMask = ^vfsCapVerMask + vfsCapFlageffective = 0x000001 + + vfscapDataSizeV1 = 4 * (1 + 2*1) + vfscapDataSizeV2 = 4 * (1 + 2*2) +) + +type vfscapData struct { + magic uint32 + data [2]struct { + permitted uint32 + inheritable uint32 + } + effective [2]uint32 + version int8 +} + +var ( + _vfsXattrName *byte +) + +func init() { + _vfsXattrName, _ = syscall.BytePtrFromString(vfsXattrName) +} + +func getVfsCap(path string, dest *vfscapData) (err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(path) + if err != nil { + return + } + r0, _, e1 := syscall.Syscall6(syscall.SYS_GETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(dest)), vfscapDataSizeV2, 0, 0) + if e1 != 0 { + if e1 == syscall.ENODATA { + dest.version = 2 + return + } + err = e1 + } + switch dest.magic & vfsCapVerMask { + case vfsCapVer1: + dest.version = 1 + if r0 != vfscapDataSizeV1 { + return syscall.EINVAL + } + dest.data[1].permitted = 0 + dest.data[1].inheritable = 0 + case vfsCapVer2: + dest.version = 2 + if r0 != vfscapDataSizeV2 { + return syscall.EINVAL + } + default: + return syscall.EINVAL + } + if dest.magic&vfsCapFlageffective != 0 { + dest.effective[0] = dest.data[0].permitted | dest.data[0].inheritable + dest.effective[1] = dest.data[1].permitted | dest.data[1].inheritable + } else { + dest.effective[0] = 0 + dest.effective[1] = 0 + } + return +} + +func setVfsCap(path string, data *vfscapData) (err error) { + var _p0 *byte + _p0, err = syscall.BytePtrFromString(path) + if err != nil { + return + } + var size uintptr + if data.version == 1 { + data.magic = vfsCapVer1 + size = vfscapDataSizeV1 + } else if data.version == 2 { + data.magic = vfsCapVer2 + if data.effective[0] != 0 || data.effective[1] != 0 { + data.magic |= vfsCapFlageffective + } + size = vfscapDataSizeV2 + } else { + return syscall.EINVAL + } + _, _, e1 := syscall.Syscall6(syscall.SYS_SETXATTR, uintptr(unsafe.Pointer(_p0)), uintptr(unsafe.Pointer(_vfsXattrName)), uintptr(unsafe.Pointer(data)), size, 0, 0) + if e1 != 0 { + err = e1 + } + return +} diff --git a/vendor/github.com/urfave/cli/v3/.gitignore b/vendor/github.com/urfave/cli/v3/.gitignore new file mode 100644 index 00000000..6b191490 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/.gitignore @@ -0,0 +1,11 @@ +*.coverprofile +*.exe +*.orig +.*envrc +.envrc +.idea +/.local/ +/site/ +coverage.txt +examples/*/built-example +vendor diff --git a/vendor/github.com/urfave/cli/v3/.golangci.yaml b/vendor/github.com/urfave/cli/v3/.golangci.yaml new file mode 100644 index 00000000..473a221a --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/.golangci.yaml @@ -0,0 +1,13 @@ +version: "2" + +formatters: + enable: + - gofumpt + +linters: + enable: + - makezero + - misspell + exclusions: + presets: + - std-error-handling diff --git a/vendor/github.com/urfave/cli/v3/CODE_OF_CONDUCT.md b/vendor/github.com/urfave/cli/v3/CODE_OF_CONDUCT.md new file mode 100644 index 00000000..9fee1480 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/CODE_OF_CONDUCT.md @@ -0,0 +1,75 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting urfave-governance@googlegroups.com, a members-only group +that is world-postable. All complaints will be reviewed and investigated and +will result in a response that is deemed necessary and appropriate to the +circumstances. The project team is obligated to maintain confidentiality with +regard to the reporter of an incident. Further details of specific enforcement +policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org + diff --git a/vendor/github.com/urfave/cli/v3/LICENSE b/vendor/github.com/urfave/cli/v3/LICENSE new file mode 100644 index 00000000..a23fc53d --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 urfave/cli maintainers + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/github.com/urfave/cli/v3/Makefile b/vendor/github.com/urfave/cli/v3/Makefile new file mode 100644 index 00000000..2e4af306 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/Makefile @@ -0,0 +1,26 @@ +# NOTE: this Makefile is meant to provide a simplified entry point for humans to +# run all of the critical steps to verify one's changes are harmonious in +# nature. Keeping target bodies to one line each and abstaining from make magic +# are very important so that maintainers and contributors can focus their +# attention on files that are primarily Go. + +GO_RUN_BUILD := go run scripts/build.go + +.PHONY: all +all: generate vet test check-binary-size gfmrun + +# NOTE: this is a special catch-all rule to run any of the commands +# defined in scripts/build.go with optional arguments passed +# via GFLAGS (global flags) and FLAGS (command-specific flags), e.g.: +# +# $ make test GFLAGS='--packages cli' +%: + $(GO_RUN_BUILD) $(GFLAGS) $* $(FLAGS) + +.PHONY: docs +docs: + mkdocs build + +.PHONY: serve-docs +serve-docs: + mkdocs serve diff --git a/vendor/github.com/urfave/cli/v3/README.md b/vendor/github.com/urfave/cli/v3/README.md new file mode 100644 index 00000000..e04c7295 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/README.md @@ -0,0 +1,56 @@ +# Welcome to urfave/cli + +[![Go Reference][goreference_badge]][goreference_link] +[![Go Report Card][goreportcard_badge]][goreportcard_link] +[![codecov][codecov_badge]][codecov_link] +[![Tests status][test_badge]][test_link] + +urfave/cli is a **declarative**, simple, fast, and fun package for building +command line tools in Go featuring: + +- commands and subcommands with alias and prefix match support +- flexible and permissive help system +- dynamic shell completion for `bash`, `zsh`, `fish`, and `powershell` +- no dependencies except Go standard library +- input flags for simple types, slices of simple types, time, duration, and + others +- compound short flag support (`-a` `-b` `-c` can be shortened to `-abc`) +- documentation generation in `man` and Markdown (supported via the + [`urfave/cli-docs`][urfave/cli-docs] module) +- input lookup from: + - environment variables + - plain text files + - structured file formats (supported via the + [`urfave/cli-altsrc`][urfave/cli-altsrc] module) + +## Documentation + +See the hosted documentation website at . Contents of +this website are built from the [`./docs`](./docs) directory. + +## Support + +Check the [Q&A discussions]. If you don't find answer to your question, [create +a new discussion]. + +If you found a bug or have a feature request, [create a new issue]. + +Please keep in mind that this project is run by unpaid volunteers. + +### License + +See [`LICENSE`](./LICENSE). + +[test_badge]: https://github.com/urfave/cli/actions/workflows/test.yml/badge.svg +[test_link]: https://github.com/urfave/cli/actions/workflows/test.yml +[goreference_badge]: https://pkg.go.dev/badge/github.com/urfave/cli/v3.svg +[goreference_link]: https://pkg.go.dev/github.com/urfave/cli/v3 +[goreportcard_badge]: https://goreportcard.com/badge/github.com/urfave/cli/v3 +[goreportcard_link]: https://goreportcard.com/report/github.com/urfave/cli/v3 +[codecov_badge]: https://codecov.io/gh/urfave/cli/branch/main/graph/badge.svg?token=t9YGWLh05g +[codecov_link]: https://codecov.io/gh/urfave/cli +[Q&A discussions]: https://github.com/urfave/cli/discussions/categories/q-a +[create a new discussion]: https://github.com/urfave/cli/discussions/new?category=q-a +[urfave/cli-docs]: https://github.com/urfave/cli-docs +[urfave/cli-altsrc]: https://github.com/urfave/cli-altsrc +[create a new issue]: https://github.com/urfave/cli/issues/new/choose diff --git a/vendor/github.com/urfave/cli/v3/args.go b/vendor/github.com/urfave/cli/v3/args.go new file mode 100644 index 00000000..918afb2e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/args.go @@ -0,0 +1,402 @@ +package cli + +import ( + "fmt" + "time" +) + +type Args interface { + // Get returns the nth argument, or else a blank string + Get(n int) string + // First returns the first argument, or else a blank string + First() string + // Tail returns the rest of the arguments (not the first one) + // or else an empty string slice + Tail() []string + // Len returns the length of the wrapped slice + Len() int + // Present checks if there are any arguments present + Present() bool + // Slice returns a copy of the internal slice + Slice() []string +} + +type stringSliceArgs struct { + v []string +} + +func (a *stringSliceArgs) Get(n int) string { + if len(a.v) > n { + return a.v[n] + } + return "" +} + +func (a *stringSliceArgs) First() string { + return a.Get(0) +} + +func (a *stringSliceArgs) Tail() []string { + if a.Len() >= 2 { + tail := a.v[1:] + ret := make([]string, len(tail)) + copy(ret, tail) + return ret + } + + return []string{} +} + +func (a *stringSliceArgs) Len() int { + return len(a.v) +} + +func (a *stringSliceArgs) Present() bool { + return a.Len() != 0 +} + +func (a *stringSliceArgs) Slice() []string { + ret := make([]string, len(a.v)) + copy(ret, a.v) + return ret +} + +// Argument captures a positional argument that can +// be parsed +type Argument interface { + // which this argument can be accessed using the given name + HasName(string) bool + + // Parse the given args and return unparsed args and/or error + Parse([]string) ([]string, error) + + // The usage template for this argument to use in help + Usage() string + + // The Value of this Arg + Get() any +} + +// AnyArguments to differentiate between no arguments(nil) vs aleast one +var AnyArguments = []Argument{ + &StringArgs{ + Max: -1, + }, +} + +type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *T `json:"-"` // the destination point for this argument + UsageText string `json:"usageText"` // the usage text to show + Config C `json:"config"` // config for this argument similar to Flag Config + + value *T +} + +func (a *ArgumentBase[T, C, VC]) HasName(s string) bool { + return s == a.Name +} + +func (a *ArgumentBase[T, C, VC]) Usage() string { + if a.UsageText != "" { + return a.UsageText + } + + usageFormat := "%[1]s" + return fmt.Sprintf(usageFormat, a.Name) +} + +func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) { + tracef("calling arg%[1] parse with args %[2]", a.Name, s) + + var vc VC + var t T + value := vc.Create(a.Value, &t, a.Config) + a.value = &t + + tracef("attempting arg%[1] parse", &a.Name) + if len(s) > 0 { + if err := value.Set(s[0]); err != nil { + return s, err + } + *a.value = value.Get().(T) + tracef("set arg%[1] one value", a.Name, *a.value) + } + + if a.Destination != nil { + tracef("setting destination") + *a.Destination = *a.value + } + + if len(s) > 0 { + return s[1:], nil + } + return s, nil +} + +func (a *ArgumentBase[T, C, VC]) Get() any { + if a.value != nil { + return *a.value + } + return a.Value +} + +// ArgumentsBase is a base type for slice arguments +type ArgumentsBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *[]T `json:"-"` // the destination point for this argument + UsageText string `json:"usageText"` // the usage text to show + Min int `json:"minTimes"` // the min num of occurrences of this argument + Max int `json:"maxTimes"` // the max num of occurrences of this argument, set to -1 for unlimited + Config C `json:"config"` // config for this argument similar to Flag Config + + values []T +} + +func (a *ArgumentsBase[T, C, VC]) HasName(s string) bool { + return s == a.Name +} + +func (a *ArgumentsBase[T, C, VC]) Usage() string { + if a.UsageText != "" { + return a.UsageText + } + + usageFormat := "" + if a.Min == 0 { + if a.Max == 1 { + usageFormat = "[%[1]s]" + } else { + usageFormat = "[%[1]s ...]" + } + } else { + usageFormat = "%[1]s [%[1]s ...]" + } + return fmt.Sprintf(usageFormat, a.Name) +} + +func (a *ArgumentsBase[T, C, VC]) Parse(s []string) ([]string, error) { + tracef("calling arg%[1] parse with args %[2]", &a.Name, s) + if a.Max == 0 { + fmt.Printf("WARNING args %s has max 0, not parsing argument\n", a.Name) + return s, nil + } + if a.Max != -1 && a.Min > a.Max { + fmt.Printf("WARNING args %s has min[%d] > max[%d], not parsing argument\n", a.Name, a.Min, a.Max) + return s, nil + } + + count := 0 + var vc VC + var t T + value := vc.Create(a.Value, &t, a.Config) + a.values = []T{} + + tracef("attempting arg%[1] parse", &a.Name) + for _, arg := range s { + if err := value.Set(arg); err != nil { + return s, err + } + tracef("set arg%[1] one value", &a.Name, value.Get().(T)) + a.values = append(a.values, value.Get().(T)) + count++ + if count >= a.Max && a.Max > -1 { + break + } + } + if count < a.Min { + return s, fmt.Errorf("sufficient count of arg %s not provided, given %d expected %d", a.Name, count, a.Min) + } + + if a.Destination != nil { + tracef("appending destination") + *a.Destination = a.values // append(*a.Destination, a.values...) + } + + return s[count:], nil +} + +func (a *ArgumentsBase[T, C, VC]) Get() any { + if a.values != nil { + return a.values + } + return []T{} +} + +type ( + FloatArg = ArgumentBase[float64, NoConfig, floatValue[float64]] + Float32Arg = ArgumentBase[float32, NoConfig, floatValue[float32]] + Float64Arg = ArgumentBase[float64, NoConfig, floatValue[float64]] + IntArg = ArgumentBase[int, IntegerConfig, intValue[int]] + Int8Arg = ArgumentBase[int8, IntegerConfig, intValue[int8]] + Int16Arg = ArgumentBase[int16, IntegerConfig, intValue[int16]] + Int32Arg = ArgumentBase[int32, IntegerConfig, intValue[int32]] + Int64Arg = ArgumentBase[int64, IntegerConfig, intValue[int64]] + StringArg = ArgumentBase[string, StringConfig, stringValue] + StringMapArgs = ArgumentBase[map[string]string, StringConfig, StringMap] + TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue] + UintArg = ArgumentBase[uint, IntegerConfig, uintValue[uint]] + Uint8Arg = ArgumentBase[uint8, IntegerConfig, uintValue[uint8]] + Uint16Arg = ArgumentBase[uint16, IntegerConfig, uintValue[uint16]] + Uint32Arg = ArgumentBase[uint32, IntegerConfig, uintValue[uint32]] + Uint64Arg = ArgumentBase[uint64, IntegerConfig, uintValue[uint64]] + + FloatArgs = ArgumentsBase[float64, NoConfig, floatValue[float64]] + Float32Args = ArgumentsBase[float32, NoConfig, floatValue[float32]] + Float64Args = ArgumentsBase[float64, NoConfig, floatValue[float64]] + IntArgs = ArgumentsBase[int, IntegerConfig, intValue[int]] + Int8Args = ArgumentsBase[int8, IntegerConfig, intValue[int8]] + Int16Args = ArgumentsBase[int16, IntegerConfig, intValue[int16]] + Int32Args = ArgumentsBase[int32, IntegerConfig, intValue[int32]] + Int64Args = ArgumentsBase[int64, IntegerConfig, intValue[int64]] + StringArgs = ArgumentsBase[string, StringConfig, stringValue] + TimestampArgs = ArgumentsBase[time.Time, TimestampConfig, timestampValue] + UintArgs = ArgumentsBase[uint, IntegerConfig, uintValue[uint]] + Uint8Args = ArgumentsBase[uint8, IntegerConfig, uintValue[uint8]] + Uint16Args = ArgumentsBase[uint16, IntegerConfig, uintValue[uint16]] + Uint32Args = ArgumentsBase[uint32, IntegerConfig, uintValue[uint32]] + Uint64Args = ArgumentsBase[uint64, IntegerConfig, uintValue[uint64]] +) + +func (c *Command) getArgValue(name string) any { + tracef("command %s looking for args %s", c.Name, name) + for _, arg := range c.Arguments { + if arg.HasName(name) { + tracef("command %s found args %s", c.Name, name) + return arg.Get() + } + } + tracef("command %s did not find args %s", c.Name, name) + return nil +} + +func arg[T any](name string, c *Command) T { + val := c.getArgValue(name) + if a, ok := val.(T); ok { + return a + } + var zero T + return zero +} + +func (c *Command) StringArg(name string) string { + return arg[string](name, c) +} + +func (c *Command) StringArgs(name string) []string { + return arg[[]string](name, c) +} + +func (c *Command) FloatArg(name string) float64 { + return arg[float64](name, c) +} + +func (c *Command) FloatArgs(name string) []float64 { + return arg[[]float64](name, c) +} + +func (c *Command) Float32Arg(name string) float32 { + return arg[float32](name, c) +} + +func (c *Command) Float32Args(name string) []float32 { + return arg[[]float32](name, c) +} + +func (c *Command) Float64Arg(name string) float64 { + return arg[float64](name, c) +} + +func (c *Command) Float64Args(name string) []float64 { + return arg[[]float64](name, c) +} + +func (c *Command) IntArg(name string) int { + return arg[int](name, c) +} + +func (c *Command) IntArgs(name string) []int { + return arg[[]int](name, c) +} + +func (c *Command) Int8Arg(name string) int8 { + return arg[int8](name, c) +} + +func (c *Command) Int8Args(name string) []int8 { + return arg[[]int8](name, c) +} + +func (c *Command) Int16Arg(name string) int16 { + return arg[int16](name, c) +} + +func (c *Command) Int16Args(name string) []int16 { + return arg[[]int16](name, c) +} + +func (c *Command) Int32Arg(name string) int32 { + return arg[int32](name, c) +} + +func (c *Command) Int32Args(name string) []int32 { + return arg[[]int32](name, c) +} + +func (c *Command) Int64Arg(name string) int64 { + return arg[int64](name, c) +} + +func (c *Command) Int64Args(name string) []int64 { + return arg[[]int64](name, c) +} + +func (c *Command) UintArg(name string) uint { + return arg[uint](name, c) +} + +func (c *Command) Uint8Arg(name string) uint8 { + return arg[uint8](name, c) +} + +func (c *Command) Uint16Arg(name string) uint16 { + return arg[uint16](name, c) +} + +func (c *Command) Uint32Arg(name string) uint32 { + return arg[uint32](name, c) +} + +func (c *Command) Uint64Arg(name string) uint64 { + return arg[uint64](name, c) +} + +func (c *Command) UintArgs(name string) []uint { + return arg[[]uint](name, c) +} + +func (c *Command) Uint8Args(name string) []uint8 { + return arg[[]uint8](name, c) +} + +func (c *Command) Uint16Args(name string) []uint16 { + return arg[[]uint16](name, c) +} + +func (c *Command) Uint32Args(name string) []uint32 { + return arg[[]uint32](name, c) +} + +func (c *Command) Uint64Args(name string) []uint64 { + return arg[[]uint64](name, c) +} + +func (c *Command) TimestampArg(name string) time.Time { + return arg[time.Time](name, c) +} + +func (c *Command) TimestampArgs(name string) []time.Time { + return arg[[]time.Time](name, c) +} diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete b/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete new file mode 100644 index 00000000..d63937d9 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/bash_autocomplete @@ -0,0 +1,34 @@ +#!/bin/bash + +# This is a shell completion script auto-generated by https://github.com/urfave/cli for bash. + +# Macs have bash3 for which the bash-completion package doesn't include +# _init_completion. This is a minimal version of that function. +__%[1]s_init_completion() { + COMPREPLY=() + _get_comp_words_by_ref "$@" cur prev words cword +} + +__%[1]s_bash_autocomplete() { + if [[ "${COMP_WORDS[0]}" != "source" ]]; then + local cur opts base words + COMPREPLY=() + cur="${COMP_WORDS[COMP_CWORD]}" + if declare -F _init_completion >/dev/null 2>&1; then + _init_completion -n "=:" || return + else + __%[1]s_init_completion -n "=:" || return + fi + words=("${words[@]:0:$cword}") + if [[ "$cur" == "-"* ]]; then + requestComp="${words[*]} ${cur} --generate-shell-completion" + else + requestComp="${words[*]} --generate-shell-completion" + fi + opts=$(eval "${requestComp}" 2>/dev/null) + COMPREPLY=($(compgen -W "${opts}" -- ${cur})) + return 0 + fi +} + +complete -o bashdefault -o default -o nospace -F __%[1]s_bash_autocomplete %[1]s diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 b/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 new file mode 100644 index 00000000..6e0c422e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/powershell_autocomplete.ps1 @@ -0,0 +1,9 @@ +$fn = $($MyInvocation.MyCommand.Name) +$name = $fn -replace "(.*)\.ps1$", '$1' +Register-ArgumentCompleter -Native -CommandName $name -ScriptBlock { + param($commandName, $wordToComplete, $cursorPosition) + $other = "$wordToComplete --generate-shell-completion" + Invoke-Expression $other | ForEach-Object { + [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) + } + } diff --git a/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete b/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete new file mode 100644 index 00000000..d24049a7 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/autocomplete/zsh_autocomplete @@ -0,0 +1,29 @@ +#compdef %[1]s +compdef _%[1]s %[1]s + +# This is a shell completion script auto-generated by https://github.com/urfave/cli for zsh. + +_%[1]s() { + local -a opts # Declare a local array + local current + current=${words[-1]} # -1 means "the last element" + if [[ "$current" == "-"* ]]; then + # Current word starts with a hyphen, so complete flags/options + opts=("${(@f)$(${words[@]:0:#words[@]-1} ${current} --generate-shell-completion)}") + else + # Current word does not start with a hyphen, so complete subcommands + opts=("${(@f)$(${words[@]:0:#words[@]-1} --generate-shell-completion)}") + fi + + if [[ "${opts[1]}" != "" ]]; then + _describe 'values' opts + else + _files + fi +} + +# Don't run the completion function when being source-ed or eval-ed. +# See https://github.com/urfave/cli/issues/1874 for discussion. +if [ "$funcstack[1]" = "_%[1]s" ]; then + _%[1]s +fi diff --git a/vendor/github.com/urfave/cli/v3/category.go b/vendor/github.com/urfave/cli/v3/category.go new file mode 100644 index 00000000..14e3649c --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/category.go @@ -0,0 +1,195 @@ +package cli + +import "sort" + +// CommandCategories interface allows for category manipulation +type CommandCategories interface { + // AddCommand adds a command to a category, creating a new category if necessary. + AddCommand(category string, command *Command) + // Categories returns a slice of categories sorted by name + Categories() []CommandCategory +} + +type commandCategories []*commandCategory + +func newCommandCategories() CommandCategories { + ret := commandCategories([]*commandCategory{}) + return &ret +} + +func (c *commandCategories) Less(i, j int) bool { + return lexicographicLess((*c)[i].Name(), (*c)[j].Name()) +} + +func (c *commandCategories) Len() int { + return len(*c) +} + +func (c *commandCategories) Swap(i, j int) { + (*c)[i], (*c)[j] = (*c)[j], (*c)[i] +} + +func (c *commandCategories) AddCommand(category string, command *Command) { + for _, commandCategory := range []*commandCategory(*c) { + if commandCategory.name == category { + commandCategory.commands = append(commandCategory.commands, command) + return + } + } + newVal := append(*c, + &commandCategory{name: category, commands: []*Command{command}}) + *c = newVal +} + +func (c *commandCategories) Categories() []CommandCategory { + ret := make([]CommandCategory, len(*c)) + for i, cat := range *c { + ret[i] = cat + } + return ret +} + +// CommandCategory is a category containing commands. +type CommandCategory interface { + // Name returns the category name string + Name() string + // VisibleCommands returns a slice of the Commands with Hidden=false + VisibleCommands() []*Command +} + +type commandCategory struct { + name string + commands []*Command +} + +func (c *commandCategory) Name() string { + return c.name +} + +func (c *commandCategory) VisibleCommands() []*Command { + if c.commands == nil { + c.commands = []*Command{} + } + + var ret []*Command + for _, command := range c.commands { + if !command.Hidden { + ret = append(ret, command) + } + } + return ret +} + +// FlagCategories interface allows for category manipulation +type FlagCategories interface { + // AddFlags adds a flag to a category, creating a new category if necessary. + AddFlag(category string, fl Flag) + // VisibleCategories returns a slice of visible flag categories sorted by name + VisibleCategories() []VisibleFlagCategory +} + +type defaultFlagCategories struct { + m map[string]*defaultVisibleFlagCategory +} + +func newFlagCategories() FlagCategories { + return &defaultFlagCategories{ + m: map[string]*defaultVisibleFlagCategory{}, + } +} + +func newFlagCategoriesFromFlags(fs []Flag) FlagCategories { + fc := newFlagCategories() + + var categorized bool + + for _, fl := range fs { + if cf, ok := fl.(CategorizableFlag); ok { + visible := false + if vf, ok := fl.(VisibleFlag); ok { + visible = vf.IsVisible() + } + if cat := cf.GetCategory(); cat != "" && visible { + fc.AddFlag(cat, fl) + categorized = true + } + } + } + + if categorized { + for _, fl := range fs { + if cf, ok := fl.(CategorizableFlag); ok { + visible := false + if vf, ok := fl.(VisibleFlag); ok { + visible = vf.IsVisible() + } + if cf.GetCategory() == "" && visible { + fc.AddFlag("", fl) + } + } + } + } + + return fc +} + +func (f *defaultFlagCategories) AddFlag(category string, fl Flag) { + if _, ok := f.m[category]; !ok { + f.m[category] = &defaultVisibleFlagCategory{name: category, m: map[string]Flag{}} + } + + f.m[category].m[fl.String()] = fl +} + +func (f *defaultFlagCategories) VisibleCategories() []VisibleFlagCategory { + catNames := []string{} + for name := range f.m { + catNames = append(catNames, name) + } + + sort.Strings(catNames) + + ret := make([]VisibleFlagCategory, len(catNames)) + for i, name := range catNames { + ret[i] = f.m[name] + } + + return ret +} + +// VisibleFlagCategory is a category containing flags. +type VisibleFlagCategory interface { + // Name returns the category name string + Name() string + // Flags returns a slice of VisibleFlag sorted by name + Flags() []Flag +} + +type defaultVisibleFlagCategory struct { + name string + m map[string]Flag +} + +func (fc *defaultVisibleFlagCategory) Name() string { + return fc.name +} + +func (fc *defaultVisibleFlagCategory) Flags() []Flag { + vfNames := []string{} + for flName, fl := range fc.m { + if vf, ok := fl.(VisibleFlag); ok { + if vf.IsVisible() { + vfNames = append(vfNames, flName) + } + } + } + + sort.Strings(vfNames) + + ret := make([]Flag, len(vfNames)) + for i, flName := range vfNames { + ret[i] = fc.m[flName] + } + + return ret +} diff --git a/vendor/github.com/urfave/cli/v3/cli.go b/vendor/github.com/urfave/cli/v3/cli.go new file mode 100644 index 00000000..d833aff5 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/cli.go @@ -0,0 +1,60 @@ +// Package cli provides a minimal framework for creating and organizing command line +// Go applications. cli is designed to be easy to understand and write, the most simple +// cli application can be written as follows: +// +// func main() { +// (&cli.Command{}).Run(context.Background(), os.Args) +// } +// +// Of course this application does not do much, so let's make this an actual application: +// +// func main() { +// cmd := &cli.Command{ +// Name: "greet", +// Usage: "say a greeting", +// Action: func(c *cli.Context) error { +// fmt.Println("Greetings") +// return nil +// }, +// } +// +// cmd.Run(context.Background(), os.Args) +// } +package cli + +import ( + "fmt" + "os" + "runtime" + "strings" +) + +var isTracingOn = os.Getenv("URFAVE_CLI_TRACING") == "on" + +func tracef(format string, a ...any) { + if !isTracingOn { + return + } + + if !strings.HasSuffix(format, "\n") { + format = format + "\n" + } + + pc, file, line, _ := runtime.Caller(1) + cf := runtime.FuncForPC(pc) + + fmt.Fprintf( + os.Stderr, + strings.Join([]string{ + "## URFAVE CLI TRACE ", + file, + ":", + fmt.Sprintf("%v", line), + " ", + fmt.Sprintf("(%s)", cf.Name()), + " ", + format, + }, ""), + a..., + ) +} diff --git a/vendor/github.com/urfave/cli/v3/command.go b/vendor/github.com/urfave/cli/v3/command.go new file mode 100644 index 00000000..d7b05637 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/command.go @@ -0,0 +1,563 @@ +package cli + +import ( + "context" + "fmt" + "io" + "slices" + "strings" +) + +const ( + // ignoreFlagPrefix is to ignore test flags when adding flags from other packages + ignoreFlagPrefix = "test." + + commandContextKey = contextKey("cli.context") +) + +type contextKey string + +// Command contains everything needed to run an application that +// accepts a string slice of arguments such as os.Args. A given +// Command may contain Flags and sub-commands in Commands. +type Command struct { + // The name of the command + Name string `json:"name"` + // A list of aliases for the command + Aliases []string `json:"aliases"` + // A short description of the usage of this command + Usage string `json:"usage"` + // Text to override the USAGE section of help + UsageText string `json:"usageText"` + // A short description of the arguments of this command + ArgsUsage string `json:"argsUsage"` + // Version of the command + Version string `json:"version"` + // Longer explanation of how the command works + Description string `json:"description"` + // DefaultCommand is the (optional) name of a command + // to run if no command names are passed as CLI arguments. + DefaultCommand string `json:"defaultCommand"` + // The category the command is part of + Category string `json:"category"` + // List of child commands + Commands []*Command `json:"commands"` + // List of flags to parse + Flags []Flag `json:"flags"` + // Boolean to hide built-in help command and help flag + HideHelp bool `json:"hideHelp"` + // Ignored if HideHelp is true. + HideHelpCommand bool `json:"hideHelpCommand"` + // Boolean to hide built-in version flag and the VERSION section of help + HideVersion bool `json:"hideVersion"` + // Boolean to enable shell completion commands + EnableShellCompletion bool `json:"-"` + // Shell Completion generation command name + ShellCompletionCommandName string `json:"-"` + // The function to call when checking for shell command completions + ShellComplete ShellCompleteFunc `json:"-"` + // The function to configure a shell completion command + ConfigureShellCompletionCommand ConfigureShellCompletionCommand `json:"-"` + // An action to execute before any subcommands are run, but after the context is ready + // If a non-nil error is returned, no subcommands are run + Before BeforeFunc `json:"-"` + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc `json:"-"` + // The function to call when this command is invoked + Action ActionFunc `json:"-"` + // Execute this function if the proper command cannot be found + CommandNotFound CommandNotFoundFunc `json:"-"` + // Execute this function if a usage error occurs. + OnUsageError OnUsageErrorFunc `json:"-"` + // Execute this function when an invalid flag is accessed from the context + InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"` + // Boolean to hide this command from help or completion + Hidden bool `json:"hidden"` + // List of all authors who contributed (string or fmt.Stringer) + // TODO: ~string | fmt.Stringer when interface unions are available + Authors []any `json:"authors"` + // Copyright of the binary if any + Copyright string `json:"copyright"` + // Reader reader to write input to (useful for tests) + Reader io.Reader `json:"-"` + // Writer writer to write output to + Writer io.Writer `json:"-"` + // ErrWriter writes error output + ErrWriter io.Writer `json:"-"` + // ExitErrHandler processes any error encountered while running a Command before it is + // returned to the caller. If no function is provided, HandleExitCoder is used as the + // default behavior. + ExitErrHandler ExitErrHandlerFunc `json:"-"` + // Other custom info + Metadata map[string]interface{} `json:"metadata"` + // Carries a function which returns app specific info. + ExtraInfo func() map[string]string `json:"-"` + // CustomRootCommandHelpTemplate the text template for app help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomRootCommandHelpTemplate string `json:"-"` + // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," + SliceFlagSeparator string `json:"sliceFlagSeparator"` + // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false + DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"` + // Boolean to enable short-option handling so user can combine several + // single-character bool arguments into one + // i.e. foobar -o -v -> foobar -ov + UseShortOptionHandling bool `json:"useShortOptionHandling"` + // Enable suggestions for commands and flags + Suggest bool `json:"suggest"` + // Allows global flags set by libraries which use flag.XXXVar(...) directly + // to be parsed through this library + AllowExtFlags bool `json:"allowExtFlags"` + // Treat all flags as normal arguments if true + SkipFlagParsing bool `json:"skipFlagParsing"` + // CustomHelpTemplate the text template for the command help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomHelpTemplate string `json:"-"` + // Use longest prefix match for commands + PrefixMatchCommands bool `json:"prefixMatchCommands"` + // Custom suggest command for matching + SuggestCommandFunc SuggestCommandFunc `json:"-"` + // Flag exclusion group + MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"` + // Arguments to parse for this command + Arguments []Argument `json:"arguments"` + // Whether to read arguments from stdin + // applicable to root command only + ReadArgsFromStdin bool `json:"readArgsFromStdin"` + + // categories contains the categorized commands and is populated on app startup + categories CommandCategories + // flagCategories contains the categorized flags and is populated on app startup + flagCategories FlagCategories + // flags that have been applied in current parse + appliedFlags []Flag + // flags that have been set + setFlags map[Flag]struct{} + // The parent of this command. This value will be nil for the + // command at the root of the graph. + parent *Command + // parsed args + parsedArgs Args + // track state of error handling + isInError bool + // track state of defaults + didSetupDefaults bool + // whether in shell completion mode + shellCompletion bool +} + +// FullName returns the full name of the command. +// For commands with parents this ensures that the parent commands +// are part of the command path. +func (cmd *Command) FullName() string { + namePath := []string{} + + if cmd.parent != nil { + namePath = append(namePath, cmd.parent.FullName()) + } + + return strings.Join(append(namePath, cmd.Name), " ") +} + +func (cmd *Command) Command(name string) *Command { + for _, subCmd := range cmd.Commands { + if subCmd.HasName(name) { + return subCmd + } + } + + return nil +} + +func (cmd *Command) checkHelp() bool { + tracef("checking if help is wanted (cmd=%[1]q)", cmd.Name) + + return HelpFlag != nil && slices.ContainsFunc(HelpFlag.Names(), cmd.Bool) +} + +func (cmd *Command) allFlags() []Flag { + var flags []Flag + flags = append(flags, cmd.Flags...) + for _, grpf := range cmd.MutuallyExclusiveFlags { + for _, f1 := range grpf.Flags { + flags = append(flags, f1...) + } + } + return flags +} + +// useShortOptionHandling traverses Lineage() for *any* ancestors +// with UseShortOptionHandling +func (cmd *Command) useShortOptionHandling() bool { + for _, pCmd := range cmd.Lineage() { + if pCmd.UseShortOptionHandling { + return true + } + } + + return false +} + +func (cmd *Command) suggestFlagFromError(err error, commandName string) (string, error) { + fl, parseErr := flagFromError(err) + if parseErr != nil { + return "", err + } + + flags := cmd.Flags + hideHelp := cmd.hideHelp() + + if commandName != "" { + subCmd := cmd.Command(commandName) + if subCmd == nil { + return "", err + } + flags = subCmd.Flags + hideHelp = hideHelp || subCmd.HideHelp + } + + suggestion := SuggestFlag(flags, fl, hideHelp) + if len(suggestion) == 0 { + return "", err + } + + return fmt.Sprintf(SuggestDidYouMeanTemplate, suggestion) + "\n\n", nil +} + +// Names returns the names including short names and aliases. +func (cmd *Command) Names() []string { + return append([]string{cmd.Name}, cmd.Aliases...) +} + +// HasName returns true if Command.Name matches given name +func (cmd *Command) HasName(name string) bool { + return slices.Contains(cmd.Names(), name) +} + +// VisibleCategories returns a slice of categories and commands that are +// Hidden=false +func (cmd *Command) VisibleCategories() []CommandCategory { + ret := []CommandCategory{} + for _, category := range cmd.categories.Categories() { + if visible := func() CommandCategory { + if len(category.VisibleCommands()) > 0 { + return category + } + return nil + }(); visible != nil { + ret = append(ret, visible) + } + } + return ret +} + +// VisibleCommands returns a slice of the Commands with Hidden=false +func (cmd *Command) VisibleCommands() []*Command { + var ret []*Command + for _, command := range cmd.Commands { + if command.Hidden || command.Name == helpName { + continue + } + ret = append(ret, command) + } + return ret +} + +// VisibleFlagCategories returns a slice containing all the visible flag categories with the flags they contain +func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory { + if cmd.flagCategories == nil { + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) + } + return cmd.flagCategories.VisibleCategories() +} + +// VisibleFlags returns a slice of the Flags with Hidden=false +func (cmd *Command) VisibleFlags() []Flag { + return visibleFlags(cmd.allFlags()) +} + +func (cmd *Command) appendFlag(fl Flag) { + if !hasFlag(cmd.Flags, fl) { + cmd.Flags = append(cmd.Flags, fl) + } +} + +// VisiblePersistentFlags returns a slice of [LocalFlag] with Persistent=true and Hidden=false. +func (cmd *Command) VisiblePersistentFlags() []Flag { + var flags []Flag + for _, fl := range cmd.Root().Flags { + pfl, ok := fl.(LocalFlag) + if !ok || pfl.IsLocal() { + continue + } + flags = append(flags, fl) + } + return visibleFlags(flags) +} + +func (cmd *Command) appendCommand(aCmd *Command) { + if !slices.Contains(cmd.Commands, aCmd) { + aCmd.parent = cmd + cmd.Commands = append(cmd.Commands, aCmd) + } +} + +func (cmd *Command) handleExitCoder(ctx context.Context, err error) error { + if cmd.parent != nil { + return cmd.parent.handleExitCoder(ctx, err) + } + + if cmd.ExitErrHandler != nil { + cmd.ExitErrHandler(ctx, cmd, err) + return err + } + + HandleExitCoder(err) + return err +} + +func (cmd *Command) argsWithDefaultCommand(oldArgs Args) Args { + if cmd.DefaultCommand != "" { + rawArgs := append([]string{cmd.DefaultCommand}, oldArgs.Slice()...) + newArgs := &stringSliceArgs{v: rawArgs} + + return newArgs + } + + return oldArgs +} + +// Root returns the Command at the root of the graph +func (cmd *Command) Root() *Command { + if cmd.parent == nil { + return cmd + } + + return cmd.parent.Root() +} + +func (cmd *Command) set(fName string, f Flag, val string) error { + cmd.setFlags[f] = struct{}{} + if err := f.Set(fName, val); err != nil { + return fmt.Errorf("invalid value %q for flag -%s: %v", val, fName, err) + } + return nil +} + +func (cmd *Command) lFlag(name string) Flag { + for _, f := range cmd.allFlags() { + if slices.Contains(f.Names(), name) { + tracef("flag found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return f + } + } + return nil +} + +func (cmd *Command) lookupFlag(name string) Flag { + for _, pCmd := range cmd.Lineage() { + if f := pCmd.lFlag(name); f != nil { + return f + } + } + + tracef("flag NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + cmd.onInvalidFlag(context.TODO(), name) + return nil +} + +func (cmd *Command) checkRequiredFlag(f Flag) (bool, string) { + if rf, ok := f.(RequiredFlag); ok && rf.IsRequired() { + flagName := f.Names()[0] + if !f.IsSet() { + return false, flagName + } + } + return true, "" +} + +func (cmd *Command) checkAllRequiredFlags() requiredFlagsErr { + for pCmd := cmd; pCmd != nil; pCmd = pCmd.parent { + if err := pCmd.checkRequiredFlags(); err != nil { + return err + } + } + return nil +} + +func (cmd *Command) checkRequiredFlags() requiredFlagsErr { + tracef("checking for required flags (cmd=%[1]q)", cmd.Name) + + missingFlags := []string{} + + for _, f := range cmd.appliedFlags { + if ok, name := cmd.checkRequiredFlag(f); !ok { + missingFlags = append(missingFlags, name) + } + } + + if len(missingFlags) != 0 { + tracef("found missing required flags %[1]q (cmd=%[2]q)", missingFlags, cmd.Name) + + return &errRequiredFlags{missingFlags: missingFlags} + } + + tracef("all required flags set (cmd=%[1]q)", cmd.Name) + + return nil +} + +func (cmd *Command) onInvalidFlag(ctx context.Context, name string) { + for cmd != nil { + if cmd.InvalidFlagAccessHandler != nil { + cmd.InvalidFlagAccessHandler(ctx, cmd, name) + break + } + cmd = cmd.parent + } +} + +// NumFlags returns the number of flags set +func (cmd *Command) NumFlags() int { + tracef("numFlags numAppliedFlags %d", len(cmd.appliedFlags)) + count := 0 + for _, f := range cmd.appliedFlags { + if f.IsSet() { + count++ + } + } + return count // cmd.flagSet.NFlag() +} + +// Set sets a context flag to a value. +func (cmd *Command) Set(name, value string) error { + if f := cmd.lookupFlag(name); f != nil { + return f.Set(name, value) + } + + return fmt.Errorf("no such flag -%s", name) +} + +// IsSet determines if the flag was actually set +func (cmd *Command) IsSet(name string) bool { + fl := cmd.lookupFlag(name) + if fl == nil { + tracef("flag with name %[1]q NOT found; assuming not set (cmd=%[2]q)", name, cmd.Name) + return false + } + + isSet := fl.IsSet() + if isSet { + tracef("flag with name %[1]q is set (cmd=%[2]q)", name, cmd.Name) + } else { + tracef("flag with name %[1]q is no set (cmd=%[2]q)", name, cmd.Name) + } + + return isSet +} + +// LocalFlagNames returns a slice of flag names used in this +// command. +func (cmd *Command) LocalFlagNames() []string { + names := []string{} + + // Check the flags which have been set via env or file + for _, f := range cmd.allFlags() { + if f.IsSet() { + names = append(names, f.Names()...) + } + } + + // Sort out the duplicates since flag could be set via multiple + // paths + m := map[string]struct{}{} + uniqNames := []string{} + + for _, name := range names { + if _, ok := m[name]; !ok { + m[name] = struct{}{} + uniqNames = append(uniqNames, name) + } + } + + return uniqNames +} + +// FlagNames returns a slice of flag names used by the this command +// and all of its parent commands. +func (cmd *Command) FlagNames() []string { + names := cmd.LocalFlagNames() + + if cmd.parent != nil { + names = append(cmd.parent.FlagNames(), names...) + } + + return names +} + +// Lineage returns *this* command and all of its ancestor commands +// in order from child to parent +func (cmd *Command) Lineage() []*Command { + lineage := []*Command{cmd} + + if cmd.parent != nil { + lineage = append(lineage, cmd.parent.Lineage()...) + } + + return lineage +} + +// Count returns the num of occurrences of this flag +func (cmd *Command) Count(name string) int { + if cf, ok := cmd.lookupFlag(name).(Countable); ok { + return cf.Count() + } + return 0 +} + +// Value returns the value of the flag corresponding to `name` +func (cmd *Command) Value(name string) interface{} { + if fs := cmd.lookupFlag(name); fs != nil { + tracef("value found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return fs.Get() + } + + tracef("value NOT found for name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} + +// Args returns the command line arguments associated with the +// command. +func (cmd *Command) Args() Args { + return cmd.parsedArgs +} + +// NArg returns the number of the command line arguments. +func (cmd *Command) NArg() int { + return cmd.Args().Len() +} + +func (cmd *Command) runFlagActions(ctx context.Context) error { + tracef("runFlagActions") + for fl := range cmd.setFlags { + /*tracef("checking %v:%v", fl.Names(), fl.IsSet()) + if !fl.IsSet() { + continue + }*/ + + //if pf, ok := fl.(LocalFlag); ok && !pf.IsLocal() { + // continue + //} + + if af, ok := fl.(ActionableFlag); ok { + if err := af.RunAction(ctx, cmd); err != nil { + return err + } + } + } + + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/command_parse.go b/vendor/github.com/urfave/cli/v3/command_parse.go new file mode 100644 index 00000000..11306580 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/command_parse.go @@ -0,0 +1,213 @@ +package cli + +import ( + "fmt" + "strings" + "unicode" +) + +const ( + providedButNotDefinedErrMsg = "flag provided but not defined: -" + argumentNotProvidedErrMsg = "flag needs an argument: " +) + +// flagFromError tries to parse a provided flag from an error message. If the +// parsing fails, it returns the input error and an empty string +func flagFromError(err error) (string, error) { + errStr := err.Error() + trimmed := strings.TrimPrefix(errStr, providedButNotDefinedErrMsg) + if errStr == trimmed { + return "", err + } + return trimmed, nil +} + +func (cmd *Command) parseFlags(args Args) (Args, error) { + tracef("parsing flags from arguments %[1]q (cmd=%[2]q)", args, cmd.Name) + + cmd.setFlags = map[Flag]struct{}{} + cmd.appliedFlags = cmd.allFlags() + + tracef("walking command lineage for persistent flags (cmd=%[1]q)", cmd.Name) + + for pCmd := cmd.parent; pCmd != nil; pCmd = pCmd.parent { + tracef( + "checking ancestor command=%[1]q for persistent flags (cmd=%[2]q)", + pCmd.Name, cmd.Name, + ) + + for _, fl := range pCmd.Flags { + flNames := fl.Names() + + pfl, ok := fl.(LocalFlag) + if !ok || pfl.IsLocal() { + tracef("skipping non-persistent flag %[1]q (cmd=%[2]q)", flNames, cmd.Name) + continue + } + + tracef( + "checking for applying persistent flag=%[1]q pCmd=%[2]q (cmd=%[3]q)", + flNames, pCmd.Name, cmd.Name, + ) + + applyPersistentFlag := true + + for _, name := range flNames { + if cmd.lFlag(name) != nil { + applyPersistentFlag = false + break + } + } + + if !applyPersistentFlag { + tracef("not applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + continue + } + + tracef("applying as persistent flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + + tracef("appending to applied flags flag=%[1]q (cmd=%[2]q)", flNames, cmd.Name) + cmd.appliedFlags = append(cmd.appliedFlags, fl) + } + } + + tracef("parsing flags iteratively tail=%[1]q (cmd=%[2]q)", args.Tail(), cmd.Name) + defer tracef("done parsing flags (cmd=%[1]q)", cmd.Name) + + posArgs := []string{} + for rargs := args.Slice(); len(rargs) > 0; rargs = rargs[1:] { + tracef("rearrange:1 (cmd=%[1]q) %[2]q", cmd.Name, rargs) + + firstArg := strings.TrimSpace(rargs[0]) + if len(firstArg) == 0 { + break + } + + // stop parsing once we see a "--" + if firstArg == "--" { + posArgs = append(posArgs, rargs[1:]...) + return &stringSliceArgs{posArgs}, nil + } + + // handle positional args + if firstArg[0] != '-' { + // positional argument probably + tracef("rearrange-3 (cmd=%[1]q) check %[2]q", cmd.Name, firstArg) + + // if there is a command by that name let the command handle the + // rest of the parsing + if cmd.Command(firstArg) != nil { + posArgs = append(posArgs, rargs...) + return &stringSliceArgs{posArgs}, nil + } + + posArgs = append(posArgs, firstArg) + continue + } + + numMinuses := 1 + // this is same as firstArg == "-" + if len(firstArg) == 1 { + posArgs = append(posArgs, firstArg) + break + } + + shortOptionHandling := cmd.useShortOptionHandling() + + // stop parsing -- as short flags + if firstArg[1] == '-' { + numMinuses++ + shortOptionHandling = false + } else if !unicode.IsLetter(rune(firstArg[1])) { + // this is not a flag + tracef("parseFlags not a unicode letter. Stop parsing") + posArgs = append(posArgs, rargs...) + return &stringSliceArgs{posArgs}, nil + } + + tracef("parseFlags (shortOptionHandling=%[1]q)", shortOptionHandling) + + flagName := firstArg[numMinuses:] + flagVal := "" + tracef("flagName:1 (fName=%[1]q)", flagName) + if index := strings.Index(flagName, "="); index != -1 { + flagVal = flagName[index+1:] + flagName = flagName[:index] + } + + tracef("flagName:2 (fName=%[1]q) (fVal=%[2]q)", flagName, flagVal) + + f := cmd.lookupFlag(flagName) + // found a flag matching given flagName + if f != nil { + tracef("Trying flag type (fName=%[1]q) (type=%[2]T)", flagName, f) + if fb, ok := f.(boolFlag); ok && fb.IsBoolFlag() { + if flagVal == "" { + flagVal = "true" + } + tracef("parse Apply bool flag (fName=%[1]q) (fVal=%[2]q)", flagName, flagVal) + if err := cmd.set(flagName, f, flagVal); err != nil { + return &stringSliceArgs{posArgs}, err + } + continue + } + + tracef("processing non bool flag (fName=%[1]q)", flagName) + // not a bool flag so need to get the next arg + if flagVal == "" { + if len(rargs) == 1 { + return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", argumentNotProvidedErrMsg, firstArg) + } + flagVal = rargs[1] + rargs = rargs[1:] + } + + tracef("setting non bool flag (fName=%[1]q) (fVal=%[2]q)", flagName, flagVal) + if err := cmd.set(flagName, f, flagVal); err != nil { + return &stringSliceArgs{posArgs}, err + } + + continue + } + + // no flag lookup found and short handling is disabled + if !shortOptionHandling { + return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName) + } + + // try to split the flags + for index, c := range flagName { + tracef("processing flag (fName=%[1]q)", string(c)) + if sf := cmd.lookupFlag(string(c)); sf == nil { + return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", providedButNotDefinedErrMsg, flagName) + } else if fb, ok := sf.(boolFlag); ok && fb.IsBoolFlag() { + fv := flagVal + if index == (len(flagName)-1) && flagVal == "" { + fv = "true" + } + if fv == "" { + fv = "true" + } + if err := cmd.set(flagName, sf, fv); err != nil { + tracef("processing flag.2 (fName=%[1]q)", string(c)) + return &stringSliceArgs{posArgs}, err + } + } else if index == len(flagName)-1 { // last flag can take an arg + if flagVal == "" { + if len(rargs) == 1 { + return &stringSliceArgs{posArgs}, fmt.Errorf("%s%s", argumentNotProvidedErrMsg, string(c)) + } + flagVal = rargs[1] + } + tracef("parseFlags (flagName %[1]q) (flagVal %[2]q)", flagName, flagVal) + if err := cmd.set(flagName, sf, flagVal); err != nil { + tracef("processing flag.4 (fName=%[1]q)", string(c)) + return &stringSliceArgs{posArgs}, err + } + } + } + } + + tracef("returning-2 (cmd=%[1]q) args %[2]q", cmd.Name, posArgs) + return &stringSliceArgs{posArgs}, nil +} diff --git a/vendor/github.com/urfave/cli/v3/command_run.go b/vendor/github.com/urfave/cli/v3/command_run.go new file mode 100644 index 00000000..6b2abc1b --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/command_run.go @@ -0,0 +1,351 @@ +package cli + +import ( + "bufio" + "context" + "fmt" + "io" + "reflect" + "slices" + "unicode" +) + +func (cmd *Command) parseArgsFromStdin() ([]string, error) { + type state int + const ( + stateSearchForToken state = -1 + stateSearchForString state = 0 + ) + + st := stateSearchForToken + linenum := 1 + token := "" + args := []string{} + + breader := bufio.NewReader(cmd.Reader) + +outer: + for { + ch, _, err := breader.ReadRune() + if err == io.EOF { + switch st { + case stateSearchForToken: + if token != "--" { + args = append(args, token) + } + case stateSearchForString: + // make sure string is not empty + for _, t := range token { + if !unicode.IsSpace(t) { + args = append(args, token) + } + } + } + break outer + } + if err != nil { + return nil, err + } + switch st { + case stateSearchForToken: + if unicode.IsSpace(ch) || ch == '"' { + if ch == '\n' { + linenum++ + } + if token != "" { + // end the processing here + if token == "--" { + break outer + } + args = append(args, token) + token = "" + } + if ch == '"' { + st = stateSearchForString + } + continue + } + token += string(ch) + case stateSearchForString: + if ch != '"' { + token += string(ch) + } else { + if token != "" { + args = append(args, token) + token = "" + } + /*else { + //TODO. Should we pass in empty strings ? + }*/ + st = stateSearchForToken + } + } + } + + tracef("parsed stdin args as %v (cmd=%[2]q)", args, cmd.Name) + + return args, nil +} + +// Run is the entry point to the command graph. The positional +// arguments are parsed according to the Flag and Command +// definitions and the matching Action functions are run. +func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) { + _, deferErr = cmd.run(ctx, osArgs) + return +} + +func (cmd *Command) run(ctx context.Context, osArgs []string) (_ context.Context, deferErr error) { + tracef("running with arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) + cmd.setupDefaults(osArgs) + + if v, ok := ctx.Value(commandContextKey).(*Command); ok { + tracef("setting parent (cmd=%[1]q) command from context.Context value (cmd=%[2]q)", v.Name, cmd.Name) + cmd.parent = v + } + + if cmd.parent == nil { + if cmd.ReadArgsFromStdin { + if args, err := cmd.parseArgsFromStdin(); err != nil { + return ctx, err + } else { + osArgs = append(osArgs, args...) + } + } + // handle the completion flag separately from the flagset since + // completion could be attempted after a flag, but before its value was put + // on the command line. this causes the flagset to interpret the completion + // flag name as the value of the flag before it which is undesirable + // note that we can only do this because the shell autocomplete function + // always appends the completion flag at the end of the command + tracef("checking osArgs %v (cmd=%[2]q)", osArgs, cmd.Name) + cmd.shellCompletion, osArgs = checkShellCompleteFlag(cmd, osArgs) + + tracef("setting cmd.shellCompletion=%[1]v from checkShellCompleteFlag (cmd=%[2]q)", cmd.shellCompletion && cmd.EnableShellCompletion, cmd.Name) + cmd.shellCompletion = cmd.EnableShellCompletion && cmd.shellCompletion + } + + tracef("using post-checkShellCompleteFlag arguments %[1]q (cmd=%[2]q)", osArgs, cmd.Name) + + tracef("setting self as cmd in context (cmd=%[1]q)", cmd.Name) + ctx = context.WithValue(ctx, commandContextKey, cmd) + + if cmd.parent == nil { + cmd.setupCommandGraph() + } + + var rargs Args = &stringSliceArgs{v: osArgs} + for _, f := range cmd.allFlags() { + if err := f.PreParse(); err != nil { + return ctx, err + } + } + + var args Args = &stringSliceArgs{rargs.Tail()} + var err error + + if cmd.SkipFlagParsing { + tracef("skipping flag parsing (cmd=%[1]q)", cmd.Name) + cmd.parsedArgs = args + } else { + cmd.parsedArgs, err = cmd.parseFlags(args) + } + + tracef("using post-parse arguments %[1]q (cmd=%[2]q)", args, cmd.Name) + + if checkCompletions(ctx, cmd) { + return ctx, nil + } + + if err != nil { + tracef("setting deferErr from %[1]q (cmd=%[2]q)", err, cmd.Name) + deferErr = err + + cmd.isInError = true + if cmd.OnUsageError != nil { + err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) + err = cmd.handleExitCoder(ctx, err) + return ctx, err + } + fmt.Fprintf(cmd.Root().ErrWriter, "Incorrect Usage: %s\n\n", err.Error()) + if cmd.Suggest { + if suggestion, err := cmd.suggestFlagFromError(err, ""); err == nil { + fmt.Fprintf(cmd.Root().ErrWriter, "%s", suggestion) + } + } + if !cmd.hideHelp() { + if cmd.parent == nil { + tracef("running ShowRootCommandHelp") + if err := ShowRootCommandHelp(cmd); err != nil { + tracef("SILENTLY IGNORING ERROR running ShowRootCommandHelp %[1]v (cmd=%[2]q)", err, cmd.Name) + } + } else { + tracef("running ShowCommandHelp with %[1]q", cmd.Name) + if err := ShowCommandHelp(ctx, cmd, cmd.Name); err != nil { + tracef("SILENTLY IGNORING ERROR running ShowCommandHelp with %[1]q %[2]v", cmd.Name, err) + } + } + } + + return ctx, err + } + + if cmd.checkHelp() { + return ctx, helpCommandAction(ctx, cmd) + } else { + tracef("no help is wanted (cmd=%[1]q)", cmd.Name) + } + + if cmd.parent == nil && !cmd.HideVersion && checkVersion(cmd) { + ShowVersion(cmd) + return ctx, nil + } + + for _, flag := range cmd.allFlags() { + if err := flag.PostParse(); err != nil { + return ctx, err + } + } + + if cmd.After != nil && !cmd.Root().shellCompletion { + defer func() { + if err := cmd.After(ctx, cmd); err != nil { + err = cmd.handleExitCoder(ctx, err) + + if deferErr != nil { + deferErr = newMultiError(deferErr, err) + } else { + deferErr = err + } + } + }() + } + + for _, grp := range cmd.MutuallyExclusiveFlags { + if err := grp.check(cmd); err != nil { + if cmd.OnUsageError != nil { + err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) + } else { + _ = ShowSubcommandHelp(cmd) + } + return ctx, err + } + } + + var subCmd *Command + if cmd.parsedArgs.Present() { + tracef("checking positional args %[1]q (cmd=%[2]q)", cmd.parsedArgs, cmd.Name) + + name := cmd.parsedArgs.First() + + tracef("using first positional argument as sub-command name=%[1]q (cmd=%[2]q)", name, cmd.Name) + + if cmd.SuggestCommandFunc != nil && name != "--" { + name = cmd.SuggestCommandFunc(cmd.Commands, name) + } + subCmd = cmd.Command(name) + if subCmd == nil { + hasDefault := cmd.DefaultCommand != "" + isFlagName := slices.Contains(cmd.FlagNames(), name) + + if hasDefault { + tracef("using default command=%[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) + } + + if isFlagName || hasDefault { + argsWithDefault := cmd.argsWithDefaultCommand(args) + tracef("using default command args=%[1]q (cmd=%[2]q)", argsWithDefault, cmd.Name) + if !reflect.DeepEqual(args, argsWithDefault) { + subCmd = cmd.Command(argsWithDefault.First()) + } + } + } + } else if cmd.parent == nil && cmd.DefaultCommand != "" { + tracef("no positional args present; checking default command %[1]q (cmd=%[2]q)", cmd.DefaultCommand, cmd.Name) + + if dc := cmd.Command(cmd.DefaultCommand); dc != cmd { + subCmd = dc + } + } + + // If a subcommand has been resolved, let it handle the remaining execution. + if subCmd != nil { + tracef("running sub-command %[1]q with arguments %[2]q (cmd=%[3]q)", subCmd.Name, cmd.Args(), cmd.Name) + + // It is important that we overwrite the ctx variable in the current + // function so any defer'd functions use the new context returned + // from the sub command. + ctx, err = subCmd.run(ctx, cmd.Args().Slice()) + return ctx, err + } + + // This code path is the innermost command execution. Here we actually + // perform the command action. + // + // First, resolve the chain of nested commands up to the parent. + var cmdChain []*Command + for p := cmd; p != nil; p = p.parent { + cmdChain = append(cmdChain, p) + } + slices.Reverse(cmdChain) + + // Run Before actions in order. + for _, cmd := range cmdChain { + if cmd.Before == nil { + continue + } + if bctx, err := cmd.Before(ctx, cmd); err != nil { + deferErr = cmd.handleExitCoder(ctx, err) + return ctx, deferErr + } else if bctx != nil { + ctx = bctx + } + } + + // Run flag actions in order. + // These take a context, so this has to happen after Before actions. + for _, cmd := range cmdChain { + tracef("running flag actions (cmd=%[1]q)", cmd.Name) + if err := cmd.runFlagActions(ctx); err != nil { + deferErr = cmd.handleExitCoder(ctx, err) + return ctx, deferErr + } + } + + if err := cmd.checkAllRequiredFlags(); err != nil { + cmd.isInError = true + if cmd.OnUsageError != nil { + err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) + } else { + _ = ShowSubcommandHelp(cmd) + } + return ctx, err + } + + // Run the command action. + if len(cmd.Arguments) > 0 { + rargs := cmd.Args().Slice() + tracef("calling argparse with %[1]v", rargs) + for _, arg := range cmd.Arguments { + var err error + rargs, err = arg.Parse(rargs) + if err != nil { + tracef("calling with %[1]v (cmd=%[2]q)", err, cmd.Name) + if cmd.OnUsageError != nil { + err = cmd.OnUsageError(ctx, cmd, err, cmd.parent != nil) + } + err = cmd.handleExitCoder(ctx, err) + return ctx, err + } + } + cmd.parsedArgs = &stringSliceArgs{v: rargs} + } + + if err := cmd.Action(ctx, cmd); err != nil { + tracef("calling handleExitCoder with %[1]v (cmd=%[2]q)", err, cmd.Name) + deferErr = cmd.handleExitCoder(ctx, err) + } + + tracef("returning deferErr (cmd=%[1]q) %[2]q", cmd.Name, deferErr) + return ctx, deferErr +} diff --git a/vendor/github.com/urfave/cli/v3/command_setup.go b/vendor/github.com/urfave/cli/v3/command_setup.go new file mode 100644 index 00000000..09df4a30 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/command_setup.go @@ -0,0 +1,214 @@ +package cli + +import ( + "flag" + "os" + "path/filepath" + "sort" + "strings" +) + +func (cmd *Command) setupDefaults(osArgs []string) { + if cmd.didSetupDefaults { + tracef("already did setup (cmd=%[1]q)", cmd.Name) + return + } + + cmd.didSetupDefaults = true + + isRoot := cmd.parent == nil + tracef("isRoot? %[1]v (cmd=%[2]q)", isRoot, cmd.Name) + + if cmd.ShellComplete == nil { + tracef("setting default ShellComplete (cmd=%[1]q)", cmd.Name) + cmd.ShellComplete = DefaultCompleteWithFlags + } + + if cmd.Name == "" && isRoot { + name := filepath.Base(osArgs[0]) + tracef("setting cmd.Name from first arg basename (cmd=%[1]q)", name) + cmd.Name = name + } + + if cmd.Usage == "" && isRoot { + tracef("setting default Usage (cmd=%[1]q)", cmd.Name) + cmd.Usage = "A new cli application" + } + + if cmd.Version == "" { + tracef("setting HideVersion=true due to empty Version (cmd=%[1]q)", cmd.Name) + cmd.HideVersion = true + } + + if cmd.Action == nil { + tracef("setting default Action as help command action (cmd=%[1]q)", cmd.Name) + cmd.Action = helpCommandAction + } + + if cmd.Reader == nil { + tracef("setting default Reader as os.Stdin (cmd=%[1]q)", cmd.Name) + cmd.Reader = os.Stdin + } + + if cmd.Writer == nil { + tracef("setting default Writer as os.Stdout (cmd=%[1]q)", cmd.Name) + cmd.Writer = os.Stdout + } + + if cmd.ErrWriter == nil { + tracef("setting default ErrWriter as os.Stderr (cmd=%[1]q)", cmd.Name) + cmd.ErrWriter = os.Stderr + } + + if cmd.AllowExtFlags { + tracef("visiting all flags given AllowExtFlags=true (cmd=%[1]q)", cmd.Name) + // add global flags added by other packages + flag.VisitAll(func(f *flag.Flag) { + // skip test flags + if !strings.HasPrefix(f.Name, ignoreFlagPrefix) { + cmd.Flags = append(cmd.Flags, &extFlag{f}) + } + }) + } + + for _, subCmd := range cmd.Commands { + tracef("setting sub-command (cmd=%[1]q) parent as self (cmd=%[2]q)", subCmd.Name, cmd.Name) + subCmd.parent = cmd + } + + cmd.ensureHelp() + + if !cmd.HideVersion && isRoot { + tracef("appending version flag (cmd=%[1]q)", cmd.Name) + cmd.appendFlag(VersionFlag) + } + + if cmd.PrefixMatchCommands && cmd.SuggestCommandFunc == nil { + tracef("setting default SuggestCommandFunc (cmd=%[1]q)", cmd.Name) + cmd.SuggestCommandFunc = suggestCommand + } + + if isRoot && cmd.EnableShellCompletion || cmd.ConfigureShellCompletionCommand != nil { + completionCommand := buildCompletionCommand(cmd.Name) + + if cmd.ShellCompletionCommandName != "" { + tracef( + "setting completion command name (%[1]q) from "+ + "cmd.ShellCompletionCommandName (cmd=%[2]q)", + cmd.ShellCompletionCommandName, cmd.Name, + ) + completionCommand.Name = cmd.ShellCompletionCommandName + } + + tracef("appending completionCommand (cmd=%[1]q)", cmd.Name) + cmd.appendCommand(completionCommand) + if cmd.ConfigureShellCompletionCommand != nil { + cmd.ConfigureShellCompletionCommand(completionCommand) + } + } + + tracef("setting command categories (cmd=%[1]q)", cmd.Name) + cmd.categories = newCommandCategories() + + for _, subCmd := range cmd.Commands { + cmd.categories.AddCommand(subCmd.Category, subCmd) + } + + tracef("sorting command categories (cmd=%[1]q)", cmd.Name) + sort.Sort(cmd.categories.(*commandCategories)) + + tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name) + for _, grp := range cmd.MutuallyExclusiveFlags { + grp.propagateCategory() + } + + tracef("setting flag categories (cmd=%[1]q)", cmd.Name) + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) + + if cmd.Metadata == nil { + tracef("setting default Metadata (cmd=%[1]q)", cmd.Name) + cmd.Metadata = map[string]any{} + } + + if len(cmd.SliceFlagSeparator) != 0 { + tracef("setting defaultSliceFlagSeparator from cmd.SliceFlagSeparator (cmd=%[1]q)", cmd.Name) + defaultSliceFlagSeparator = cmd.SliceFlagSeparator + } + + tracef("setting disableSliceFlagSeparator from cmd.DisableSliceFlagSeparator (cmd=%[1]q)", cmd.Name) + disableSliceFlagSeparator = cmd.DisableSliceFlagSeparator + + cmd.setFlags = map[Flag]struct{}{} +} + +func (cmd *Command) setupCommandGraph() { + tracef("setting up command graph (cmd=%[1]q)", cmd.Name) + + for _, subCmd := range cmd.Commands { + subCmd.parent = cmd + subCmd.setupSubcommand() + subCmd.setupCommandGraph() + } +} + +func (cmd *Command) setupSubcommand() { + tracef("setting up self as sub-command (cmd=%[1]q)", cmd.Name) + + cmd.ensureHelp() + + tracef("setting command categories (cmd=%[1]q)", cmd.Name) + cmd.categories = newCommandCategories() + + for _, subCmd := range cmd.Commands { + cmd.categories.AddCommand(subCmd.Category, subCmd) + } + + tracef("sorting command categories (cmd=%[1]q)", cmd.Name) + sort.Sort(cmd.categories.(*commandCategories)) + + tracef("setting category on mutually exclusive flags (cmd=%[1]q)", cmd.Name) + for _, grp := range cmd.MutuallyExclusiveFlags { + grp.propagateCategory() + } + + tracef("setting flag categories (cmd=%[1]q)", cmd.Name) + cmd.flagCategories = newFlagCategoriesFromFlags(cmd.allFlags()) +} + +func (cmd *Command) hideHelp() bool { + tracef("hide help (cmd=%[1]q)", cmd.Name) + for c := cmd; c != nil; c = c.parent { + if c.HideHelp { + return true + } + } + + return false +} + +func (cmd *Command) ensureHelp() { + tracef("ensuring help (cmd=%[1]q)", cmd.Name) + + helpCommand := buildHelpCommand(true) + + if !cmd.hideHelp() { + if cmd.Command(helpCommand.Name) == nil { + if !cmd.HideHelpCommand { + tracef("appending helpCommand (cmd=%[1]q)", cmd.Name) + cmd.appendCommand(helpCommand) + } + } + + if HelpFlag != nil { + // TODO need to remove hack + if hf, ok := HelpFlag.(*BoolFlag); ok { + hf.applied = false + hf.hasBeenSet = false + hf.Value = false + hf.value = nil + } + tracef("appending HelpFlag (cmd=%[1]q)", cmd.Name) + cmd.appendFlag(HelpFlag) + } + } +} diff --git a/vendor/github.com/urfave/cli/v3/completion.go b/vendor/github.com/urfave/cli/v3/completion.go new file mode 100644 index 00000000..d97ade6e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/completion.go @@ -0,0 +1,100 @@ +package cli + +import ( + "context" + "embed" + "fmt" + "sort" + "strings" +) + +const ( + completionCommandName = "completion" + + // This flag is supposed to only be used by the completion script itself to generate completions on the fly. + completionFlag = "--generate-shell-completion" +) + +type renderCompletion func(cmd *Command, appName string) (string, error) + +var ( + //go:embed autocomplete + autoCompleteFS embed.FS + + shellCompletions = map[string]renderCompletion{ + "bash": func(c *Command, appName string) (string, error) { + b, err := autoCompleteFS.ReadFile("autocomplete/bash_autocomplete") + return fmt.Sprintf(string(b), appName), err + }, + "zsh": func(c *Command, appName string) (string, error) { + b, err := autoCompleteFS.ReadFile("autocomplete/zsh_autocomplete") + return fmt.Sprintf(string(b), appName), err + }, + "fish": func(c *Command, appName string) (string, error) { + return c.Root().ToFishCompletion() + }, + "pwsh": func(c *Command, appName string) (string, error) { + b, err := autoCompleteFS.ReadFile("autocomplete/powershell_autocomplete.ps1") + return string(b), err + }, + } +) + +const completionDescription = `Output shell completion script for bash, zsh, fish, or Powershell. +Source the output to enable completion. + +# .bashrc +source <($COMMAND completion bash) + +# .zshrc +source <($COMMAND completion zsh) + +# fish +$COMMAND completion fish > ~/.config/fish/completions/$COMMAND.fish + +# Powershell +Output the script to path/to/autocomplete/$COMMAND.ps1 an run it. +` + +func buildCompletionCommand(appName string) *Command { + return &Command{ + Name: completionCommandName, + Hidden: true, + Usage: "Output shell completion script for bash, zsh, fish, or Powershell", + Description: strings.ReplaceAll(completionDescription, "$COMMAND", appName), + Action: func(ctx context.Context, cmd *Command) error { + return printShellCompletion(ctx, cmd, appName) + }, + } +} + +func printShellCompletion(_ context.Context, cmd *Command, appName string) error { + var shells []string + for k := range shellCompletions { + shells = append(shells, k) + } + + sort.Strings(shells) + + if cmd.Args().Len() == 0 { + return Exit(fmt.Sprintf("no shell provided for completion command. available shells are %+v", shells), 1) + } + s := cmd.Args().First() + + renderCompletion, ok := shellCompletions[s] + if !ok { + return Exit(fmt.Sprintf("unknown shell %s, available shells are %+v", s, shells), 1) + } + + completionScript, err := renderCompletion(cmd, appName) + if err != nil { + return Exit(err, 1) + } + + _, err = cmd.Writer.Write([]byte(completionScript)) + if err != nil { + return Exit(err, 1) + } + + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/docs.go b/vendor/github.com/urfave/cli/v3/docs.go new file mode 100644 index 00000000..42cad718 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/docs.go @@ -0,0 +1,125 @@ +package cli + +import ( + "fmt" + "os" + "runtime" + "strings" +) + +func prefixFor(name string) (prefix string) { + if len(name) == 1 { + prefix = "-" + } else { + prefix = "--" + } + + return +} + +// Returns the placeholder, if any, and the unquoted usage string. +func unquoteUsage(usage string) (string, string) { + for i := 0; i < len(usage); i++ { + if usage[i] == '`' { + for j := i + 1; j < len(usage); j++ { + if usage[j] == '`' { + name := usage[i+1 : j] + usage = usage[:i] + name + usage[j+1:] + return name, usage + } + } + break + } + } + return "", usage +} + +func prefixedNames(names []string, placeholder string) string { + var prefixed string + for i, name := range names { + if name == "" { + continue + } + + prefixed += prefixFor(name) + name + if placeholder != "" { + prefixed += " " + placeholder + } + if i < len(names)-1 { + prefixed += ", " + } + } + return prefixed +} + +func envFormat(envVars []string, prefix, sep, suffix string) string { + if len(envVars) > 0 { + return fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(envVars, sep), suffix) + } + return "" +} + +func defaultEnvFormat(envVars []string) string { + return envFormat(envVars, "$", ", $", "") +} + +func withEnvHint(envVars []string, str string) string { + envText := "" + if runtime.GOOS != "windows" || os.Getenv("PSHOME") != "" { + envText = defaultEnvFormat(envVars) + } else { + envText = envFormat(envVars, "%", "%, %", "%") + } + return str + envText +} + +func withFileHint(filePath, str string) string { + fileText := "" + if filePath != "" { + fileText = fmt.Sprintf(" [%s]", filePath) + } + return str + fileText +} + +func formatDefault(format string) string { + return " (default: " + format + ")" +} + +func stringifyFlag(f Flag) string { + // enforce DocGeneration interface on flags to avoid reflection + df, ok := f.(DocGenerationFlag) + if !ok { + return "" + } + placeholder, usage := unquoteUsage(df.GetUsage()) + needsPlaceholder := df.TakesValue() + // if needsPlaceholder is true, placeholder is empty + if needsPlaceholder && placeholder == "" { + // try to get type from flag + if tname := df.TypeName(); tname != "" { + placeholder = tname + } else { + placeholder = defaultPlaceholder + } + } + + defaultValueString := "" + + // don't print default text for required flags + if rf, ok := f.(RequiredFlag); !ok || !rf.IsRequired() { + isVisible := df.IsDefaultVisible() + if s := df.GetDefaultText(); isVisible && s != "" { + defaultValueString = fmt.Sprintf(formatDefault("%s"), s) + } + } + + usageWithDefault := strings.TrimSpace(usage + defaultValueString) + + pn := prefixedNames(f.Names(), placeholder) + sliceFlag, ok := f.(DocGenerationMultiValueFlag) + if ok && sliceFlag.IsMultiValueFlag() { + pn = pn + " [ " + pn + " ]" + } + + return withEnvHint(df.GetEnvVars(), fmt.Sprintf("%s\t%s", pn, usageWithDefault)) +} diff --git a/vendor/github.com/urfave/cli/v3/errors.go b/vendor/github.com/urfave/cli/v3/errors.go new file mode 100644 index 00000000..a1188e73 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/errors.go @@ -0,0 +1,184 @@ +package cli + +import ( + "fmt" + "io" + "os" + "strings" +) + +// OsExiter is the function used when the app exits. If not set defaults to os.Exit. +var OsExiter = os.Exit + +// ErrWriter is used to write errors to the user. This can be anything +// implementing the io.Writer interface and defaults to os.Stderr. +var ErrWriter io.Writer = os.Stderr + +// MultiError is an error that wraps multiple errors. +type MultiError interface { + error + Errors() []error +} + +// newMultiError creates a new MultiError. Pass in one or more errors. +func newMultiError(err ...error) MultiError { + ret := multiError(err) + return &ret +} + +type multiError []error + +// Error implements the error interface. +func (m *multiError) Error() string { + errs := make([]string, len(*m)) + for i, err := range *m { + errs[i] = err.Error() + } + + return strings.Join(errs, "\n") +} + +// Errors returns a copy of the errors slice +func (m *multiError) Errors() []error { + errs := make([]error, len(*m)) + copy(errs, *m) + return errs +} + +type requiredFlagsErr interface { + error +} + +type errRequiredFlags struct { + missingFlags []string +} + +func (e *errRequiredFlags) Error() string { + if len(e.missingFlags) == 1 { + return fmt.Sprintf("Required flag %q not set", e.missingFlags[0]) + } + joinedMissingFlags := strings.Join(e.missingFlags, ", ") + return fmt.Sprintf("Required flags %q not set", joinedMissingFlags) +} + +type mutuallyExclusiveGroup struct { + flag1Name string + flag2Name string +} + +func (e *mutuallyExclusiveGroup) Error() string { + return fmt.Sprintf("option %s cannot be set along with option %s", e.flag1Name, e.flag2Name) +} + +type mutuallyExclusiveGroupRequiredFlag struct { + flags *MutuallyExclusiveFlags +} + +func (e *mutuallyExclusiveGroupRequiredFlag) Error() string { + var missingFlags []string + for _, grpf := range e.flags.Flags { + var grpString []string + for _, f := range grpf { + grpString = append(grpString, f.Names()...) + } + missingFlags = append(missingFlags, strings.Join(grpString, " ")) + } + + return fmt.Sprintf("one of these flags needs to be provided: %s", strings.Join(missingFlags, ", ")) +} + +// ErrorFormatter is the interface that will suitably format the error output +type ErrorFormatter interface { + Format(s fmt.State, verb rune) +} + +// ExitCoder is the interface checked by `Command` for a custom exit code. +type ExitCoder interface { + error + ExitCode() int +} + +type exitError struct { + exitCode int + err error +} + +// Exit wraps a message and exit code into an error, which by default is +// handled with a call to os.Exit during default error handling. +// +// This is the simplest way to trigger a non-zero exit code for a Command without +// having to call os.Exit manually. During testing, this behavior can be avoided +// by overriding the ExitErrHandler function on a Command or the package-global +// OsExiter function. +func Exit(message any, exitCode int) ExitCoder { + var err error + + switch e := message.(type) { + case ErrorFormatter: + err = fmt.Errorf("%+v", message) + case error: + err = e + default: + err = fmt.Errorf("%+v", message) + } + + return &exitError{ + err: err, + exitCode: exitCode, + } +} + +func (ee *exitError) Error() string { + return ee.err.Error() +} + +func (ee *exitError) ExitCode() int { + return ee.exitCode +} + +// HandleExitCoder handles errors implementing ExitCoder by printing their +// message and calling OsExiter with the given exit code. +// +// If the given error instead implements MultiError, each error will be checked +// for the ExitCoder interface, and OsExiter will be called with the last exit +// code found, or exit code 1 if no ExitCoder is found. +// +// This function is the default error-handling behavior for a Command. +func HandleExitCoder(err error) { + if err == nil { + return + } + + if exitErr, ok := err.(ExitCoder); ok { + if err.Error() != "" { + if _, ok := exitErr.(ErrorFormatter); ok { + _, _ = fmt.Fprintf(ErrWriter, "%+v\n", err) + } else { + _, _ = fmt.Fprintln(ErrWriter, err) + } + } + OsExiter(exitErr.ExitCode()) + return + } + + if multiErr, ok := err.(MultiError); ok { + code := handleMultiError(multiErr) + OsExiter(code) + return + } +} + +func handleMultiError(multiErr MultiError) int { + code := 1 + for _, merr := range multiErr.Errors() { + if multiErr2, ok := merr.(MultiError); ok { + code = handleMultiError(multiErr2) + } else if merr != nil { + fmt.Fprintln(ErrWriter, merr) + if exitErr, ok := merr.(ExitCoder); ok { + code = exitErr.ExitCode() + } + } + } + return code +} diff --git a/vendor/github.com/urfave/cli/v3/fish.go b/vendor/github.com/urfave/cli/v3/fish.go new file mode 100644 index 00000000..1607f55b --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/fish.go @@ -0,0 +1,189 @@ +package cli + +import ( + "bytes" + "fmt" + "io" + "strings" + "text/template" +) + +// ToFishCompletion creates a fish completion string for the `*Command` +// The function errors if either parsing or writing of the string fails. +func (cmd *Command) ToFishCompletion() (string, error) { + var w bytes.Buffer + if err := cmd.writeFishCompletionTemplate(&w); err != nil { + return "", err + } + return w.String(), nil +} + +type fishCommandCompletionTemplate struct { + Command *Command + Completions []string + AllCommands []string +} + +func (cmd *Command) writeFishCompletionTemplate(w io.Writer) error { + const name = "cli" + t, err := template.New(name).Parse(FishCompletionTemplate) + if err != nil { + return err + } + + // Add global flags + completions := prepareFishFlags(cmd.Name, cmd) + + // Add commands and their flags + completions = append( + completions, + prepareFishCommands(cmd.Name, cmd)..., + ) + + toplevelCommandNames := []string{} + for _, child := range cmd.Commands { + toplevelCommandNames = append(toplevelCommandNames, child.Names()...) + } + + return t.ExecuteTemplate(w, name, &fishCommandCompletionTemplate{ + Command: cmd, + Completions: completions, + AllCommands: toplevelCommandNames, + }) +} + +func prepareFishCommands(binary string, parent *Command) []string { + commands := parent.Commands + completions := []string{} + for _, command := range commands { + if !command.Hidden { + var completion strings.Builder + fmt.Fprintf(&completion, + "complete -x -c %s -n '%s' -a '%s'", + binary, + fishSubcommandHelper(binary, parent, commands), + command.Name, + ) + + if command.Usage != "" { + fmt.Fprintf(&completion, + " -d '%s'", + escapeSingleQuotes(command.Usage)) + } + completions = append(completions, completion.String()) + } + completions = append( + completions, + prepareFishFlags(binary, command)..., + ) + + // recursively iterate subcommands + completions = append( + completions, + prepareFishCommands(binary, command)..., + ) + } + + return completions +} + +func prepareFishFlags(binary string, owner *Command) []string { + flags := owner.VisibleFlags() + completions := []string{} + for _, f := range flags { + completion := &strings.Builder{} + fmt.Fprintf(completion, + "complete -c %s -n '%s'", + binary, + fishFlagHelper(binary, owner), + ) + + fishAddFileFlag(f, completion) + + for idx, opt := range f.Names() { + if idx == 0 { + fmt.Fprintf(completion, + " -l %s", strings.TrimSpace(opt), + ) + } else { + fmt.Fprintf(completion, + " -s %s", strings.TrimSpace(opt), + ) + } + } + + if flag, ok := f.(DocGenerationFlag); ok { + if flag.TakesValue() { + completion.WriteString(" -r") + } + + if flag.GetUsage() != "" { + fmt.Fprintf(completion, + " -d '%s'", + escapeSingleQuotes(flag.GetUsage())) + } + } + + completions = append(completions, completion.String()) + } + + return completions +} + +func fishAddFileFlag(flag Flag, completion *strings.Builder) { + switch f := flag.(type) { + case *StringFlag: + if f.TakesFile { + return + } + case *StringSliceFlag: + if f.TakesFile { + return + } + } + completion.WriteString(" -f") +} + +func fishSubcommandHelper(binary string, command *Command, siblings []*Command) string { + fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", binary) + if len(command.Lineage()) > 1 { + var siblingNames []string + for _, sibling := range siblings { + siblingNames = append(siblingNames, sibling.Names()...) + } + ancestry := commandAncestry(command) + fishHelper = fmt.Sprintf( + "%s; and not __fish_seen_subcommand_from %s", + ancestry, + strings.Join(siblingNames, " "), + ) + } + return fishHelper +} + +func fishFlagHelper(binary string, command *Command) string { + fishHelper := fmt.Sprintf("__fish_%s_no_subcommand", binary) + if len(command.Lineage()) > 1 { + fishHelper = commandAncestry(command) + } + return fishHelper +} + +func commandAncestry(command *Command) string { + var ancestry []string + ancestors := command.Lineage() + for i := len(ancestors) - 2; i >= 0; i-- { + ancestry = append( + ancestry, + fmt.Sprintf( + "__fish_seen_subcommand_from %s", + strings.Join(ancestors[i].Names(), " "), + ), + ) + } + return strings.Join(ancestry, "; and ") +} + +func escapeSingleQuotes(input string) string { + return strings.ReplaceAll(input, `'`, `\'`) +} diff --git a/vendor/github.com/urfave/cli/v3/flag.go b/vendor/github.com/urfave/cli/v3/flag.go new file mode 100644 index 00000000..a5bd5474 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag.go @@ -0,0 +1,231 @@ +package cli + +import ( + "context" + "fmt" + "regexp" + "strings" + "time" +) + +const defaultPlaceholder = "value" + +var ( + defaultSliceFlagSeparator = "," + defaultMapFlagKeyValueSeparator = "=" + disableSliceFlagSeparator = false +) + +var ( + slPfx = fmt.Sprintf("sl:::%d:::", time.Now().UTC().UnixNano()) + + commaWhitespace = regexp.MustCompile("[, ]+.*") +) + +// GenerateShellCompletionFlag enables shell completion +var GenerateShellCompletionFlag Flag = &BoolFlag{ + Name: "generate-shell-completion", + Hidden: true, +} + +// VersionFlag prints the version for the application +var VersionFlag Flag = &BoolFlag{ + Name: "version", + Aliases: []string{"v"}, + Usage: "print the version", + HideDefault: true, + Local: true, +} + +// HelpFlag prints the help for all commands and subcommands. +// Set to nil to disable the flag. The subcommand +// will still be added unless HideHelp or HideHelpCommand is set to true. +var HelpFlag Flag = &BoolFlag{ + Name: "help", + Aliases: []string{"h"}, + Usage: "show help", + HideDefault: true, + Local: true, +} + +// FlagStringer converts a flag definition to a string. This is used by help +// to display a flag. +var FlagStringer FlagStringFunc = stringifyFlag + +// Serializer is used to circumvent the limitations of flag.FlagSet.Set +type Serializer interface { + Serialize() string +} + +// FlagNamePrefixer converts a full flag name and its placeholder into the help +// message flag prefix. This is used by the default FlagStringer. +var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames + +// FlagEnvHinter annotates flag help message with the environment variable +// details. This is used by the default FlagStringer. +var FlagEnvHinter FlagEnvHintFunc = withEnvHint + +// FlagFileHinter annotates flag help message with the environment variable +// details. This is used by the default FlagStringer. +var FlagFileHinter FlagFileHintFunc = withFileHint + +// FlagsByName is a slice of Flag. +type FlagsByName []Flag + +func (f FlagsByName) Len() int { + return len(f) +} + +func (f FlagsByName) Less(i, j int) bool { + if len(f[j].Names()) == 0 { + return false + } else if len(f[i].Names()) == 0 { + return true + } + return lexicographicLess(f[i].Names()[0], f[j].Names()[0]) +} + +func (f FlagsByName) Swap(i, j int) { + f[i], f[j] = f[j], f[i] +} + +// ActionableFlag is an interface that wraps Flag interface and RunAction operation. +type ActionableFlag interface { + RunAction(context.Context, *Command) error +} + +// Flag is a common interface related to parsing flags in cli. +// For more advanced flag parsing techniques, it is recommended that +// this interface be implemented. +type Flag interface { + fmt.Stringer + + // Retrieve the value of the Flag + Get() any + + // Lifecycle methods. + // flag callback prior to parsing + PreParse() error + + // flag callback post parsing + PostParse() error + + // Apply Flag settings to the given flag set + Set(string, string) error + + // All possible names for this flag + Names() []string + + // Whether the flag has been set or not + IsSet() bool +} + +// RequiredFlag is an interface that allows us to mark flags as required +// it allows flags required flags to be backwards compatible with the Flag interface +type RequiredFlag interface { + // whether the flag is a required flag or not + IsRequired() bool +} + +// DocGenerationFlag is an interface that allows documentation generation for the flag +type DocGenerationFlag interface { + // TakesValue returns true if the flag takes a value, otherwise false + TakesValue() bool + + // GetUsage returns the usage string for the flag + GetUsage() string + + // GetValue returns the flags value as string representation and an empty + // string if the flag takes no value at all. + GetValue() string + + // GetDefaultText returns the default text for this flag + GetDefaultText() string + + // GetEnvVars returns the env vars for this flag + GetEnvVars() []string + + // IsDefaultVisible returns whether the default value should be shown in + // help text + IsDefaultVisible() bool + // TypeName to detect if a flag is a string, bool, etc. + TypeName() string +} + +// DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based flags. +type DocGenerationMultiValueFlag interface { + DocGenerationFlag + + // IsMultiValueFlag returns true for flags that can be given multiple times. + IsMultiValueFlag() bool +} + +// Countable is an interface to enable detection of flag values which support +// repetitive flags +type Countable interface { + Count() int +} + +// VisibleFlag is an interface that allows to check if a flag is visible +type VisibleFlag interface { + // IsVisible returns true if the flag is not hidden, otherwise false + IsVisible() bool +} + +// CategorizableFlag is an interface that allows us to potentially +// use a flag in a categorized representation. +type CategorizableFlag interface { + // Returns the category of the flag + GetCategory() string + + // Sets the category of the flag + SetCategory(string) +} + +// LocalFlag is an interface to enable detection of flags which are local +// to current command +type LocalFlag interface { + IsLocal() bool +} + +func visibleFlags(fl []Flag) []Flag { + var visible []Flag + for _, f := range fl { + if vf, ok := f.(VisibleFlag); ok && vf.IsVisible() { + visible = append(visible, f) + } + } + return visible +} + +func FlagNames(name string, aliases []string) []string { + var ret []string + + for _, part := range append([]string{name}, aliases...) { + // v1 -> v2 migration warning zone: + // Strip off anything after the first found comma or space, which + // *hopefully* makes it a tiny bit more obvious that unexpected behavior is + // caused by using the v1 form of stringly typed "Name". + ret = append(ret, commaWhitespace.ReplaceAllString(part, "")) + } + + return ret +} + +func hasFlag(flags []Flag, fl Flag) bool { + for _, existing := range flags { + if fl == existing { + return true + } + } + + return false +} + +func flagSplitMultiValues(val string) []string { + if disableSliceFlagSeparator { + return []string{val} + } + + return strings.Split(val, defaultSliceFlagSeparator) +} diff --git a/vendor/github.com/urfave/cli/v3/flag_bool.go b/vendor/github.com/urfave/cli/v3/flag_bool.go new file mode 100644 index 00000000..d5764482 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_bool.go @@ -0,0 +1,81 @@ +package cli + +import ( + "errors" + "strconv" +) + +type BoolFlag = FlagBase[bool, BoolConfig, boolValue] + +// BoolConfig defines the configuration for bool flags +type BoolConfig struct { + Count *int +} + +// boolValue needs to implement the boolFlag internal interface in flag +// to be able to capture bool fields and values +// +// type boolFlag interface { +// Value +// IsBoolFlag() bool +// } +type boolValue struct { + destination *bool + count *int +} + +func (cmd *Command) Bool(name string) bool { + if v, ok := cmd.Value(name).(bool); ok { + tracef("bool available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return false +} + +// Below functions are to satisfy the ValueCreator interface + +// Create creates the bool value +func (b boolValue) Create(val bool, p *bool, c BoolConfig) Value { + *p = val + if c.Count == nil { + c.Count = new(int) + } + return &boolValue{ + destination: p, + count: c.Count, + } +} + +// ToString formats the bool value +func (b boolValue) ToString(value bool) string { + return strconv.FormatBool(value) +} + +// Below functions are to satisfy the flag.Value interface + +func (b *boolValue) Set(s string) error { + v, err := strconv.ParseBool(s) + if err != nil { + err = errors.New("parse error") + return err + } + *b.destination = v + if b.count != nil { + *b.count = *b.count + 1 + } + return err +} + +func (b *boolValue) Get() interface{} { return *b.destination } + +func (b *boolValue) String() string { + return strconv.FormatBool(*b.destination) +} + +func (b *boolValue) IsBoolFlag() bool { return true } + +func (b *boolValue) Count() int { + return *b.count +} diff --git a/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go b/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go new file mode 100644 index 00000000..272dd98f --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_bool_with_inverse.go @@ -0,0 +1,240 @@ +package cli + +import ( + "context" + "fmt" + "slices" + "strings" +) + +var DefaultInverseBoolPrefix = "no-" + +type BoolWithInverseFlag struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value bool `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *bool `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, bool) error `json:"-"` // Action callback to be called when flag is set + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(bool) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + Config BoolConfig `json:"config"` // Additional/Custom configuration associated with this flag type + InversePrefix string `json:"invPrefix"` // The prefix used to indicate a negative value. Default: `env` becomes `no-env` + + // unexported fields for internal use + count int // number of times the flag has been set + hasBeenSet bool // whether the flag has been set from env or file + applied bool // whether the flag has been applied to a flag set already + value Value // value representing this flag's value + pset bool + nset bool +} + +func (bif *BoolWithInverseFlag) IsSet() bool { + return bif.hasBeenSet +} + +func (bif *BoolWithInverseFlag) Get() any { + return bif.value.Get() +} + +func (bif *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error { + if bif.Action != nil { + return bif.Action(ctx, cmd, bif.Get().(bool)) + } + + return nil +} + +func (bif *BoolWithInverseFlag) IsLocal() bool { + return bif.Local +} + +func (bif *BoolWithInverseFlag) inversePrefix() string { + if bif.InversePrefix == "" { + bif.InversePrefix = DefaultInverseBoolPrefix + } + + return bif.InversePrefix +} + +func (bif *BoolWithInverseFlag) PreParse() error { + count := bif.Config.Count + if count == nil { + count = &bif.count + } + dest := bif.Destination + if dest == nil { + dest = new(bool) + } + *dest = bif.Value + bif.value = &boolValue{ + destination: dest, + count: count, + } + + // Validate the given default or values set from external sources as well + if bif.Validator != nil && bif.ValidateDefaults { + if err := bif.Validator(bif.value.Get().(bool)); err != nil { + return err + } + } + bif.applied = true + return nil +} + +func (bif *BoolWithInverseFlag) PostParse() error { + tracef("postparse (flag=%[1]q)", bif.Name) + + if !bif.hasBeenSet { + if val, source, found := bif.Sources.LookupWithSource(); found { + if val == "" { + val = "false" + } + if err := bif.Set(bif.Name, val); err != nil { + return fmt.Errorf( + "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s", + val, bif.Value, source, bif.Name, err, + ) + } + + bif.hasBeenSet = true + } + } + + return nil +} + +func (bif *BoolWithInverseFlag) Set(name, val string) error { + if bif.count > 0 && bif.OnlyOnce { + return fmt.Errorf("cant duplicate this flag") + } + + bif.hasBeenSet = true + + if slices.Contains(append([]string{bif.Name}, bif.Aliases...), name) { + if bif.nset { + return fmt.Errorf("cannot set both flags `--%s` and `--%s`", bif.Name, bif.inversePrefix()+bif.Name) + } + if err := bif.value.Set(val); err != nil { + return err + } + bif.pset = true + } else { + if bif.pset { + return fmt.Errorf("cannot set both flags `--%s` and `--%s`", bif.Name, bif.inversePrefix()+bif.Name) + } + if err := bif.value.Set("false"); err != nil { + return err + } + bif.nset = true + } + + if bif.Validator != nil { + return bif.Validator(bif.value.Get().(bool)) + } + return nil +} + +func (bif *BoolWithInverseFlag) Names() []string { + names := append([]string{bif.Name}, bif.Aliases...) + + for _, name := range names { + names = append(names, bif.inversePrefix()+name) + } + + return names +} + +func (bif *BoolWithInverseFlag) IsRequired() bool { + return bif.Required +} + +func (bif *BoolWithInverseFlag) IsVisible() bool { + return !bif.Hidden +} + +// String implements the standard Stringer interface. +// +// Example for BoolFlag{Name: "env"} +// --[no-]env (default: false) +func (bif *BoolWithInverseFlag) String() string { + out := FlagStringer(bif) + + i := strings.Index(out, "\t") + + prefix := "--" + + // single character flags are prefixed with `-` instead of `--` + if len(bif.Name) == 1 { + prefix = "-" + } + + return fmt.Sprintf("%s[%s]%s%s", prefix, bif.inversePrefix(), bif.Name, out[i:]) +} + +// IsBoolFlag returns whether the flag doesnt need to accept args +func (bif *BoolWithInverseFlag) IsBoolFlag() bool { + return true +} + +// Count returns the number of times this flag has been invoked +func (bif *BoolWithInverseFlag) Count() int { + return bif.count +} + +// GetDefaultText returns the default text for this flag +func (bif *BoolWithInverseFlag) GetDefaultText() string { + if bif.Required { + return bif.DefaultText + } + return boolValue{}.ToString(bif.Value) +} + +// GetCategory returns the category of the flag +func (bif *BoolWithInverseFlag) GetCategory() string { + return bif.Category +} + +func (bif *BoolWithInverseFlag) SetCategory(c string) { + bif.Category = c +} + +// GetUsage returns the usage string for the flag +func (bif *BoolWithInverseFlag) GetUsage() string { + return bif.Usage +} + +// GetEnvVars returns the env vars for this flag +func (bif *BoolWithInverseFlag) GetEnvVars() []string { + return bif.Sources.EnvKeys() +} + +// GetValue returns the flags value as string representation and an empty +// string if the flag takes no value at all. +func (bif *BoolWithInverseFlag) GetValue() string { + return "" +} + +func (bif *BoolWithInverseFlag) TakesValue() bool { + return false +} + +// IsDefaultVisible returns true if the flag is not hidden, otherwise false +func (bif *BoolWithInverseFlag) IsDefaultVisible() bool { + return !bif.HideDefault +} + +// TypeName is used for stringify/docs. For bool its a no-op +func (bif *BoolWithInverseFlag) TypeName() string { + return "bool" +} diff --git a/vendor/github.com/urfave/cli/v3/flag_duration.go b/vendor/github.com/urfave/cli/v3/flag_duration.go new file mode 100644 index 00000000..37b4cb64 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_duration.go @@ -0,0 +1,47 @@ +package cli + +import ( + "fmt" + "time" +) + +type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue] + +// -- time.Duration Value +type durationValue time.Duration + +// Below functions are to satisfy the ValueCreator interface + +func (d durationValue) Create(val time.Duration, p *time.Duration, c NoConfig) Value { + *p = val + return (*durationValue)(p) +} + +func (d durationValue) ToString(val time.Duration) string { + return fmt.Sprintf("%v", val) +} + +// Below functions are to satisfy the flag.Value interface + +func (d *durationValue) Set(s string) error { + v, err := time.ParseDuration(s) + if err != nil { + return err + } + *d = durationValue(v) + return err +} + +func (d *durationValue) Get() any { return time.Duration(*d) } + +func (d *durationValue) String() string { return (*time.Duration)(d).String() } + +func (cmd *Command) Duration(name string) time.Duration { + if v, ok := cmd.Value(name).(time.Duration); ok { + tracef("duration available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("bool NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_ext.go b/vendor/github.com/urfave/cli/v3/flag_ext.go new file mode 100644 index 00000000..9972af7c --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_ext.go @@ -0,0 +1,63 @@ +package cli + +import "flag" + +type extFlag struct { + f *flag.Flag +} + +func (e *extFlag) PreParse() error { + if e.f.DefValue != "" { + return e.Set("", e.f.DefValue) + } + + return nil +} + +func (e *extFlag) PostParse() error { + return nil +} + +func (e *extFlag) Set(_ string, val string) error { + return e.f.Value.Set(val) +} + +func (e *extFlag) Get() any { + return e.f.Value.(flag.Getter).Get() +} + +func (e *extFlag) Names() []string { + return []string{e.f.Name} +} + +func (e *extFlag) IsSet() bool { + return false +} + +func (e *extFlag) String() string { + return FlagStringer(e) +} + +func (e *extFlag) IsVisible() bool { + return true +} + +func (e *extFlag) TakesValue() bool { + return false +} + +func (e *extFlag) GetUsage() string { + return e.f.Usage +} + +func (e *extFlag) GetValue() string { + return e.f.Value.String() +} + +func (e *extFlag) GetDefaultText() string { + return e.f.DefValue +} + +func (e *extFlag) GetEnvVars() []string { + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_float.go b/vendor/github.com/urfave/cli/v3/flag_float.go new file mode 100644 index 00000000..71aa0c27 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_float.go @@ -0,0 +1,75 @@ +package cli + +import ( + "strconv" + "unsafe" +) + +type ( + FloatFlag = FlagBase[float64, NoConfig, floatValue[float64]] + Float32Flag = FlagBase[float32, NoConfig, floatValue[float32]] + Float64Flag = FlagBase[float64, NoConfig, floatValue[float64]] +) + +// -- float Value +type floatValue[T float32 | float64] struct { + val *T +} + +// Below functions are to satisfy the ValueCreator interface + +func (f floatValue[T]) Create(val T, p *T, c NoConfig) Value { + *p = val + + return &floatValue[T]{val: p} +} + +func (f floatValue[T]) ToString(b T) string { + return strconv.FormatFloat(float64(b), 'g', -1, int(unsafe.Sizeof(T(0))*8)) +} + +// Below functions are to satisfy the flag.Value interface + +func (f *floatValue[T]) Set(s string) error { + v, err := strconv.ParseFloat(s, int(unsafe.Sizeof(T(0))*8)) + if err != nil { + return err + } + *f.val = T(v) + return nil +} + +func (f *floatValue[T]) Get() any { return *f.val } + +func (f *floatValue[T]) String() string { + return strconv.FormatFloat(float64(*f.val), 'g', -1, int(unsafe.Sizeof(T(0))*8)) +} + +// Float looks up the value of a local FloatFlag, returns +// 0 if not found +func (cmd *Command) Float(name string) float64 { + return getFloat[float64](cmd, name) +} + +// Float32 looks up the value of a local Float32Flag, returns +// 0 if not found +func (cmd *Command) Float32(name string) float32 { + return getFloat[float32](cmd, name) +} + +// Float64 looks up the value of a local Float64Flag, returns +// 0 if not found +func (cmd *Command) Float64(name string) float64 { + return getFloat[float64](cmd, name) +} + +func getFloat[T float32 | float64](cmd *Command, name string) T { + if v, ok := cmd.Value(name).(T); ok { + tracef("float available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + + return v + } + + tracef("float NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_float_slice.go b/vendor/github.com/urfave/cli/v3/flag_float_slice.go new file mode 100644 index 00000000..9a6a46d8 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_float_slice.go @@ -0,0 +1,34 @@ +package cli + +type ( + FloatSlice = SliceBase[float64, NoConfig, floatValue[float64]] + Float32Slice = SliceBase[float32, NoConfig, floatValue[float32]] + Float64Slice = SliceBase[float64, NoConfig, floatValue[float64]] + FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice] + Float32SliceFlag = FlagBase[[]float32, NoConfig, Float32Slice] + Float64SliceFlag = FlagBase[[]float64, NoConfig, Float64Slice] +) + +var ( + NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue[float64]] + NewFloat32Slice = NewSliceBase[float32, NoConfig, floatValue[float32]] + NewFloat64Slice = NewSliceBase[float64, NoConfig, floatValue[float64]] +) + +// FloatSlice looks up the value of a local FloatSliceFlag, returns +// nil if not found +func (cmd *Command) FloatSlice(name string) []float64 { + return getNumberSlice[float64](cmd, name) +} + +// Float32Slice looks up the value of a local Float32Slice, returns +// nil if not found +func (cmd *Command) Float32Slice(name string) []float32 { + return getNumberSlice[float32](cmd, name) +} + +// Float64Slice looks up the value of a local Float64SliceFlag, returns +// nil if not found +func (cmd *Command) Float64Slice(name string) []float64 { + return getNumberSlice[float64](cmd, name) +} diff --git a/vendor/github.com/urfave/cli/v3/flag_generic.go b/vendor/github.com/urfave/cli/v3/flag_generic.go new file mode 100644 index 00000000..9618409e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_generic.go @@ -0,0 +1,67 @@ +package cli + +type GenericFlag = FlagBase[Value, NoConfig, genericValue] + +// -- Value Value +type genericValue struct { + val Value +} + +// Below functions are to satisfy the ValueCreator interface + +func (f genericValue) Create(val Value, p *Value, c NoConfig) Value { + *p = val + return &genericValue{ + val: *p, + } +} + +func (f genericValue) ToString(b Value) string { + if b != nil { + return b.String() + } + return "" +} + +// Below functions are to satisfy the flag.Value interface + +func (f *genericValue) Set(s string) error { + if f.val != nil { + return f.val.Set(s) + } + return nil +} + +func (f *genericValue) Get() any { + if f.val != nil { + return f.val.Get() + } + return nil +} + +func (f *genericValue) String() string { + if f.val != nil { + return f.val.String() + } + return "" +} + +func (f *genericValue) IsBoolFlag() bool { + if f.val == nil { + return false + } + bf, ok := f.val.(boolFlag) + return ok && bf.IsBoolFlag() +} + +// Generic looks up the value of a local GenericFlag, returns +// nil if not found +func (cmd *Command) Generic(name string) Value { + if v, ok := cmd.Value(name).(Value); ok { + tracef("generic available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("generic NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_impl.go b/vendor/github.com/urfave/cli/v3/flag_impl.go new file mode 100644 index 00000000..2495b6ef --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_impl.go @@ -0,0 +1,297 @@ +package cli + +import ( + "context" + "flag" + "fmt" + "reflect" + "strings" +) + +// Value represents a value as used by cli. +// For now it implements the golang flag.Value interface +type Value interface { + flag.Value + flag.Getter +} + +type boolFlag interface { + IsBoolFlag() bool +} + +// ValueCreator is responsible for creating a flag.Value emulation +// as well as custom formatting +// +// T specifies the type +// C specifies the config for the type +type ValueCreator[T any, C any] interface { + Create(T, *T, C) Value + ToString(T) string +} + +// NoConfig is for flags which dont need a custom configuration +type NoConfig struct{} + +// FlagBase [T,C,VC] is a generic flag base which can be used +// as a boilerplate to implement the most common interfaces +// used by urfave/cli. +// +// T specifies the type +// C specifies the configuration required(if any for that flag type) +// VC specifies the value creator which creates the flag.Value emulation +type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value T `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *T `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set + Config C `json:"config"` // Additional/Custom configuration associated with this flag type + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(T) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + + // unexported fields for internal use + count int // number of times the flag has been set + hasBeenSet bool // whether the flag has been set from env or file + applied bool // whether the flag has been applied to a flag set already + creator VC // value creator for this flag type + value Value // value representing this flag's value +} + +// GetValue returns the flags value as string representation and an empty +// string if the flag takes no value at all. +func (f *FlagBase[T, C, V]) GetValue() string { + if !f.TakesValue() { + return "" + } + return fmt.Sprintf("%v", f.Value) +} + +// TypeName returns the type of the flag. +func (f *FlagBase[T, C, V]) TypeName() string { + ty := reflect.TypeOf(f.Value) + if ty == nil { + return "" + } + // convert the typename to generic type + convertToGenericType := func(name string) string { + prefixMap := map[string]string{ + "float": "float", + "int": "int", + "uint": "uint", + } + for prefix, genericType := range prefixMap { + if strings.HasPrefix(name, prefix) { + return genericType + } + } + return strings.ToLower(name) + } + + switch ty.Kind() { + // if it is a Slice, then return the slice's inner type. Will nested slices be used in the future? + case reflect.Slice: + elemType := ty.Elem() + return convertToGenericType(elemType.Name()) + // if it is a Map, then return the map's key and value types. + case reflect.Map: + keyType := ty.Key() + valueType := ty.Elem() + return fmt.Sprintf("%s=%s", convertToGenericType(keyType.Name()), convertToGenericType(valueType.Name())) + default: + return convertToGenericType(ty.Name()) + } +} + +// PostParse populates the flag given the flag set and environment +func (f *FlagBase[T, C, V]) PostParse() error { + tracef("postparse (flag=%[1]q)", f.Name) + + if !f.hasBeenSet { + if val, source, found := f.Sources.LookupWithSource(); found { + if val != "" || reflect.TypeOf(f.Value).Kind() == reflect.String { + if err := f.Set(f.Name, val); err != nil { + return fmt.Errorf( + "could not parse %[1]q as %[2]T value from %[3]s for flag %[4]s: %[5]s", + val, f.Value, source, f.Name, err, + ) + } + } else if val == "" && reflect.TypeOf(f.Value).Kind() == reflect.Bool { + _ = f.Set(f.Name, "false") + } + + f.hasBeenSet = true + } + } + + return nil +} + +func (f *FlagBase[T, C, V]) PreParse() error { + newVal := f.Value + + if f.Destination == nil { + f.value = f.creator.Create(newVal, new(T), f.Config) + } else { + f.value = f.creator.Create(newVal, f.Destination, f.Config) + } + + // Validate the given default or values set from external sources as well + if f.Validator != nil && f.ValidateDefaults { + if err := f.Validator(f.value.Get().(T)); err != nil { + return err + } + } + f.applied = true + return nil +} + +// Set applies given value from string +func (f *FlagBase[T, C, V]) Set(_ string, val string) error { + tracef("apply (flag=%[1]q)", f.Name) + + // TODO move this phase into a separate flag initialization function + // if flag has been applied previously then it would have already been set + // from env or file. So no need to apply the env set again. However + // lots of units tests prior to persistent flags assumed that the + // flag can be applied to different flag sets multiple times while still + // keeping the env set. + if !f.applied || f.Local { + if err := f.PreParse(); err != nil { + return err + } + f.applied = true + } + + if f.count == 1 && f.OnlyOnce { + return fmt.Errorf("cant duplicate this flag") + } + + f.count++ + if err := f.value.Set(val); err != nil { + return err + } + f.hasBeenSet = true + if f.Validator != nil { + if err := f.Validator(f.value.Get().(T)); err != nil { + return err + } + } + return nil +} + +func (f *FlagBase[T, C, V]) Get() any { + if f.value != nil { + return f.value.Get() + } + return f.Value +} + +// IsDefaultVisible returns true if the flag is not hidden, otherwise false +func (f *FlagBase[T, C, V]) IsDefaultVisible() bool { + return !f.HideDefault +} + +// String returns a readable representation of this value (for usage defaults) +func (f *FlagBase[T, C, V]) String() string { + return FlagStringer(f) +} + +// IsSet returns whether or not the flag has been set through env or file +func (f *FlagBase[T, C, V]) IsSet() bool { + return f.hasBeenSet +} + +// Names returns the names of the flag +func (f *FlagBase[T, C, V]) Names() []string { + return FlagNames(f.Name, f.Aliases) +} + +// IsRequired returns whether or not the flag is required +func (f *FlagBase[T, C, V]) IsRequired() bool { + return f.Required +} + +// IsVisible returns true if the flag is not hidden, otherwise false +func (f *FlagBase[T, C, V]) IsVisible() bool { + return !f.Hidden +} + +// GetCategory returns the category of the flag +func (f *FlagBase[T, C, V]) GetCategory() string { + return f.Category +} + +func (f *FlagBase[T, C, V]) SetCategory(c string) { + f.Category = c +} + +// GetUsage returns the usage string for the flag +func (f *FlagBase[T, C, V]) GetUsage() string { + return f.Usage +} + +// GetEnvVars returns the env vars for this flag +func (f *FlagBase[T, C, V]) GetEnvVars() []string { + return f.Sources.EnvKeys() +} + +// TakesValue returns true if the flag takes a value, otherwise false +func (f *FlagBase[T, C, V]) TakesValue() bool { + var t T + return reflect.TypeOf(t) == nil || reflect.TypeOf(t).Kind() != reflect.Bool +} + +// GetDefaultText returns the default text for this flag +func (f *FlagBase[T, C, V]) GetDefaultText() string { + if f.DefaultText != "" { + return f.DefaultText + } + var v V + return v.ToString(f.Value) +} + +// RunAction executes flag action if set +func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error { + if f.Action != nil { + return f.Action(ctx, cmd, f.value.Get().(T)) + } + + return nil +} + +// IsMultiValueFlag returns true if the value type T can take multiple +// values from cmd line. This is true for slice and map type flags +func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool { + // TBD how to specify + if reflect.TypeOf(f.Value) == nil { + return false + } + kind := reflect.TypeOf(f.Value).Kind() + return kind == reflect.Slice || kind == reflect.Map +} + +// IsLocal returns false if flag needs to be persistent across subcommands +func (f *FlagBase[T, C, VC]) IsLocal() bool { + return f.Local +} + +// IsBoolFlag returns whether the flag doesnt need to accept args +func (f *FlagBase[T, C, VC]) IsBoolFlag() bool { + bf, ok := f.value.(boolFlag) + return ok && bf.IsBoolFlag() +} + +// Count returns the number of times this flag has been invoked +func (f *FlagBase[T, C, VC]) Count() int { + return f.count +} diff --git a/vendor/github.com/urfave/cli/v3/flag_int.go b/vendor/github.com/urfave/cli/v3/flag_int.go new file mode 100644 index 00000000..0e082221 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_int.go @@ -0,0 +1,107 @@ +package cli + +import ( + "strconv" + "unsafe" +) + +type ( + IntFlag = FlagBase[int, IntegerConfig, intValue[int]] + Int8Flag = FlagBase[int8, IntegerConfig, intValue[int8]] + Int16Flag = FlagBase[int16, IntegerConfig, intValue[int16]] + Int32Flag = FlagBase[int32, IntegerConfig, intValue[int32]] + Int64Flag = FlagBase[int64, IntegerConfig, intValue[int64]] +) + +// IntegerConfig is the configuration for all integer type flags +type IntegerConfig struct { + Base int +} + +// -- int Value +type intValue[T int | int8 | int16 | int32 | int64] struct { + val *T + base int +} + +// Below functions are to satisfy the ValueCreator interface + +func (i intValue[T]) Create(val T, p *T, c IntegerConfig) Value { + *p = val + + return &intValue[T]{ + val: p, + base: c.Base, + } +} + +func (i intValue[T]) ToString(b T) string { + if i.base == 0 { + i.base = 10 + } + + return strconv.FormatInt(int64(b), i.base) +} + +// Below functions are to satisfy the flag.Value interface + +func (i *intValue[T]) Set(s string) error { + v, err := strconv.ParseInt(s, i.base, int(unsafe.Sizeof(T(0))*8)) + if err != nil { + return err + } + *i.val = T(v) + return err +} + +func (i *intValue[T]) Get() any { return *i.val } + +func (i *intValue[T]) String() string { + base := i.base + if base == 0 { + base = 10 + } + + return strconv.FormatInt(int64(*i.val), base) +} + +// Int looks up the value of a local Int64Flag, returns +// 0 if not found +func (cmd *Command) Int(name string) int { + return getInt[int](cmd, name) +} + +// Int8 looks up the value of a local Int8Flag, returns +// 0 if not found +func (cmd *Command) Int8(name string) int8 { + return getInt[int8](cmd, name) +} + +// Int16 looks up the value of a local Int16Flag, returns +// 0 if not found +func (cmd *Command) Int16(name string) int16 { + return getInt[int16](cmd, name) +} + +// Int32 looks up the value of a local Int32Flag, returns +// 0 if not found +func (cmd *Command) Int32(name string) int32 { + return getInt[int32](cmd, name) +} + +// Int64 looks up the value of a local Int64Flag, returns +// 0 if not found +func (cmd *Command) Int64(name string) int64 { + return getInt[int64](cmd, name) +} + +func getInt[T int | int8 | int16 | int32 | int64](cmd *Command, name string) T { + if v, ok := cmd.Value(name).(T); ok { + tracef("int available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + + return v + } + + tracef("int NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_int_slice.go b/vendor/github.com/urfave/cli/v3/flag_int_slice.go new file mode 100644 index 00000000..22dcb5a2 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_int_slice.go @@ -0,0 +1,52 @@ +package cli + +type ( + IntSlice = SliceBase[int, IntegerConfig, intValue[int]] + Int8Slice = SliceBase[int8, IntegerConfig, intValue[int8]] + Int16Slice = SliceBase[int16, IntegerConfig, intValue[int16]] + Int32Slice = SliceBase[int32, IntegerConfig, intValue[int32]] + Int64Slice = SliceBase[int64, IntegerConfig, intValue[int64]] + IntSliceFlag = FlagBase[[]int, IntegerConfig, IntSlice] + Int8SliceFlag = FlagBase[[]int8, IntegerConfig, Int8Slice] + Int16SliceFlag = FlagBase[[]int16, IntegerConfig, Int16Slice] + Int32SliceFlag = FlagBase[[]int32, IntegerConfig, Int32Slice] + Int64SliceFlag = FlagBase[[]int64, IntegerConfig, Int64Slice] +) + +var ( + NewIntSlice = NewSliceBase[int, IntegerConfig, intValue[int]] + NewInt8Slice = NewSliceBase[int8, IntegerConfig, intValue[int8]] + NewInt16Slice = NewSliceBase[int16, IntegerConfig, intValue[int16]] + NewInt32Slice = NewSliceBase[int32, IntegerConfig, intValue[int32]] + NewInt64Slice = NewSliceBase[int64, IntegerConfig, intValue[int64]] +) + +// IntSlice looks up the value of a local IntSliceFlag, returns +// nil if not found +func (cmd *Command) IntSlice(name string) []int { + return getNumberSlice[int](cmd, name) +} + +// Int8Slice looks up the value of a local Int8SliceFlag, returns +// nil if not found +func (cmd *Command) Int8Slice(name string) []int8 { + return getNumberSlice[int8](cmd, name) +} + +// Int16Slice looks up the value of a local Int16SliceFlag, returns +// nil if not found +func (cmd *Command) Int16Slice(name string) []int16 { + return getNumberSlice[int16](cmd, name) +} + +// Int32Slice looks up the value of a local Int32SliceFlag, returns +// nil if not found +func (cmd *Command) Int32Slice(name string) []int32 { + return getNumberSlice[int32](cmd, name) +} + +// Int64Slice looks up the value of a local Int64SliceFlag, returns +// nil if not found +func (cmd *Command) Int64Slice(name string) []int64 { + return getNumberSlice[int64](cmd, name) +} diff --git a/vendor/github.com/urfave/cli/v3/flag_map_impl.go b/vendor/github.com/urfave/cli/v3/flag_map_impl.go new file mode 100644 index 00000000..b03514b7 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_map_impl.go @@ -0,0 +1,112 @@ +package cli + +import ( + "encoding/json" + "fmt" + "reflect" + "sort" + "strings" +) + +// MapBase wraps map[string]T to satisfy flag.Value +type MapBase[T any, C any, VC ValueCreator[T, C]] struct { + dict *map[string]T + hasBeenSet bool + value Value +} + +func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value { + *p = map[string]T{} + for k, v := range val { + (*p)[k] = v + } + var t T + np := new(T) + var vc VC + return &MapBase[T, C, VC]{ + dict: p, + value: vc.Create(t, np, c), + } +} + +// NewMapBase makes a *MapBase with default values +func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC] { + return &MapBase[T, C, VC]{ + dict: &defaults, + } +} + +// Set parses the value and appends it to the list of values +func (i *MapBase[T, C, VC]) Set(value string) error { + if !i.hasBeenSet { + *i.dict = map[string]T{} + i.hasBeenSet = true + } + + if strings.HasPrefix(value, slPfx) { + // Deserializing assumes overwrite + _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.dict) + i.hasBeenSet = true + return nil + } + + for _, item := range flagSplitMultiValues(value) { + key, value, ok := strings.Cut(item, defaultMapFlagKeyValueSeparator) + if !ok { + return fmt.Errorf("item %q is missing separator %q", item, defaultMapFlagKeyValueSeparator) + } + if err := i.value.Set(value); err != nil { + return err + } + (*i.dict)[key] = i.value.Get().(T) + } + + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (i *MapBase[T, C, VC]) String() string { + v := i.Value() + var t T + if reflect.TypeOf(t).Kind() == reflect.String { + return fmt.Sprintf("%v", v) + } + return fmt.Sprintf("%T{%s}", v, i.ToString(v)) +} + +// Serialize allows MapBase to fulfill Serializer +func (i *MapBase[T, C, VC]) Serialize() string { + jsonBytes, _ := json.Marshal(i.dict) + return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) +} + +// Value returns the mapping of values set by this flag +func (i *MapBase[T, C, VC]) Value() map[string]T { + if i.dict == nil { + return map[string]T{} + } + return *i.dict +} + +// Get returns the mapping of values set by this flag +func (i *MapBase[T, C, VC]) Get() interface{} { + return *i.dict +} + +func (i MapBase[T, C, VC]) ToString(t map[string]T) string { + var defaultVals []string + var vc VC + for _, k := range sortedKeys(t) { + defaultVals = append(defaultVals, k+defaultMapFlagKeyValueSeparator+vc.ToString(t[k])) + } + return strings.Join(defaultVals, ", ") +} + +func sortedKeys[T any](dict map[string]T) []string { + keys := make([]string, 0, len(dict)) + for k := range dict { + keys = append(keys, k) + } + sort.Strings(keys) + return keys +} diff --git a/vendor/github.com/urfave/cli/v3/flag_mutex.go b/vendor/github.com/urfave/cli/v3/flag_mutex.go new file mode 100644 index 00000000..247bcb56 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_mutex.go @@ -0,0 +1,54 @@ +package cli + +// MutuallyExclusiveFlags defines a mutually exclusive flag group +// Multiple option paths can be provided out of which +// only one can be defined on cmdline +// So for example +// [ --foo | [ --bar something --darth somethingelse ] ] +type MutuallyExclusiveFlags struct { + // Flag list + Flags [][]Flag + + // whether this group is required + Required bool + + // Category to apply to all flags within group + Category string +} + +func (grp MutuallyExclusiveFlags) check(_ *Command) error { + oneSet := false + e := &mutuallyExclusiveGroup{} + + for _, grpf := range grp.Flags { + for _, f := range grpf { + if f.IsSet() { + if oneSet { + e.flag2Name = f.Names()[0] + return e + } + e.flag1Name = f.Names()[0] + oneSet = true + break + } + if oneSet { + break + } + } + } + + if !oneSet && grp.Required { + return &mutuallyExclusiveGroupRequiredFlag{flags: &grp} + } + return nil +} + +func (grp MutuallyExclusiveFlags) propagateCategory() { + for _, grpf := range grp.Flags { + for _, f := range grpf { + if cf, ok := f.(CategorizableFlag); ok { + cf.SetCategory(grp.Category) + } + } + } +} diff --git a/vendor/github.com/urfave/cli/v3/flag_number_slice.go b/vendor/github.com/urfave/cli/v3/flag_number_slice.go new file mode 100644 index 00000000..77e31702 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_number_slice.go @@ -0,0 +1,15 @@ +package cli + +type numberType interface { + int | int8 | int16 | int32 | int64 | float32 | float64 +} + +func getNumberSlice[T numberType](cmd *Command, name string) []T { + if v, ok := cmd.Value(name).([]T); ok { + tracef("%T slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", *new(T), name, v, cmd.Name) + return v + } + + tracef("%T slice NOT available for flag name %[1]q (cmd=%[2]q)", *new(T), name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_slice_base.go b/vendor/github.com/urfave/cli/v3/flag_slice_base.go new file mode 100644 index 00000000..3e7b049e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_slice_base.go @@ -0,0 +1,109 @@ +package cli + +import ( + "encoding/json" + "fmt" + "reflect" + "strings" +) + +// SliceBase wraps []T to satisfy flag.Value +type SliceBase[T any, C any, VC ValueCreator[T, C]] struct { + slice *[]T + hasBeenSet bool + value Value +} + +func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value { + *p = []T{} + *p = append(*p, val...) + var t T + np := new(T) + var vc VC + return &SliceBase[T, C, VC]{ + slice: p, + value: vc.Create(t, np, c), + } +} + +// NewSliceBase makes a *SliceBase with default values +func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC] { + return &SliceBase[T, C, VC]{ + slice: &defaults, + } +} + +// Set parses the value and appends it to the list of values +func (i *SliceBase[T, C, VC]) Set(value string) error { + if !i.hasBeenSet { + *i.slice = []T{} + i.hasBeenSet = true + } + + if strings.HasPrefix(value, slPfx) { + // Deserializing assumes overwrite + _ = json.Unmarshal([]byte(strings.Replace(value, slPfx, "", 1)), &i.slice) + i.hasBeenSet = true + return nil + } + + trimSpace := true + // hack. How do we know if we should trim spaces? + // it makes sense only for string slice flags which have + // an option to not trim spaces. So by default we trim spaces + // otherwise we let the underlying value type handle it. + var t T + if reflect.TypeOf(t).Kind() == reflect.String { + trimSpace = false + } + + for _, s := range flagSplitMultiValues(value) { + if trimSpace { + s = strings.TrimSpace(s) + } + if err := i.value.Set(s); err != nil { + return err + } + *i.slice = append(*i.slice, i.value.Get().(T)) + } + + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (i *SliceBase[T, C, VC]) String() string { + v := i.Value() + var t T + if reflect.TypeOf(t).Kind() == reflect.String { + return fmt.Sprintf("%v", v) + } + return fmt.Sprintf("%T{%s}", v, i.ToString(v)) +} + +// Serialize allows SliceBase to fulfill Serializer +func (i *SliceBase[T, C, VC]) Serialize() string { + jsonBytes, _ := json.Marshal(i.slice) + return fmt.Sprintf("%s%s", slPfx, string(jsonBytes)) +} + +// Value returns the slice of values set by this flag +func (i *SliceBase[T, C, VC]) Value() []T { + if i.slice == nil { + return nil + } + return *i.slice +} + +// Get returns the slice of values set by this flag +func (i *SliceBase[T, C, VC]) Get() interface{} { + return *i.slice +} + +func (i SliceBase[T, C, VC]) ToString(t []T) string { + var defaultVals []string + var v VC + for _, s := range t { + defaultVals = append(defaultVals, v.ToString(s)) + } + return strings.Join(defaultVals, ", ") +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string.go b/vendor/github.com/urfave/cli/v3/flag_string.go new file mode 100644 index 00000000..bdc1ec65 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string.go @@ -0,0 +1,66 @@ +package cli + +import ( + "fmt" + "strings" +) + +type StringFlag = FlagBase[string, StringConfig, stringValue] + +// StringConfig defines the configuration for string flags +type StringConfig struct { + // Whether to trim whitespace of parsed value + TrimSpace bool +} + +// -- string Value +type stringValue struct { + destination *string + trimSpace bool +} + +// Below functions are to satisfy the ValueCreator interface + +func (s stringValue) Create(val string, p *string, c StringConfig) Value { + *p = val + return &stringValue{ + destination: p, + trimSpace: c.TrimSpace, + } +} + +func (s stringValue) ToString(val string) string { + if val == "" { + return val + } + return fmt.Sprintf("%q", val) +} + +// Below functions are to satisfy the flag.Value interface + +func (s *stringValue) Set(val string) error { + if s.trimSpace { + val = strings.TrimSpace(val) + } + *s.destination = val + return nil +} + +func (s *stringValue) Get() any { return *s.destination } + +func (s *stringValue) String() string { + if s.destination != nil { + return *s.destination + } + return "" +} + +func (cmd *Command) String(name string) string { + if v, ok := cmd.Value(name).(string); ok { + tracef("string available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return "" +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string_map.go b/vendor/github.com/urfave/cli/v3/flag_string_map.go new file mode 100644 index 00000000..52fd7362 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string_map.go @@ -0,0 +1,20 @@ +package cli + +type ( + StringMap = MapBase[string, StringConfig, stringValue] + StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap] +) + +var NewStringMap = NewMapBase[string, StringConfig, stringValue] + +// StringMap looks up the value of a local StringMapFlag, returns +// nil if not found +func (cmd *Command) StringMap(name string) map[string]string { + if v, ok := cmd.Value(name).(map[string]string); ok { + tracef("string map available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string map NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_string_slice.go b/vendor/github.com/urfave/cli/v3/flag_string_slice.go new file mode 100644 index 00000000..4cb6c5a0 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_string_slice.go @@ -0,0 +1,20 @@ +package cli + +type ( + StringSlice = SliceBase[string, StringConfig, stringValue] + StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice] +) + +var NewStringSlice = NewSliceBase[string, StringConfig, stringValue] + +// StringSlice looks up the value of a local StringSliceFlag, returns +// nil if not found +func (cmd *Command) StringSlice(name string) []string { + if v, ok := cmd.Value(name).([]string); ok { + tracef("string slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("string slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/flag_timestamp.go b/vendor/github.com/urfave/cli/v3/flag_timestamp.go new file mode 100644 index 00000000..413a2f0e --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_timestamp.go @@ -0,0 +1,142 @@ +package cli + +import ( + "errors" + "fmt" + "time" +) + +type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue] + +// TimestampConfig defines the config for timestamp flags +type TimestampConfig struct { + Timezone *time.Location + // Available layouts for flag value. + // + // Note that value for formats with missing year/date will be interpreted as current year/date respectively. + // + // Read more about time layouts: https://pkg.go.dev/time#pkg-constants + Layouts []string +} + +// timestampValue wrap to satisfy golang's flag interface. +type timestampValue struct { + timestamp *time.Time + hasBeenSet bool + layouts []string + location *time.Location +} + +var _ ValueCreator[time.Time, TimestampConfig] = timestampValue{} + +// Below functions are to satisfy the ValueCreator interface + +func (t timestampValue) Create(val time.Time, p *time.Time, c TimestampConfig) Value { + *p = val + return ×tampValue{ + timestamp: p, + layouts: c.Layouts, + location: c.Timezone, + } +} + +func (t timestampValue) ToString(b time.Time) string { + if b.IsZero() { + return "" + } + return fmt.Sprintf("%v", b) +} + +// Below functions are to satisfy the Value interface + +// Parses the string value to timestamp +func (t *timestampValue) Set(value string) error { + var timestamp time.Time + var err error + + if t.location == nil { + t.location = time.UTC + } + + if len(t.layouts) == 0 { + return errors.New("got nil/empty layouts slice") + } + + for _, layout := range t.layouts { + var locErr error + + timestamp, locErr = time.ParseInLocation(layout, value, t.location) + if locErr != nil { + if err == nil { + err = locErr + continue + } + + err = newMultiError(err, locErr) + continue + } + + err = nil + break + } + + if err != nil { + return err + } + + defaultTS, _ := time.ParseInLocation(time.TimeOnly, time.TimeOnly, timestamp.Location()) + + n := time.Now().In(timestamp.Location()) + + // If format is missing date (or year only), set it explicitly to current + if timestamp.Truncate(time.Hour*24).UnixNano() == defaultTS.Truncate(time.Hour*24).UnixNano() { + timestamp = time.Date( + n.Year(), + n.Month(), + n.Day(), + timestamp.Hour(), + timestamp.Minute(), + timestamp.Second(), + timestamp.Nanosecond(), + timestamp.Location(), + ) + } else if timestamp.Year() == 0 { + timestamp = time.Date( + n.Year(), + timestamp.Month(), + timestamp.Day(), + timestamp.Hour(), + timestamp.Minute(), + timestamp.Second(), + timestamp.Nanosecond(), + timestamp.Location(), + ) + } + + if t.timestamp != nil { + *t.timestamp = timestamp + } + t.hasBeenSet = true + return nil +} + +// String returns a readable representation of this value (for usage defaults) +func (t *timestampValue) String() string { + return fmt.Sprintf("%#v", t.timestamp) +} + +// Get returns the flag structure +func (t *timestampValue) Get() any { + return *t.timestamp +} + +// Timestamp gets the timestamp from a flag name +func (cmd *Command) Timestamp(name string) time.Time { + if v, ok := cmd.Value(name).(time.Time); ok { + tracef("time.Time available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + return v + } + + tracef("time.Time NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return time.Time{} +} diff --git a/vendor/github.com/urfave/cli/v3/flag_uint.go b/vendor/github.com/urfave/cli/v3/flag_uint.go new file mode 100644 index 00000000..64ee2319 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_uint.go @@ -0,0 +1,103 @@ +package cli + +import ( + "strconv" + "unsafe" +) + +type ( + UintFlag = FlagBase[uint, IntegerConfig, uintValue[uint]] + Uint8Flag = FlagBase[uint8, IntegerConfig, uintValue[uint8]] + Uint16Flag = FlagBase[uint16, IntegerConfig, uintValue[uint16]] + Uint32Flag = FlagBase[uint32, IntegerConfig, uintValue[uint32]] + Uint64Flag = FlagBase[uint64, IntegerConfig, uintValue[uint64]] +) + +// -- uint Value +type uintValue[T uint | uint8 | uint16 | uint32 | uint64] struct { + val *T + base int +} + +// Below functions are to satisfy the ValueCreator interface + +func (i uintValue[T]) Create(val T, p *T, c IntegerConfig) Value { + *p = val + + return &uintValue[T]{ + val: p, + base: c.Base, + } +} + +func (i uintValue[T]) ToString(b T) string { + base := i.base + if base == 0 { + base = 10 + } + + return strconv.FormatUint(uint64(b), base) +} + +// Below functions are to satisfy the flag.Value interface + +func (i *uintValue[T]) Set(s string) error { + v, err := strconv.ParseUint(s, i.base, int(unsafe.Sizeof(T(0))*8)) + if err != nil { + return err + } + *i.val = T(v) + return err +} + +func (i *uintValue[T]) Get() any { return *i.val } + +func (i *uintValue[T]) String() string { + base := i.base + if base == 0 { + base = 10 + } + + return strconv.FormatUint(uint64(*i.val), base) +} + +// Uint looks up the value of a local Uint64Flag, returns +// 0 if not found +func (cmd *Command) Uint(name string) uint { + return getUint[uint](cmd, name) +} + +// Uint8 looks up the value of a local Uint8Flag, returns +// 0 if not found +func (cmd *Command) Uint8(name string) uint8 { + return getUint[uint8](cmd, name) +} + +// Uint16 looks up the value of a local Uint16Flag, returns +// 0 if not found +func (cmd *Command) Uint16(name string) uint16 { + return getUint[uint16](cmd, name) +} + +// Uint32 looks up the value of a local Uint32Flag, returns +// 0 if not found +func (cmd *Command) Uint32(name string) uint32 { + return getUint[uint32](cmd, name) +} + +// Uint64 looks up the value of a local Uint64Flag, returns +// 0 if not found +func (cmd *Command) Uint64(name string) uint64 { + return getUint[uint64](cmd, name) +} + +func getUint[T uint | uint8 | uint16 | uint32 | uint64](cmd *Command, name string) T { + if v, ok := cmd.Value(name).(T); ok { + tracef("uint available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + + return v + } + + tracef("uint NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return 0 +} diff --git a/vendor/github.com/urfave/cli/v3/flag_uint_slice.go b/vendor/github.com/urfave/cli/v3/flag_uint_slice.go new file mode 100644 index 00000000..18c5b4d2 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/flag_uint_slice.go @@ -0,0 +1,63 @@ +package cli + +type ( + UintSlice = SliceBase[uint, IntegerConfig, uintValue[uint]] + Uint8Slice = SliceBase[uint8, IntegerConfig, uintValue[uint8]] + Uint16Slice = SliceBase[uint16, IntegerConfig, uintValue[uint16]] + Uint32Slice = SliceBase[uint32, IntegerConfig, uintValue[uint32]] + Uint64Slice = SliceBase[uint64, IntegerConfig, uintValue[uint64]] + UintSliceFlag = FlagBase[[]uint, IntegerConfig, UintSlice] + Uint8SliceFlag = FlagBase[[]uint8, IntegerConfig, Uint8Slice] + Uint16SliceFlag = FlagBase[[]uint16, IntegerConfig, Uint16Slice] + Uint32SliceFlag = FlagBase[[]uint32, IntegerConfig, Uint32Slice] + Uint64SliceFlag = FlagBase[[]uint64, IntegerConfig, Uint64Slice] +) + +var ( + NewUintSlice = NewSliceBase[uint, IntegerConfig, uintValue[uint]] + NewUint8Slice = NewSliceBase[uint8, IntegerConfig, uintValue[uint8]] + NewUint16Slice = NewSliceBase[uint16, IntegerConfig, uintValue[uint16]] + NewUint32Slice = NewSliceBase[uint32, IntegerConfig, uintValue[uint32]] + NewUint64Slice = NewSliceBase[uint64, IntegerConfig, uintValue[uint64]] +) + +// UintSlice looks up the value of a local UintSliceFlag, returns +// nil if not found +func (cmd *Command) UintSlice(name string) []uint { + return getUintSlice[uint](cmd, name) +} + +// Uint8Slice looks up the value of a local Uint8SliceFlag, returns +// nil if not found +func (cmd *Command) Uint8Slice(name string) []uint8 { + return getUintSlice[uint8](cmd, name) +} + +// Uint16Slice looks up the value of a local Uint16SliceFlag, returns +// nil if not found +func (cmd *Command) Uint16Slice(name string) []uint16 { + return getUintSlice[uint16](cmd, name) +} + +// Uint32Slice looks up the value of a local Uint32SliceFlag, returns +// nil if not found +func (cmd *Command) Uint32Slice(name string) []uint32 { + return getUintSlice[uint32](cmd, name) +} + +// Uint64Slice looks up the value of a local Uint64SliceFlag, returns +// nil if not found +func (cmd *Command) Uint64Slice(name string) []uint64 { + return getUintSlice[uint64](cmd, name) +} + +func getUintSlice[T uint | uint8 | uint16 | uint32 | uint64](cmd *Command, name string) []T { + if v, ok := cmd.Value(name).([]T); ok { + tracef("uint slice available for flag name %[1]q with value=%[2]v (cmd=%[3]q)", name, v, cmd.Name) + + return v + } + + tracef("uint slice NOT available for flag name %[1]q (cmd=%[2]q)", name, cmd.Name) + return nil +} diff --git a/vendor/github.com/urfave/cli/v3/funcs.go b/vendor/github.com/urfave/cli/v3/funcs.go new file mode 100644 index 00000000..fe1224c4 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/funcs.go @@ -0,0 +1,53 @@ +package cli + +import "context" + +// ShellCompleteFunc is an action to execute when the shell completion flag is set +type ShellCompleteFunc func(context.Context, *Command) + +// BeforeFunc is an action that executes prior to any subcommands being run once +// the context is ready. If a non-nil error is returned, no subcommands are +// run. +type BeforeFunc func(context.Context, *Command) (context.Context, error) + +// AfterFunc is an action that executes after any subcommands are run and have +// finished. The AfterFunc is run even if Action() panics. +type AfterFunc func(context.Context, *Command) error + +// ActionFunc is the action to execute when no subcommands are specified +type ActionFunc func(context.Context, *Command) error + +// CommandNotFoundFunc is executed if the proper command cannot be found +type CommandNotFoundFunc func(context.Context, *Command, string) + +// ConfigureShellCompletionCommand is a function to configure a shell completion command +type ConfigureShellCompletionCommand func(*Command) + +// OnUsageErrorFunc is executed if a usage error occurs. This is useful for displaying +// customized usage error messages. This function is able to replace the +// original error messages. If this function is not set, the "Incorrect usage" +// is displayed and the execution is interrupted. +type OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) error + +// InvalidFlagAccessFunc is executed when an invalid flag is accessed from the context. +type InvalidFlagAccessFunc func(context.Context, *Command, string) + +// ExitErrHandlerFunc is executed if provided in order to handle exitError values +// returned by Actions and Before/After functions. +type ExitErrHandlerFunc func(context.Context, *Command, error) + +// FlagStringFunc is used by the help generation to display a flag, which is +// expected to be a single line. +type FlagStringFunc func(Flag) string + +// FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix +// text for a flag's full name. +type FlagNamePrefixFunc func(fullName []string, placeholder string) string + +// FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help +// with the environment variable details. +type FlagEnvHintFunc func(envVars []string, str string) string + +// FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help +// with the file path details. +type FlagFileHintFunc func(filePath, str string) string diff --git a/vendor/github.com/urfave/cli/v3/godoc-current.txt b/vendor/github.com/urfave/cli/v3/godoc-current.txt new file mode 100644 index 00000000..bf43768c --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/godoc-current.txt @@ -0,0 +1,1482 @@ +package cli // import "github.com/urfave/cli/v3" + +Package cli provides a minimal framework for creating and organizing command +line Go applications. cli is designed to be easy to understand and write, +the most simple cli application can be written as follows: + + func main() { + (&cli.Command{}).Run(context.Background(), os.Args) + } + +Of course this application does not do much, so let's make this an actual +application: + + func main() { + cmd := &cli.Command{ + Name: "greet", + Usage: "say a greeting", + Action: func(c *cli.Context) error { + fmt.Println("Greetings") + return nil + }, + } + + cmd.Run(context.Background(), os.Args) + } + +VARIABLES + +var ( + NewFloatSlice = NewSliceBase[float64, NoConfig, floatValue[float64]] + NewFloat32Slice = NewSliceBase[float32, NoConfig, floatValue[float32]] + NewFloat64Slice = NewSliceBase[float64, NoConfig, floatValue[float64]] +) +var ( + NewIntSlice = NewSliceBase[int, IntegerConfig, intValue[int]] + NewInt8Slice = NewSliceBase[int8, IntegerConfig, intValue[int8]] + NewInt16Slice = NewSliceBase[int16, IntegerConfig, intValue[int16]] + NewInt32Slice = NewSliceBase[int32, IntegerConfig, intValue[int32]] + NewInt64Slice = NewSliceBase[int64, IntegerConfig, intValue[int64]] +) +var ( + NewUintSlice = NewSliceBase[uint, IntegerConfig, uintValue[uint]] + NewUint8Slice = NewSliceBase[uint8, IntegerConfig, uintValue[uint8]] + NewUint16Slice = NewSliceBase[uint16, IntegerConfig, uintValue[uint16]] + NewUint32Slice = NewSliceBase[uint32, IntegerConfig, uintValue[uint32]] + NewUint64Slice = NewSliceBase[uint64, IntegerConfig, uintValue[uint64]] +) +var ( + SuggestFlag SuggestFlagFunc = suggestFlag + SuggestCommand SuggestCommandFunc = suggestCommand + SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate +) +var AnyArguments = []Argument{ + &StringArgs{ + Max: -1, + }, +} + AnyArguments to differentiate between no arguments(nil) vs aleast one + +var CommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{template "usageTemplate" .}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}} + +GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}} +` + CommandHelpTemplate is the text template for the command help topic. cli.go + uses text/template to render templates. You can render custom help text by + setting this variable. + +var DefaultAppComplete = DefaultRootCommandComplete + DefaultAppComplete is a backward-compatible name for + DefaultRootCommandComplete. + +var DefaultInverseBoolPrefix = "no-" +var ErrWriter io.Writer = os.Stderr + ErrWriter is used to write errors to the user. This can be anything + implementing the io.Writer interface and defaults to os.Stderr. + +var FishCompletionTemplate = `# {{ .Command.Name }} fish shell completion + +function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' + for i in (commandline -opc) + if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} + return 1 + end + end + return 0 +end + +{{ range $v := .Completions }}{{ $v }} +{{ end }}` +var NewStringMap = NewMapBase[string, StringConfig, stringValue] +var NewStringSlice = NewSliceBase[string, StringConfig, stringValue] +var OsExiter = os.Exit + OsExiter is the function used when the app exits. If not set defaults to + os.Exit. + +var RootCommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[global options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} + +VERSION: + {{.Version}}{{end}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}} +{{- if len .Authors}} + +AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} + +COPYRIGHT: + {{template "copyrightTemplate" .}}{{end}} +` + RootCommandHelpTemplate is the text template for the Default help topic. + cli.go uses text/template to render templates. You can render custom help + text by setting this variable. + +var ShowAppHelp = ShowRootCommandHelp + ShowAppHelp is a backward-compatible name for ShowRootCommandHelp. + +var ShowAppHelpAndExit = ShowRootCommandHelpAndExit + ShowAppHelpAndExit is a backward-compatible name for ShowRootCommandHelp. + +var ShowCommandHelp = DefaultShowCommandHelp + ShowCommandHelp prints help for the given command + +var ShowRootCommandHelp = DefaultShowRootCommandHelp + ShowRootCommandHelp is an action that displays help for the root command. + +var ShowSubcommandHelp = DefaultShowSubcommandHelp + ShowSubcommandHelp prints help for the given subcommand + +var SubcommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} +` + SubcommandHelpTemplate is the text template for the subcommand help topic. + cli.go uses text/template to render templates. You can render custom help + text by setting this variable. + +var VersionPrinter = DefaultPrintVersion + VersionPrinter prints the version for the root Command. + + +FUNCTIONS + +func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) +func DefaultPrintHelp(out io.Writer, templ string, data any) + DefaultPrintHelp is the default implementation of HelpPrinter. + +func DefaultPrintHelpCustom(out io.Writer, templ string, data any, customFuncs map[string]any) + DefaultPrintHelpCustom is the default implementation of HelpPrinterCustom. + + The customFuncs map will be combined with a default template.FuncMap to + allow using arbitrary functions in template rendering. + +func DefaultPrintVersion(cmd *Command) + DefaultPrintVersion is the default implementation of VersionPrinter. + +func DefaultRootCommandComplete(ctx context.Context, cmd *Command) + DefaultRootCommandComplete prints the list of subcommands as the default + completion method. + +func DefaultShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error + DefaultShowCommandHelp is the default implementation of ShowCommandHelp. + +func DefaultShowRootCommandHelp(cmd *Command) error + DefaultShowRootCommandHelp is the default implementation of + ShowRootCommandHelp. + +func DefaultShowSubcommandHelp(cmd *Command) error + DefaultShowSubcommandHelp is the default implementation of + ShowSubcommandHelp. + +func FlagNames(name string, aliases []string) []string +func HandleExitCoder(err error) + HandleExitCoder handles errors implementing ExitCoder by printing their + message and calling OsExiter with the given exit code. + + If the given error instead implements MultiError, each error will be checked + for the ExitCoder interface, and OsExiter will be called with the last exit + code found, or exit code 1 if no ExitCoder is found. + + This function is the default error-handling behavior for a Command. + +func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) + ShowCommandHelpAndExit exits with code after showing help via + ShowCommandHelp. + +func ShowRootCommandHelpAndExit(cmd *Command, exitCode int) + ShowRootCommandHelpAndExit prints the list of subcommands and exits with + exit code. + +func ShowSubcommandHelpAndExit(cmd *Command, exitCode int) + ShowSubcommandHelpAndExit prints help for the given subcommand via + ShowSubcommandHelp and exits with exit code. + +func ShowVersion(cmd *Command) + ShowVersion prints the version number of the root Command. + + +TYPES + +type ActionFunc func(context.Context, *Command) error + ActionFunc is the action to execute when no subcommands are specified + +type ActionableFlag interface { + RunAction(context.Context, *Command) error +} + ActionableFlag is an interface that wraps Flag interface and RunAction + operation. + +type AfterFunc func(context.Context, *Command) error + AfterFunc is an action that executes after any subcommands are run and have + finished. The AfterFunc is run even if Action() panics. + +type Args interface { + // Get returns the nth argument, or else a blank string + Get(n int) string + // First returns the first argument, or else a blank string + First() string + // Tail returns the rest of the arguments (not the first one) + // or else an empty string slice + Tail() []string + // Len returns the length of the wrapped slice + Len() int + // Present checks if there are any arguments present + Present() bool + // Slice returns a copy of the internal slice + Slice() []string +} + +type Argument interface { + // which this argument can be accessed using the given name + HasName(string) bool + + // Parse the given args and return unparsed args and/or error + Parse([]string) ([]string, error) + + // The usage template for this argument to use in help + Usage() string + + // The Value of this Arg + Get() any +} + Argument captures a positional argument that can be parsed + +type ArgumentBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *T `json:"-"` // the destination point for this argument + UsageText string `json:"usageText"` // the usage text to show + Config C `json:"config"` // config for this argument similar to Flag Config + + // Has unexported fields. +} + +func (a *ArgumentBase[T, C, VC]) Get() any + +func (a *ArgumentBase[T, C, VC]) HasName(s string) bool + +func (a *ArgumentBase[T, C, VC]) Parse(s []string) ([]string, error) + +func (a *ArgumentBase[T, C, VC]) Usage() string + +type ArgumentsBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // the name of this argument + Value T `json:"value"` // the default value of this argument + Destination *[]T `json:"-"` // the destination point for this argument + UsageText string `json:"usageText"` // the usage text to show + Min int `json:"minTimes"` // the min num of occurrences of this argument + Max int `json:"maxTimes"` // the max num of occurrences of this argument, set to -1 for unlimited + Config C `json:"config"` // config for this argument similar to Flag Config + + // Has unexported fields. +} + ArgumentsBase is a base type for slice arguments + +func (a *ArgumentsBase[T, C, VC]) Get() any + +func (a *ArgumentsBase[T, C, VC]) HasName(s string) bool + +func (a *ArgumentsBase[T, C, VC]) Parse(s []string) ([]string, error) + +func (a *ArgumentsBase[T, C, VC]) Usage() string + +type BeforeFunc func(context.Context, *Command) (context.Context, error) + BeforeFunc is an action that executes prior to any subcommands being run + once the context is ready. If a non-nil error is returned, no subcommands + are run. + +type BoolConfig struct { + Count *int +} + BoolConfig defines the configuration for bool flags + +type BoolFlag = FlagBase[bool, BoolConfig, boolValue] + +type BoolWithInverseFlag struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value bool `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *bool `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, bool) error `json:"-"` // Action callback to be called when flag is set + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(bool) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + Config BoolConfig `json:"config"` // Additional/Custom configuration associated with this flag type + InversePrefix string `json:"invPrefix"` // The prefix used to indicate a negative value. Default: `env` becomes `no-env` + + // Has unexported fields. +} + +func (bif *BoolWithInverseFlag) Count() int + Count returns the number of times this flag has been invoked + +func (bif *BoolWithInverseFlag) Get() any + +func (bif *BoolWithInverseFlag) GetCategory() string + GetCategory returns the category of the flag + +func (bif *BoolWithInverseFlag) GetDefaultText() string + GetDefaultText returns the default text for this flag + +func (bif *BoolWithInverseFlag) GetEnvVars() []string + GetEnvVars returns the env vars for this flag + +func (bif *BoolWithInverseFlag) GetUsage() string + GetUsage returns the usage string for the flag + +func (bif *BoolWithInverseFlag) GetValue() string + GetValue returns the flags value as string representation and an empty + string if the flag takes no value at all. + +func (bif *BoolWithInverseFlag) IsBoolFlag() bool + IsBoolFlag returns whether the flag doesnt need to accept args + +func (bif *BoolWithInverseFlag) IsDefaultVisible() bool + IsDefaultVisible returns true if the flag is not hidden, otherwise false + +func (bif *BoolWithInverseFlag) IsLocal() bool + +func (bif *BoolWithInverseFlag) IsRequired() bool + +func (bif *BoolWithInverseFlag) IsSet() bool + +func (bif *BoolWithInverseFlag) IsVisible() bool + +func (bif *BoolWithInverseFlag) Names() []string + +func (bif *BoolWithInverseFlag) PostParse() error + +func (bif *BoolWithInverseFlag) PreParse() error + +func (bif *BoolWithInverseFlag) RunAction(ctx context.Context, cmd *Command) error + +func (bif *BoolWithInverseFlag) Set(name, val string) error + +func (bif *BoolWithInverseFlag) SetCategory(c string) + +func (bif *BoolWithInverseFlag) String() string + String implements the standard Stringer interface. + + Example for BoolFlag{Name: "env"} --[no-]env (default: false) + +func (bif *BoolWithInverseFlag) TakesValue() bool + +func (bif *BoolWithInverseFlag) TypeName() string + TypeName is used for stringify/docs. For bool its a no-op + +type CategorizableFlag interface { + // Returns the category of the flag + GetCategory() string + + // Sets the category of the flag + SetCategory(string) +} + CategorizableFlag is an interface that allows us to potentially use a flag + in a categorized representation. + +type Command struct { + // The name of the command + Name string `json:"name"` + // A list of aliases for the command + Aliases []string `json:"aliases"` + // A short description of the usage of this command + Usage string `json:"usage"` + // Text to override the USAGE section of help + UsageText string `json:"usageText"` + // A short description of the arguments of this command + ArgsUsage string `json:"argsUsage"` + // Version of the command + Version string `json:"version"` + // Longer explanation of how the command works + Description string `json:"description"` + // DefaultCommand is the (optional) name of a command + // to run if no command names are passed as CLI arguments. + DefaultCommand string `json:"defaultCommand"` + // The category the command is part of + Category string `json:"category"` + // List of child commands + Commands []*Command `json:"commands"` + // List of flags to parse + Flags []Flag `json:"flags"` + // Boolean to hide built-in help command and help flag + HideHelp bool `json:"hideHelp"` + // Ignored if HideHelp is true. + HideHelpCommand bool `json:"hideHelpCommand"` + // Boolean to hide built-in version flag and the VERSION section of help + HideVersion bool `json:"hideVersion"` + // Boolean to enable shell completion commands + EnableShellCompletion bool `json:"-"` + // Shell Completion generation command name + ShellCompletionCommandName string `json:"-"` + // The function to call when checking for shell command completions + ShellComplete ShellCompleteFunc `json:"-"` + // The function to configure a shell completion command + ConfigureShellCompletionCommand ConfigureShellCompletionCommand `json:"-"` + // An action to execute before any subcommands are run, but after the context is ready + // If a non-nil error is returned, no subcommands are run + Before BeforeFunc `json:"-"` + // An action to execute after any subcommands are run, but after the subcommand has finished + // It is run even if Action() panics + After AfterFunc `json:"-"` + // The function to call when this command is invoked + Action ActionFunc `json:"-"` + // Execute this function if the proper command cannot be found + CommandNotFound CommandNotFoundFunc `json:"-"` + // Execute this function if a usage error occurs. + OnUsageError OnUsageErrorFunc `json:"-"` + // Execute this function when an invalid flag is accessed from the context + InvalidFlagAccessHandler InvalidFlagAccessFunc `json:"-"` + // Boolean to hide this command from help or completion + Hidden bool `json:"hidden"` + // List of all authors who contributed (string or fmt.Stringer) + // TODO: ~string | fmt.Stringer when interface unions are available + Authors []any `json:"authors"` + // Copyright of the binary if any + Copyright string `json:"copyright"` + // Reader reader to write input to (useful for tests) + Reader io.Reader `json:"-"` + // Writer writer to write output to + Writer io.Writer `json:"-"` + // ErrWriter writes error output + ErrWriter io.Writer `json:"-"` + // ExitErrHandler processes any error encountered while running a Command before it is + // returned to the caller. If no function is provided, HandleExitCoder is used as the + // default behavior. + ExitErrHandler ExitErrHandlerFunc `json:"-"` + // Other custom info + Metadata map[string]interface{} `json:"metadata"` + // Carries a function which returns app specific info. + ExtraInfo func() map[string]string `json:"-"` + // CustomRootCommandHelpTemplate the text template for app help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomRootCommandHelpTemplate string `json:"-"` + // SliceFlagSeparator is used to customize the separator for SliceFlag, the default is "," + SliceFlagSeparator string `json:"sliceFlagSeparator"` + // DisableSliceFlagSeparator is used to disable SliceFlagSeparator, the default is false + DisableSliceFlagSeparator bool `json:"disableSliceFlagSeparator"` + // Boolean to enable short-option handling so user can combine several + // single-character bool arguments into one + // i.e. foobar -o -v -> foobar -ov + UseShortOptionHandling bool `json:"useShortOptionHandling"` + // Enable suggestions for commands and flags + Suggest bool `json:"suggest"` + // Allows global flags set by libraries which use flag.XXXVar(...) directly + // to be parsed through this library + AllowExtFlags bool `json:"allowExtFlags"` + // Treat all flags as normal arguments if true + SkipFlagParsing bool `json:"skipFlagParsing"` + // CustomHelpTemplate the text template for the command help topic. + // cli.go uses text/template to render templates. You can + // render custom help text by setting this variable. + CustomHelpTemplate string `json:"-"` + // Use longest prefix match for commands + PrefixMatchCommands bool `json:"prefixMatchCommands"` + // Custom suggest command for matching + SuggestCommandFunc SuggestCommandFunc `json:"-"` + // Flag exclusion group + MutuallyExclusiveFlags []MutuallyExclusiveFlags `json:"mutuallyExclusiveFlags"` + // Arguments to parse for this command + Arguments []Argument `json:"arguments"` + // Whether to read arguments from stdin + // applicable to root command only + ReadArgsFromStdin bool `json:"readArgsFromStdin"` + + // Has unexported fields. +} + Command contains everything needed to run an application that accepts a + string slice of arguments such as os.Args. A given Command may contain Flags + and sub-commands in Commands. + +func (cmd *Command) Args() Args + Args returns the command line arguments associated with the command. + +func (cmd *Command) Bool(name string) bool + +func (cmd *Command) Command(name string) *Command + +func (cmd *Command) Count(name string) int + Count returns the num of occurrences of this flag + +func (cmd *Command) Duration(name string) time.Duration + +func (cmd *Command) FlagNames() []string + FlagNames returns a slice of flag names used by the this command and all of + its parent commands. + +func (cmd *Command) Float(name string) float64 + Float looks up the value of a local FloatFlag, returns 0 if not found + +func (cmd *Command) Float32(name string) float32 + Float32 looks up the value of a local Float32Flag, returns 0 if not found + +func (c *Command) Float32Arg(name string) float32 + +func (c *Command) Float32Args(name string) []float32 + +func (cmd *Command) Float32Slice(name string) []float32 + Float32Slice looks up the value of a local Float32Slice, returns nil if not + found + +func (cmd *Command) Float64(name string) float64 + Float64 looks up the value of a local Float64Flag, returns 0 if not found + +func (c *Command) Float64Arg(name string) float64 + +func (c *Command) Float64Args(name string) []float64 + +func (cmd *Command) Float64Slice(name string) []float64 + Float64Slice looks up the value of a local Float64SliceFlag, returns nil if + not found + +func (c *Command) FloatArg(name string) float64 + +func (c *Command) FloatArgs(name string) []float64 + +func (cmd *Command) FloatSlice(name string) []float64 + FloatSlice looks up the value of a local FloatSliceFlag, returns nil if not + found + +func (cmd *Command) FullName() string + FullName returns the full name of the command. For commands with parents + this ensures that the parent commands are part of the command path. + +func (cmd *Command) Generic(name string) Value + Generic looks up the value of a local GenericFlag, returns nil if not found + +func (cmd *Command) HasName(name string) bool + HasName returns true if Command.Name matches given name + +func (cmd *Command) Int(name string) int + Int looks up the value of a local Int64Flag, returns 0 if not found + +func (cmd *Command) Int16(name string) int16 + Int16 looks up the value of a local Int16Flag, returns 0 if not found + +func (c *Command) Int16Arg(name string) int16 + +func (c *Command) Int16Args(name string) []int16 + +func (cmd *Command) Int16Slice(name string) []int16 + Int16Slice looks up the value of a local Int16SliceFlag, returns nil if not + found + +func (cmd *Command) Int32(name string) int32 + Int32 looks up the value of a local Int32Flag, returns 0 if not found + +func (c *Command) Int32Arg(name string) int32 + +func (c *Command) Int32Args(name string) []int32 + +func (cmd *Command) Int32Slice(name string) []int32 + Int32Slice looks up the value of a local Int32SliceFlag, returns nil if not + found + +func (cmd *Command) Int64(name string) int64 + Int64 looks up the value of a local Int64Flag, returns 0 if not found + +func (c *Command) Int64Arg(name string) int64 + +func (c *Command) Int64Args(name string) []int64 + +func (cmd *Command) Int64Slice(name string) []int64 + Int64Slice looks up the value of a local Int64SliceFlag, returns nil if not + found + +func (cmd *Command) Int8(name string) int8 + Int8 looks up the value of a local Int8Flag, returns 0 if not found + +func (c *Command) Int8Arg(name string) int8 + +func (c *Command) Int8Args(name string) []int8 + +func (cmd *Command) Int8Slice(name string) []int8 + Int8Slice looks up the value of a local Int8SliceFlag, returns nil if not + found + +func (c *Command) IntArg(name string) int + +func (c *Command) IntArgs(name string) []int + +func (cmd *Command) IntSlice(name string) []int + IntSlice looks up the value of a local IntSliceFlag, returns nil if not + found + +func (cmd *Command) IsSet(name string) bool + IsSet determines if the flag was actually set + +func (cmd *Command) Lineage() []*Command + Lineage returns *this* command and all of its ancestor commands in order + from child to parent + +func (cmd *Command) LocalFlagNames() []string + LocalFlagNames returns a slice of flag names used in this command. + +func (cmd *Command) NArg() int + NArg returns the number of the command line arguments. + +func (cmd *Command) Names() []string + Names returns the names including short names and aliases. + +func (cmd *Command) NumFlags() int + NumFlags returns the number of flags set + +func (cmd *Command) Root() *Command + Root returns the Command at the root of the graph + +func (cmd *Command) Run(ctx context.Context, osArgs []string) (deferErr error) + Run is the entry point to the command graph. The positional arguments are + parsed according to the Flag and Command definitions and the matching Action + functions are run. + +func (cmd *Command) Set(name, value string) error + Set sets a context flag to a value. + +func (cmd *Command) String(name string) string + +func (c *Command) StringArg(name string) string + +func (c *Command) StringArgs(name string) []string + +func (cmd *Command) StringMap(name string) map[string]string + StringMap looks up the value of a local StringMapFlag, returns nil if not + found + +func (cmd *Command) StringSlice(name string) []string + StringSlice looks up the value of a local StringSliceFlag, returns nil if + not found + +func (cmd *Command) Timestamp(name string) time.Time + Timestamp gets the timestamp from a flag name + +func (c *Command) TimestampArg(name string) time.Time + +func (c *Command) TimestampArgs(name string) []time.Time + +func (cmd *Command) ToFishCompletion() (string, error) + ToFishCompletion creates a fish completion string for the `*Command` The + function errors if either parsing or writing of the string fails. + +func (cmd *Command) Uint(name string) uint + Uint looks up the value of a local Uint64Flag, returns 0 if not found + +func (cmd *Command) Uint16(name string) uint16 + Uint16 looks up the value of a local Uint16Flag, returns 0 if not found + +func (c *Command) Uint16Arg(name string) uint16 + +func (c *Command) Uint16Args(name string) []uint16 + +func (cmd *Command) Uint16Slice(name string) []uint16 + Uint16Slice looks up the value of a local Uint16SliceFlag, returns nil if + not found + +func (cmd *Command) Uint32(name string) uint32 + Uint32 looks up the value of a local Uint32Flag, returns 0 if not found + +func (c *Command) Uint32Arg(name string) uint32 + +func (c *Command) Uint32Args(name string) []uint32 + +func (cmd *Command) Uint32Slice(name string) []uint32 + Uint32Slice looks up the value of a local Uint32SliceFlag, returns nil if + not found + +func (cmd *Command) Uint64(name string) uint64 + Uint64 looks up the value of a local Uint64Flag, returns 0 if not found + +func (c *Command) Uint64Arg(name string) uint64 + +func (c *Command) Uint64Args(name string) []uint64 + +func (cmd *Command) Uint64Slice(name string) []uint64 + Uint64Slice looks up the value of a local Uint64SliceFlag, returns nil if + not found + +func (cmd *Command) Uint8(name string) uint8 + Uint8 looks up the value of a local Uint8Flag, returns 0 if not found + +func (c *Command) Uint8Arg(name string) uint8 + +func (c *Command) Uint8Args(name string) []uint8 + +func (cmd *Command) Uint8Slice(name string) []uint8 + Uint8Slice looks up the value of a local Uint8SliceFlag, returns nil if not + found + +func (c *Command) UintArg(name string) uint + +func (c *Command) UintArgs(name string) []uint + +func (cmd *Command) UintSlice(name string) []uint + UintSlice looks up the value of a local UintSliceFlag, returns nil if not + found + +func (cmd *Command) Value(name string) interface{} + Value returns the value of the flag corresponding to `name` + +func (cmd *Command) VisibleCategories() []CommandCategory + VisibleCategories returns a slice of categories and commands that are + Hidden=false + +func (cmd *Command) VisibleCommands() []*Command + VisibleCommands returns a slice of the Commands with Hidden=false + +func (cmd *Command) VisibleFlagCategories() []VisibleFlagCategory + VisibleFlagCategories returns a slice containing all the visible flag + categories with the flags they contain + +func (cmd *Command) VisibleFlags() []Flag + VisibleFlags returns a slice of the Flags with Hidden=false + +func (cmd *Command) VisiblePersistentFlags() []Flag + VisiblePersistentFlags returns a slice of LocalFlag with Persistent=true and + Hidden=false. + +type CommandCategories interface { + // AddCommand adds a command to a category, creating a new category if necessary. + AddCommand(category string, command *Command) + // Categories returns a slice of categories sorted by name + Categories() []CommandCategory +} + CommandCategories interface allows for category manipulation + +type CommandCategory interface { + // Name returns the category name string + Name() string + // VisibleCommands returns a slice of the Commands with Hidden=false + VisibleCommands() []*Command +} + CommandCategory is a category containing commands. + +type CommandNotFoundFunc func(context.Context, *Command, string) + CommandNotFoundFunc is executed if the proper command cannot be found + +type ConfigureShellCompletionCommand func(*Command) + ConfigureShellCompletionCommand is a function to configure a shell + completion command + +type Countable interface { + Count() int +} + Countable is an interface to enable detection of flag values which support + repetitive flags + +type DocGenerationFlag interface { + // TakesValue returns true if the flag takes a value, otherwise false + TakesValue() bool + + // GetUsage returns the usage string for the flag + GetUsage() string + + // GetValue returns the flags value as string representation and an empty + // string if the flag takes no value at all. + GetValue() string + + // GetDefaultText returns the default text for this flag + GetDefaultText() string + + // GetEnvVars returns the env vars for this flag + GetEnvVars() []string + + // IsDefaultVisible returns whether the default value should be shown in + // help text + IsDefaultVisible() bool + // TypeName to detect if a flag is a string, bool, etc. + TypeName() string +} + DocGenerationFlag is an interface that allows documentation generation for + the flag + +type DocGenerationMultiValueFlag interface { + DocGenerationFlag + + // IsMultiValueFlag returns true for flags that can be given multiple times. + IsMultiValueFlag() bool +} + DocGenerationMultiValueFlag extends DocGenerationFlag for slice/map based + flags. + +type DurationFlag = FlagBase[time.Duration, NoConfig, durationValue] + +type EnvValueSource interface { + IsFromEnv() bool + Key() string +} + EnvValueSource is to specifically detect env sources when printing help text + +type ErrorFormatter interface { + Format(s fmt.State, verb rune) +} + ErrorFormatter is the interface that will suitably format the error output + +type ExitCoder interface { + error + ExitCode() int +} + ExitCoder is the interface checked by `Command` for a custom exit code. + +func Exit(message any, exitCode int) ExitCoder + Exit wraps a message and exit code into an error, which by default is + handled with a call to os.Exit during default error handling. + + This is the simplest way to trigger a non-zero exit code for a Command + without having to call os.Exit manually. During testing, this behavior can + be avoided by overriding the ExitErrHandler function on a Command or the + package-global OsExiter function. + +type ExitErrHandlerFunc func(context.Context, *Command, error) + ExitErrHandlerFunc is executed if provided in order to handle exitError + values returned by Actions and Before/After functions. + +type Flag interface { + fmt.Stringer + + // Retrieve the value of the Flag + Get() any + + // Lifecycle methods. + // flag callback prior to parsing + PreParse() error + + // flag callback post parsing + PostParse() error + + // Apply Flag settings to the given flag set + Set(string, string) error + + // All possible names for this flag + Names() []string + + // Whether the flag has been set or not + IsSet() bool +} + Flag is a common interface related to parsing flags in cli. For more + advanced flag parsing techniques, it is recommended that this interface be + implemented. + +var GenerateShellCompletionFlag Flag = &BoolFlag{ + Name: "generate-shell-completion", + Hidden: true, +} + GenerateShellCompletionFlag enables shell completion + +var HelpFlag Flag = &BoolFlag{ + Name: "help", + Aliases: []string{"h"}, + Usage: "show help", + HideDefault: true, + Local: true, +} + HelpFlag prints the help for all commands and subcommands. Set to nil to + disable the flag. The subcommand will still be added unless HideHelp or + HideHelpCommand is set to true. + +var VersionFlag Flag = &BoolFlag{ + Name: "version", + Aliases: []string{"v"}, + Usage: "print the version", + HideDefault: true, + Local: true, +} + VersionFlag prints the version for the application + +type FlagBase[T any, C any, VC ValueCreator[T, C]] struct { + Name string `json:"name"` // name of the flag + Category string `json:"category"` // category of the flag, if any + DefaultText string `json:"defaultText"` // default text of the flag for usage purposes + HideDefault bool `json:"hideDefault"` // whether to hide the default value in output + Usage string `json:"usage"` // usage string for help output + Sources ValueSourceChain `json:"-"` // sources to load flag value from + Required bool `json:"required"` // whether the flag is required or not + Hidden bool `json:"hidden"` // whether to hide the flag in help output + Local bool `json:"local"` // whether the flag needs to be applied to subcommands as well + Value T `json:"defaultValue"` // default value for this flag if not set by from any source + Destination *T `json:"-"` // destination pointer for value when set + Aliases []string `json:"aliases"` // Aliases that are allowed for this flag + TakesFile bool `json:"takesFileArg"` // whether this flag takes a file argument, mainly for shell completion purposes + Action func(context.Context, *Command, T) error `json:"-"` // Action callback to be called when flag is set + Config C `json:"config"` // Additional/Custom configuration associated with this flag type + OnlyOnce bool `json:"onlyOnce"` // whether this flag can be duplicated on the command line + Validator func(T) error `json:"-"` // custom function to validate this flag value + ValidateDefaults bool `json:"validateDefaults"` // whether to validate defaults or not + + // Has unexported fields. +} + FlagBase [T,C,VC] is a generic flag base which can be used as a boilerplate + to implement the most common interfaces used by urfave/cli. + + T specifies the type + C specifies the configuration required(if any for that flag type) + VC specifies the value creator which creates the flag.Value emulation + +func (f *FlagBase[T, C, VC]) Count() int + Count returns the number of times this flag has been invoked + +func (f *FlagBase[T, C, V]) Get() any + +func (f *FlagBase[T, C, V]) GetCategory() string + GetCategory returns the category of the flag + +func (f *FlagBase[T, C, V]) GetDefaultText() string + GetDefaultText returns the default text for this flag + +func (f *FlagBase[T, C, V]) GetEnvVars() []string + GetEnvVars returns the env vars for this flag + +func (f *FlagBase[T, C, V]) GetUsage() string + GetUsage returns the usage string for the flag + +func (f *FlagBase[T, C, V]) GetValue() string + GetValue returns the flags value as string representation and an empty + string if the flag takes no value at all. + +func (f *FlagBase[T, C, VC]) IsBoolFlag() bool + IsBoolFlag returns whether the flag doesnt need to accept args + +func (f *FlagBase[T, C, V]) IsDefaultVisible() bool + IsDefaultVisible returns true if the flag is not hidden, otherwise false + +func (f *FlagBase[T, C, VC]) IsLocal() bool + IsLocal returns false if flag needs to be persistent across subcommands + +func (f *FlagBase[T, C, VC]) IsMultiValueFlag() bool + IsMultiValueFlag returns true if the value type T can take multiple values + from cmd line. This is true for slice and map type flags + +func (f *FlagBase[T, C, V]) IsRequired() bool + IsRequired returns whether or not the flag is required + +func (f *FlagBase[T, C, V]) IsSet() bool + IsSet returns whether or not the flag has been set through env or file + +func (f *FlagBase[T, C, V]) IsVisible() bool + IsVisible returns true if the flag is not hidden, otherwise false + +func (f *FlagBase[T, C, V]) Names() []string + Names returns the names of the flag + +func (f *FlagBase[T, C, V]) PostParse() error + PostParse populates the flag given the flag set and environment + +func (f *FlagBase[T, C, V]) PreParse() error + +func (f *FlagBase[T, C, V]) RunAction(ctx context.Context, cmd *Command) error + RunAction executes flag action if set + +func (f *FlagBase[T, C, V]) Set(_ string, val string) error + Set applies given value from string + +func (f *FlagBase[T, C, V]) SetCategory(c string) + +func (f *FlagBase[T, C, V]) String() string + String returns a readable representation of this value (for usage defaults) + +func (f *FlagBase[T, C, V]) TakesValue() bool + TakesValue returns true if the flag takes a value, otherwise false + +func (f *FlagBase[T, C, V]) TypeName() string + TypeName returns the type of the flag. + +type FlagCategories interface { + // AddFlags adds a flag to a category, creating a new category if necessary. + AddFlag(category string, fl Flag) + // VisibleCategories returns a slice of visible flag categories sorted by name + VisibleCategories() []VisibleFlagCategory +} + FlagCategories interface allows for category manipulation + +type FlagEnvHintFunc func(envVars []string, str string) string + FlagEnvHintFunc is used by the default FlagStringFunc to annotate flag help + with the environment variable details. + +var FlagEnvHinter FlagEnvHintFunc = withEnvHint + FlagEnvHinter annotates flag help message with the environment variable + details. This is used by the default FlagStringer. + +type FlagFileHintFunc func(filePath, str string) string + FlagFileHintFunc is used by the default FlagStringFunc to annotate flag help + with the file path details. + +var FlagFileHinter FlagFileHintFunc = withFileHint + FlagFileHinter annotates flag help message with the environment variable + details. This is used by the default FlagStringer. + +type FlagNamePrefixFunc func(fullName []string, placeholder string) string + FlagNamePrefixFunc is used by the default FlagStringFunc to create prefix + text for a flag's full name. + +var FlagNamePrefixer FlagNamePrefixFunc = prefixedNames + FlagNamePrefixer converts a full flag name and its placeholder into the help + message flag prefix. This is used by the default FlagStringer. + +type FlagStringFunc func(Flag) string + FlagStringFunc is used by the help generation to display a flag, which is + expected to be a single line. + +var FlagStringer FlagStringFunc = stringifyFlag + FlagStringer converts a flag definition to a string. This is used by help to + display a flag. + +type FlagsByName []Flag + FlagsByName is a slice of Flag. + +func (f FlagsByName) Len() int + +func (f FlagsByName) Less(i, j int) bool + +func (f FlagsByName) Swap(i, j int) + +type Float32Arg = ArgumentBase[float32, NoConfig, floatValue[float32]] + +type Float32Args = ArgumentsBase[float32, NoConfig, floatValue[float32]] + +type Float32Flag = FlagBase[float32, NoConfig, floatValue[float32]] + +type Float32Slice = SliceBase[float32, NoConfig, floatValue[float32]] + +type Float32SliceFlag = FlagBase[[]float32, NoConfig, Float32Slice] + +type Float64Arg = ArgumentBase[float64, NoConfig, floatValue[float64]] + +type Float64Args = ArgumentsBase[float64, NoConfig, floatValue[float64]] + +type Float64Flag = FlagBase[float64, NoConfig, floatValue[float64]] + +type Float64Slice = SliceBase[float64, NoConfig, floatValue[float64]] + +type Float64SliceFlag = FlagBase[[]float64, NoConfig, Float64Slice] + +type FloatArg = ArgumentBase[float64, NoConfig, floatValue[float64]] + +type FloatArgs = ArgumentsBase[float64, NoConfig, floatValue[float64]] + +type FloatFlag = FlagBase[float64, NoConfig, floatValue[float64]] + +type FloatSlice = SliceBase[float64, NoConfig, floatValue[float64]] + +type FloatSliceFlag = FlagBase[[]float64, NoConfig, FloatSlice] + +type GenericFlag = FlagBase[Value, NoConfig, genericValue] + +type HelpPrinterCustomFunc func(w io.Writer, templ string, data any, customFunc map[string]any) + Prints help for the Command with custom template function. + +var HelpPrinterCustom HelpPrinterCustomFunc = DefaultPrintHelpCustom + HelpPrinterCustom is a function that writes the help output. It is used as + the default implementation of HelpPrinter, and may be called directly if the + ExtraInfo field is set on a Command. + + In the default implementation, if the customFuncs argument contains a + "wrapAt" key, which is a function which takes no arguments and returns an + int, this int value will be used to produce a "wrap" function used by the + default template to wrap long lines. + +type HelpPrinterFunc func(w io.Writer, templ string, data any) + HelpPrinterFunc prints help for the Command. + +var HelpPrinter HelpPrinterFunc = DefaultPrintHelp + HelpPrinter is a function that writes the help output. If not set + explicitly, this calls HelpPrinterCustom using only the default template + functions. + + If custom logic for printing help is required, this function can be + overridden. If the ExtraInfo field is defined on a Command, this function + should not be modified, as HelpPrinterCustom will be used directly in order + to capture the extra information. + +type Int16Arg = ArgumentBase[int16, IntegerConfig, intValue[int16]] + +type Int16Args = ArgumentsBase[int16, IntegerConfig, intValue[int16]] + +type Int16Flag = FlagBase[int16, IntegerConfig, intValue[int16]] + +type Int16Slice = SliceBase[int16, IntegerConfig, intValue[int16]] + +type Int16SliceFlag = FlagBase[[]int16, IntegerConfig, Int16Slice] + +type Int32Arg = ArgumentBase[int32, IntegerConfig, intValue[int32]] + +type Int32Args = ArgumentsBase[int32, IntegerConfig, intValue[int32]] + +type Int32Flag = FlagBase[int32, IntegerConfig, intValue[int32]] + +type Int32Slice = SliceBase[int32, IntegerConfig, intValue[int32]] + +type Int32SliceFlag = FlagBase[[]int32, IntegerConfig, Int32Slice] + +type Int64Arg = ArgumentBase[int64, IntegerConfig, intValue[int64]] + +type Int64Args = ArgumentsBase[int64, IntegerConfig, intValue[int64]] + +type Int64Flag = FlagBase[int64, IntegerConfig, intValue[int64]] + +type Int64Slice = SliceBase[int64, IntegerConfig, intValue[int64]] + +type Int64SliceFlag = FlagBase[[]int64, IntegerConfig, Int64Slice] + +type Int8Arg = ArgumentBase[int8, IntegerConfig, intValue[int8]] + +type Int8Args = ArgumentsBase[int8, IntegerConfig, intValue[int8]] + +type Int8Flag = FlagBase[int8, IntegerConfig, intValue[int8]] + +type Int8Slice = SliceBase[int8, IntegerConfig, intValue[int8]] + +type Int8SliceFlag = FlagBase[[]int8, IntegerConfig, Int8Slice] + +type IntArg = ArgumentBase[int, IntegerConfig, intValue[int]] + +type IntArgs = ArgumentsBase[int, IntegerConfig, intValue[int]] + +type IntFlag = FlagBase[int, IntegerConfig, intValue[int]] + +type IntSlice = SliceBase[int, IntegerConfig, intValue[int]] + +type IntSliceFlag = FlagBase[[]int, IntegerConfig, IntSlice] + +type IntegerConfig struct { + Base int +} + IntegerConfig is the configuration for all integer type flags + +type InvalidFlagAccessFunc func(context.Context, *Command, string) + InvalidFlagAccessFunc is executed when an invalid flag is accessed from the + context. + +type LocalFlag interface { + IsLocal() bool +} + LocalFlag is an interface to enable detection of flags which are local to + current command + +type MapBase[T any, C any, VC ValueCreator[T, C]] struct { + // Has unexported fields. +} + MapBase wraps map[string]T to satisfy flag.Value + +func NewMapBase[T any, C any, VC ValueCreator[T, C]](defaults map[string]T) *MapBase[T, C, VC] + NewMapBase makes a *MapBase with default values + +func (i MapBase[T, C, VC]) Create(val map[string]T, p *map[string]T, c C) Value + +func (i *MapBase[T, C, VC]) Get() interface{} + Get returns the mapping of values set by this flag + +func (i *MapBase[T, C, VC]) Serialize() string + Serialize allows MapBase to fulfill Serializer + +func (i *MapBase[T, C, VC]) Set(value string) error + Set parses the value and appends it to the list of values + +func (i *MapBase[T, C, VC]) String() string + String returns a readable representation of this value (for usage defaults) + +func (i MapBase[T, C, VC]) ToString(t map[string]T) string + +func (i *MapBase[T, C, VC]) Value() map[string]T + Value returns the mapping of values set by this flag + +type MapSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source based on key + // and if it was found + // or returns an empty string and false + Lookup(string) (any, bool) +} + MapSource is a source which can be used to look up a value based on a key + typically for use with a cli.Flag + +func NewMapSource(name string, m map[any]any) MapSource + +type MultiError interface { + error + Errors() []error +} + MultiError is an error that wraps multiple errors. + +type MutuallyExclusiveFlags struct { + // Flag list + Flags [][]Flag + + // whether this group is required + Required bool + + // Category to apply to all flags within group + Category string +} + MutuallyExclusiveFlags defines a mutually exclusive flag group Multiple + option paths can be provided out of which only one can be defined on cmdline + So for example [ --foo | [ --bar something --darth somethingelse ] ] + +type NoConfig struct{} + NoConfig is for flags which dont need a custom configuration + +type OnUsageErrorFunc func(ctx context.Context, cmd *Command, err error, isSubcommand bool) error + OnUsageErrorFunc is executed if a usage error occurs. This is useful for + displaying customized usage error messages. This function is able to replace + the original error messages. If this function is not set, the "Incorrect + usage" is displayed and the execution is interrupted. + +type RequiredFlag interface { + // whether the flag is a required flag or not + IsRequired() bool +} + RequiredFlag is an interface that allows us to mark flags as required + it allows flags required flags to be backwards compatible with the Flag + interface + +type Serializer interface { + Serialize() string +} + Serializer is used to circumvent the limitations of flag.FlagSet.Set + +type ShellCompleteFunc func(context.Context, *Command) + ShellCompleteFunc is an action to execute when the shell completion flag is + set + +type SliceBase[T any, C any, VC ValueCreator[T, C]] struct { + // Has unexported fields. +} + SliceBase wraps []T to satisfy flag.Value + +func NewSliceBase[T any, C any, VC ValueCreator[T, C]](defaults ...T) *SliceBase[T, C, VC] + NewSliceBase makes a *SliceBase with default values + +func (i SliceBase[T, C, VC]) Create(val []T, p *[]T, c C) Value + +func (i *SliceBase[T, C, VC]) Get() interface{} + Get returns the slice of values set by this flag + +func (i *SliceBase[T, C, VC]) Serialize() string + Serialize allows SliceBase to fulfill Serializer + +func (i *SliceBase[T, C, VC]) Set(value string) error + Set parses the value and appends it to the list of values + +func (i *SliceBase[T, C, VC]) String() string + String returns a readable representation of this value (for usage defaults) + +func (i SliceBase[T, C, VC]) ToString(t []T) string + +func (i *SliceBase[T, C, VC]) Value() []T + Value returns the slice of values set by this flag + +type StringArg = ArgumentBase[string, StringConfig, stringValue] + +type StringArgs = ArgumentsBase[string, StringConfig, stringValue] + +type StringConfig struct { + // Whether to trim whitespace of parsed value + TrimSpace bool +} + StringConfig defines the configuration for string flags + +type StringFlag = FlagBase[string, StringConfig, stringValue] + +type StringMap = MapBase[string, StringConfig, stringValue] + +type StringMapArgs = ArgumentBase[map[string]string, StringConfig, StringMap] + +type StringMapFlag = FlagBase[map[string]string, StringConfig, StringMap] + +type StringSlice = SliceBase[string, StringConfig, stringValue] + +type StringSliceFlag = FlagBase[[]string, StringConfig, StringSlice] + +type SuggestCommandFunc func(commands []*Command, provided string) string + +type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string + +type TimestampArg = ArgumentBase[time.Time, TimestampConfig, timestampValue] + +type TimestampArgs = ArgumentsBase[time.Time, TimestampConfig, timestampValue] + +type TimestampConfig struct { + Timezone *time.Location + // Available layouts for flag value. + // + // Note that value for formats with missing year/date will be interpreted as current year/date respectively. + // + // Read more about time layouts: https://pkg.go.dev/time#pkg-constants + Layouts []string +} + TimestampConfig defines the config for timestamp flags + +type TimestampFlag = FlagBase[time.Time, TimestampConfig, timestampValue] + +type Uint16Arg = ArgumentBase[uint16, IntegerConfig, uintValue[uint16]] + +type Uint16Args = ArgumentsBase[uint16, IntegerConfig, uintValue[uint16]] + +type Uint16Flag = FlagBase[uint16, IntegerConfig, uintValue[uint16]] + +type Uint16Slice = SliceBase[uint16, IntegerConfig, uintValue[uint16]] + +type Uint16SliceFlag = FlagBase[[]uint16, IntegerConfig, Uint16Slice] + +type Uint32Arg = ArgumentBase[uint32, IntegerConfig, uintValue[uint32]] + +type Uint32Args = ArgumentsBase[uint32, IntegerConfig, uintValue[uint32]] + +type Uint32Flag = FlagBase[uint32, IntegerConfig, uintValue[uint32]] + +type Uint32Slice = SliceBase[uint32, IntegerConfig, uintValue[uint32]] + +type Uint32SliceFlag = FlagBase[[]uint32, IntegerConfig, Uint32Slice] + +type Uint64Arg = ArgumentBase[uint64, IntegerConfig, uintValue[uint64]] + +type Uint64Args = ArgumentsBase[uint64, IntegerConfig, uintValue[uint64]] + +type Uint64Flag = FlagBase[uint64, IntegerConfig, uintValue[uint64]] + +type Uint64Slice = SliceBase[uint64, IntegerConfig, uintValue[uint64]] + +type Uint64SliceFlag = FlagBase[[]uint64, IntegerConfig, Uint64Slice] + +type Uint8Arg = ArgumentBase[uint8, IntegerConfig, uintValue[uint8]] + +type Uint8Args = ArgumentsBase[uint8, IntegerConfig, uintValue[uint8]] + +type Uint8Flag = FlagBase[uint8, IntegerConfig, uintValue[uint8]] + +type Uint8Slice = SliceBase[uint8, IntegerConfig, uintValue[uint8]] + +type Uint8SliceFlag = FlagBase[[]uint8, IntegerConfig, Uint8Slice] + +type UintArg = ArgumentBase[uint, IntegerConfig, uintValue[uint]] + +type UintArgs = ArgumentsBase[uint, IntegerConfig, uintValue[uint]] + +type UintFlag = FlagBase[uint, IntegerConfig, uintValue[uint]] + +type UintSlice = SliceBase[uint, IntegerConfig, uintValue[uint]] + +type UintSliceFlag = FlagBase[[]uint, IntegerConfig, UintSlice] + +type Value interface { + flag.Value + flag.Getter +} + Value represents a value as used by cli. For now it implements the golang + flag.Value interface + +type ValueCreator[T any, C any] interface { + Create(T, *T, C) Value + ToString(T) string +} + ValueCreator is responsible for creating a flag.Value emulation as well as + custom formatting + + T specifies the type + C specifies the config for the type + +type ValueSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source and if it was found + // or returns an empty string and false + Lookup() (string, bool) +} + ValueSource is a source which can be used to look up a value, typically for + use with a cli.Flag + +func EnvVar(key string) ValueSource + +func File(path string) ValueSource + +func NewMapValueSource(key string, ms MapSource) ValueSource + +type ValueSourceChain struct { + Chain []ValueSource +} + ValueSourceChain contains an ordered series of ValueSource that allows for + lookup where the first ValueSource to resolve is returned + +func EnvVars(keys ...string) ValueSourceChain + EnvVars is a helper function to encapsulate a number of envVarValueSource + together as a ValueSourceChain + +func Files(paths ...string) ValueSourceChain + Files is a helper function to encapsulate a number of fileValueSource + together as a ValueSourceChain + +func NewValueSourceChain(src ...ValueSource) ValueSourceChain + +func (vsc *ValueSourceChain) Append(other ValueSourceChain) + +func (vsc *ValueSourceChain) EnvKeys() []string + +func (vsc *ValueSourceChain) GoString() string + +func (vsc *ValueSourceChain) Lookup() (string, bool) + +func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool) + +func (vsc *ValueSourceChain) String() string + +type VisibleFlag interface { + // IsVisible returns true if the flag is not hidden, otherwise false + IsVisible() bool +} + VisibleFlag is an interface that allows to check if a flag is visible + +type VisibleFlagCategory interface { + // Name returns the category name string + Name() string + // Flags returns a slice of VisibleFlag sorted by name + Flags() []Flag +} + VisibleFlagCategory is a category containing flags. + diff --git a/vendor/github.com/urfave/cli/v3/help.go b/vendor/github.com/urfave/cli/v3/help.go new file mode 100644 index 00000000..028fbb5d --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/help.go @@ -0,0 +1,620 @@ +package cli + +import ( + "context" + "fmt" + "io" + "os" + "strings" + "text/tabwriter" + "text/template" + "unicode/utf8" +) + +const ( + helpName = "help" + helpAlias = "h" +) + +// HelpPrinterFunc prints help for the Command. +type HelpPrinterFunc func(w io.Writer, templ string, data any) + +// Prints help for the Command with custom template function. +type HelpPrinterCustomFunc func(w io.Writer, templ string, data any, customFunc map[string]any) + +// HelpPrinter is a function that writes the help output. If not set explicitly, +// this calls HelpPrinterCustom using only the default template functions. +// +// If custom logic for printing help is required, this function can be +// overridden. If the ExtraInfo field is defined on a Command, this function +// should not be modified, as HelpPrinterCustom will be used directly in order +// to capture the extra information. +var HelpPrinter HelpPrinterFunc = DefaultPrintHelp + +// HelpPrinterCustom is a function that writes the help output. It is used as +// the default implementation of HelpPrinter, and may be called directly if +// the ExtraInfo field is set on a Command. +// +// In the default implementation, if the customFuncs argument contains a +// "wrapAt" key, which is a function which takes no arguments and returns +// an int, this int value will be used to produce a "wrap" function used +// by the default template to wrap long lines. +var HelpPrinterCustom HelpPrinterCustomFunc = DefaultPrintHelpCustom + +// VersionPrinter prints the version for the root Command. +var VersionPrinter = DefaultPrintVersion + +// ShowRootCommandHelp is an action that displays help for the root command. +var ShowRootCommandHelp = DefaultShowRootCommandHelp + +// ShowAppHelp is a backward-compatible name for ShowRootCommandHelp. +var ShowAppHelp = ShowRootCommandHelp + +// ShowCommandHelp prints help for the given command +var ShowCommandHelp = DefaultShowCommandHelp + +// ShowSubcommandHelp prints help for the given subcommand +var ShowSubcommandHelp = DefaultShowSubcommandHelp + +func buildHelpCommand(withAction bool) *Command { + cmd := &Command{ + Name: helpName, + Aliases: []string{helpAlias}, + Usage: "Shows a list of commands or help for one command", + ArgsUsage: "[command]", + HideHelp: true, + } + + if withAction { + cmd.Action = helpCommandAction + } + + return cmd +} + +func helpCommandAction(ctx context.Context, cmd *Command) error { + args := cmd.Args() + firstArg := args.First() + + tracef("doing help for cmd %[1]q with args %[2]q", cmd, args) + + // This action can be triggered by a "default" action of a command + // or via cmd.Run when cmd == helpCmd. So we have following possibilities + // + // 1 $ app + // 2 $ app help + // 3 $ app foo + // 4 $ app help foo + // 5 $ app foo help + + // Case 4. when executing a help command set the context to parent + // to allow resolution of subsequent args. This will transform + // $ app help foo + // to + // $ app foo + // which will then be handled as case 3 + if cmd.parent != nil && (cmd.HasName(helpName) || cmd.HasName(helpAlias)) { + tracef("setting cmd to cmd.parent") + cmd = cmd.parent + } + + // Case 4. $ app help foo + // foo is the command for which help needs to be shown + if firstArg != "" { + /* if firstArg == "--" { + return nil + }*/ + tracef("returning ShowCommandHelp with %[1]q", firstArg) + return ShowCommandHelp(ctx, cmd, firstArg) + } + + // Case 1 & 2 + // Special case when running help on main app itself as opposed to individual + // commands/subcommands + if cmd.parent == nil { + tracef("returning ShowRootCommandHelp") + _ = ShowRootCommandHelp(cmd) + return nil + } + + // Case 3, 5 + if (len(cmd.Commands) == 1 && !cmd.HideHelp) || + (len(cmd.Commands) == 0 && cmd.HideHelp) { + + tmpl := cmd.CustomHelpTemplate + if tmpl == "" { + tmpl = CommandHelpTemplate + } + + tracef("running HelpPrinter with command %[1]q", cmd.Name) + HelpPrinter(cmd.Root().Writer, tmpl, cmd) + + return nil + } + + tracef("running ShowSubcommandHelp") + return ShowSubcommandHelp(cmd) +} + +// ShowRootCommandHelpAndExit prints the list of subcommands and exits with exit code. +func ShowRootCommandHelpAndExit(cmd *Command, exitCode int) { + _ = ShowRootCommandHelp(cmd) + OsExiter(exitCode) +} + +// ShowAppHelpAndExit is a backward-compatible name for ShowRootCommandHelp. +var ShowAppHelpAndExit = ShowRootCommandHelpAndExit + +// DefaultShowRootCommandHelp is the default implementation of ShowRootCommandHelp. +func DefaultShowRootCommandHelp(cmd *Command) error { + tmpl := cmd.CustomRootCommandHelpTemplate + if tmpl == "" { + tracef("using RootCommandHelpTemplate") + tmpl = RootCommandHelpTemplate + } + + if cmd.ExtraInfo == nil { + HelpPrinter(cmd.Root().Writer, tmpl, cmd.Root()) + return nil + } + + tracef("setting ExtraInfo in customAppData") + customAppData := func() map[string]any { + return map[string]any{ + "ExtraInfo": cmd.ExtraInfo, + } + } + HelpPrinterCustom(cmd.Root().Writer, tmpl, cmd.Root(), customAppData()) + + return nil +} + +// DefaultRootCommandComplete prints the list of subcommands as the default completion method. +func DefaultRootCommandComplete(ctx context.Context, cmd *Command) { + DefaultCompleteWithFlags(ctx, cmd) +} + +// DefaultAppComplete is a backward-compatible name for DefaultRootCommandComplete. +var DefaultAppComplete = DefaultRootCommandComplete + +func printCommandSuggestions(commands []*Command, writer io.Writer) { + for _, command := range commands { + if command.Hidden { + continue + } + if strings.HasSuffix(os.Getenv("SHELL"), "zsh") { + _, _ = fmt.Fprintf(writer, "%s:%s\n", command.Name, command.Usage) + } else { + _, _ = fmt.Fprintf(writer, "%s\n", command.Name) + } + } +} + +func cliArgContains(flagName string, args []string) bool { + for _, name := range strings.Split(flagName, ",") { + name = strings.TrimSpace(name) + count := utf8.RuneCountInString(name) + if count > 2 { + count = 2 + } + flag := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) + for _, a := range args { + if a == flag { + return true + } + } + } + return false +} + +func printFlagSuggestions(lastArg string, flags []Flag, writer io.Writer) { + // Trim to handle both "-short" and "--long" flags. + cur := strings.TrimLeft(lastArg, "-") + for _, flag := range flags { + if bflag, ok := flag.(*BoolFlag); ok && bflag.Hidden { + continue + } + + usage := "" + if docFlag, ok := flag.(DocGenerationFlag); ok { + usage = docFlag.GetUsage() + } + + name := strings.TrimSpace(flag.Names()[0]) + // this will get total count utf8 letters in flag name + count := utf8.RuneCountInString(name) + if count > 2 { + count = 2 // reuse this count to generate single - or -- in flag completion + } + // if flag name has more than one utf8 letter and last argument in cli has -- prefix then + // skip flag completion for short flags example -v or -x + if strings.HasPrefix(lastArg, "--") && count == 1 { + continue + } + // match if last argument matches this flag and it is not repeated + if strings.HasPrefix(name, cur) && cur != name /* && !cliArgContains(name, os.Args)*/ { + flagCompletion := fmt.Sprintf("%s%s", strings.Repeat("-", count), name) + if usage != "" && strings.HasSuffix(os.Getenv("SHELL"), "zsh") { + flagCompletion = fmt.Sprintf("%s:%s", flagCompletion, usage) + } + fmt.Fprintln(writer, flagCompletion) + } + } +} + +func DefaultCompleteWithFlags(ctx context.Context, cmd *Command) { + args := os.Args + if cmd != nil && cmd.parent != nil { + args = cmd.Args().Slice() + tracef("running default complete with flags[%v] on command %[2]q", args, cmd.Name) + } else { + tracef("running default complete with os.Args flags[%v]", args) + } + argsLen := len(args) + lastArg := "" + // parent command will have --generate-shell-completion so we need + // to account for that + if argsLen > 1 { + lastArg = args[argsLen-2] + } else if argsLen > 0 { + lastArg = args[argsLen-1] + } + + if lastArg == "--" { + tracef("No completions due to termination") + return + } + + if lastArg == completionFlag { + lastArg = "" + } + + if strings.HasPrefix(lastArg, "-") { + tracef("printing flag suggestion for flag[%v] on command %[1]q", lastArg, cmd.Name) + printFlagSuggestions(lastArg, cmd.Flags, cmd.Root().Writer) + return + } + + if cmd != nil { + tracef("printing command suggestions on command %[1]q", cmd.Name) + printCommandSuggestions(cmd.Commands, cmd.Root().Writer) + return + } +} + +// ShowCommandHelpAndExit exits with code after showing help via ShowCommandHelp. +func ShowCommandHelpAndExit(ctx context.Context, cmd *Command, command string, code int) { + _ = ShowCommandHelp(ctx, cmd, command) + OsExiter(code) +} + +// DefaultShowCommandHelp is the default implementation of ShowCommandHelp. +func DefaultShowCommandHelp(ctx context.Context, cmd *Command, commandName string) error { + for _, subCmd := range cmd.Commands { + if !subCmd.HasName(commandName) { + continue + } + + tmpl := subCmd.CustomHelpTemplate + if tmpl == "" { + if len(subCmd.Commands) == 0 { + tracef("using CommandHelpTemplate") + tmpl = CommandHelpTemplate + } else { + tracef("using SubcommandHelpTemplate") + tmpl = SubcommandHelpTemplate + } + } + + tracef("running HelpPrinter") + HelpPrinter(cmd.Root().Writer, tmpl, subCmd) + + tracef("returning nil after printing help") + return nil + } + + tracef("no matching command found") + + if cmd.CommandNotFound == nil { + errMsg := fmt.Sprintf("No help topic for '%v'", commandName) + + if cmd.Suggest { + if suggestion := SuggestCommand(cmd.Commands, commandName); suggestion != "" { + errMsg += ". " + suggestion + } + } + + tracef("exiting 3 with errMsg %[1]q", errMsg) + return Exit(errMsg, 3) + } + + tracef("running CommandNotFound func for %[1]q", commandName) + cmd.CommandNotFound(ctx, cmd, commandName) + + return nil +} + +// ShowSubcommandHelpAndExit prints help for the given subcommand via ShowSubcommandHelp and exits with exit code. +func ShowSubcommandHelpAndExit(cmd *Command, exitCode int) { + _ = ShowSubcommandHelp(cmd) + OsExiter(exitCode) +} + +// DefaultShowSubcommandHelp is the default implementation of ShowSubcommandHelp. +func DefaultShowSubcommandHelp(cmd *Command) error { + HelpPrinter(cmd.Root().Writer, SubcommandHelpTemplate, cmd) + return nil +} + +// ShowVersion prints the version number of the root Command. +func ShowVersion(cmd *Command) { + tracef("showing version via VersionPrinter (cmd=%[1]q)", cmd.Name) + VersionPrinter(cmd) +} + +// DefaultPrintVersion is the default implementation of VersionPrinter. +func DefaultPrintVersion(cmd *Command) { + _, _ = fmt.Fprintf(cmd.Root().Writer, "%v version %v\n", cmd.Name, cmd.Version) +} + +func handleTemplateError(err error) { + if err != nil { + tracef("error encountered during template parse: %[1]v", err) + // If the writer is closed, t.Execute will fail, and there's nothing + // we can do to recover. + if os.Getenv("CLI_TEMPLATE_ERROR_DEBUG") != "" { + _, _ = fmt.Fprintf(ErrWriter, "CLI TEMPLATE ERROR: %#v\n", err) + } + return + } +} + +// DefaultPrintHelpCustom is the default implementation of HelpPrinterCustom. +// +// The customFuncs map will be combined with a default template.FuncMap to +// allow using arbitrary functions in template rendering. +func DefaultPrintHelpCustom(out io.Writer, templ string, data any, customFuncs map[string]any) { + const maxLineLength = 10000 + + tracef("building default funcMap") + funcMap := template.FuncMap{ + "join": strings.Join, + "subtract": subtract, + "indent": indent, + "nindent": nindent, + "trim": strings.TrimSpace, + "wrap": func(input string, offset int) string { return wrap(input, offset, maxLineLength) }, + "offset": offset, + "offsetCommands": offsetCommands, + } + + if wa, ok := customFuncs["wrapAt"]; ok { + if wrapAtFunc, ok := wa.(func() int); ok { + wrapAt := wrapAtFunc() + customFuncs["wrap"] = func(input string, offset int) string { + return wrap(input, offset, wrapAt) + } + } + } + + for key, value := range customFuncs { + funcMap[key] = value + } + + w := tabwriter.NewWriter(out, 1, 8, 2, ' ', 0) + t := template.Must(template.New("help").Funcs(funcMap).Parse(templ)) + + if _, err := t.New("helpNameTemplate").Parse(helpNameTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("argsTemplate").Parse(argsTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("usageTemplate").Parse(usageTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("descriptionTemplate").Parse(descriptionTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleCommandTemplate").Parse(visibleCommandTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("copyrightTemplate").Parse(copyrightTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("versionTemplate").Parse(versionTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleFlagCategoryTemplate").Parse(visibleFlagCategoryTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleFlagTemplate").Parse(visibleFlagTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visiblePersistentFlagTemplate").Parse(visiblePersistentFlagTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleGlobalFlagCategoryTemplate").Parse(strings.ReplaceAll(visibleFlagCategoryTemplate, "OPTIONS", "GLOBAL OPTIONS")); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("authorsTemplate").Parse(authorsTemplate); err != nil { + handleTemplateError(err) + } + + if _, err := t.New("visibleCommandCategoryTemplate").Parse(visibleCommandCategoryTemplate); err != nil { + handleTemplateError(err) + } + + tracef("executing template") + handleTemplateError(t.Execute(w, data)) + + _ = w.Flush() +} + +// DefaultPrintHelp is the default implementation of HelpPrinter. +func DefaultPrintHelp(out io.Writer, templ string, data any) { + HelpPrinterCustom(out, templ, data, nil) +} + +func checkVersion(cmd *Command) bool { + found := false + for _, name := range VersionFlag.Names() { + if cmd.Bool(name) { + found = true + } + } + return found +} + +func checkShellCompleteFlag(c *Command, arguments []string) (bool, []string) { + if (c.parent == nil && !c.EnableShellCompletion) || (c.parent != nil && !c.Root().shellCompletion) { + return false, arguments + } + + pos := len(arguments) - 1 + lastArg := arguments[pos] + + if lastArg != completionFlag { + return false, arguments + } + + for _, arg := range arguments { + // If arguments include "--", shell completion is disabled + // because after "--" only positional arguments are accepted. + // https://unix.stackexchange.com/a/11382 + if arg == "--" { + return false, arguments[:pos] + } + } + + return true, arguments[:pos] +} + +func checkCompletions(ctx context.Context, cmd *Command) bool { + tracef("checking completions on command %[1]q", cmd.Name) + + if !cmd.Root().shellCompletion { + tracef("completion not enabled skipping %[1]q", cmd.Name) + return false + } + + if argsArguments := cmd.Args(); argsArguments.Present() { + name := argsArguments.First() + if cmd := cmd.Command(name); cmd != nil { + // let the command handle the completion + return false + } + } + + tracef("no subcommand found for completion %[1]q", cmd.Name) + + if cmd.ShellComplete != nil { + tracef("running shell completion func for command %[1]q", cmd.Name) + cmd.ShellComplete(ctx, cmd) + } + + return true +} + +func subtract(a, b int) int { + return a - b +} + +func indent(spaces int, v string) string { + pad := strings.Repeat(" ", spaces) + return pad + strings.ReplaceAll(v, "\n", "\n"+pad) +} + +func nindent(spaces int, v string) string { + return "\n" + indent(spaces, v) +} + +func wrap(input string, offset int, wrapAt int) string { + var ss []string + + lines := strings.Split(input, "\n") + + padding := strings.Repeat(" ", offset) + + for i, line := range lines { + if line == "" { + ss = append(ss, line) + } else { + wrapped := wrapLine(line, offset, wrapAt, padding) + if i == 0 { + ss = append(ss, wrapped) + } else { + ss = append(ss, padding+wrapped) + } + + } + } + + return strings.Join(ss, "\n") +} + +func wrapLine(input string, offset int, wrapAt int, padding string) string { + if wrapAt <= offset || len(input) <= wrapAt-offset { + return input + } + + lineWidth := wrapAt - offset + words := strings.Fields(input) + if len(words) == 0 { + return input + } + + wrapped := words[0] + spaceLeft := lineWidth - len(wrapped) + for _, word := range words[1:] { + if len(word)+1 > spaceLeft { + wrapped += "\n" + padding + word + spaceLeft = lineWidth - len(word) + } else { + wrapped += " " + word + spaceLeft -= 1 + len(word) + } + } + + return wrapped +} + +func offset(input string, fixed int) int { + return len(input) + fixed +} + +// this function tries to find the max width of the names column +// so say we have the following rows for help +// +// foo1, foo2, foo3 some string here +// bar1, b2 some other string here +// +// We want to offset the 2nd row usage by some amount so that everything +// is aligned +// +// foo1, foo2, foo3 some string here +// bar1, b2 some other string here +// +// to find that offset we find the length of all the rows and use the max +// to calculate the offset +func offsetCommands(cmds []*Command, fixed int) int { + max := 0 + for _, cmd := range cmds { + s := strings.Join(cmd.Names(), ", ") + if len(s) > max { + max = len(s) + } + } + return max + fixed +} diff --git a/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt b/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt new file mode 100644 index 00000000..365d864c --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/mkdocs-reqs.txt @@ -0,0 +1,5 @@ +mkdocs-git-revision-date-localized-plugin~=1.2 +mkdocs-material~=9.5 +mkdocs~=1.6 +mkdocs-redirects~=1.2 +pygments~=2.18 diff --git a/vendor/github.com/urfave/cli/v3/mkdocs.yml b/vendor/github.com/urfave/cli/v3/mkdocs.yml new file mode 100644 index 00000000..97bc4ad5 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/mkdocs.yml @@ -0,0 +1,139 @@ +# NOTE: the mkdocs dependencies will need to be installed out of +# band until this whole thing gets more automated: +# +# pip install -r mkdocs-reqs.txt +# + +site_name: urfave/cli +site_url: https://cli.urfave.org/ +repo_url: https://github.com/urfave/cli +edit_uri: edit/main/docs/ +nav: + - Home: + - Welcome: index.md + - Contributing: CONTRIBUTING.md + - Code of Conduct: CODE_OF_CONDUCT.md + - Releasing: RELEASING.md + - Security: SECURITY.md + - Migrate v2 to v3: migrate-v2-to-v3.md + - Migrate v1 to v2: migrate-v1-to-v2.md + - v3 Manual: + - Getting Started: v3/getting-started.md + - Migrating From Older Releases: v3/migrating-from-older-releases.md + - Examples: + - Greet: v3/examples/greet.md + - Flags: + - Basics: v3/examples/flags/basics.md + - Value Sources: v3/examples/flags/value-sources.md + - Short Options: v3/examples/flags/short-options.md + - Advanced: v3/examples/flags/advanced.md + - Arguments: + - Basics: v3/examples/arguments/basics.md + - Advanced: v3/examples/arguments/advanced.md + - Subcommands: + - Basics: v3/examples/subcommands/basics.md + - Categories: v3/examples/subcommands/categories.md + - Completions: + - Shell Completions: v3/examples/completions/shell-completions.md + - Customizations: v3/examples/completions/customizations.md + - Help Text: + - Generated Help Text: v3/examples/help/generated-help-text.md + - Suggestions: v3/examples/help/suggestions.md + - Error Handling: + - Exit Codes: v3/examples/exit-codes.md + - Full API Example: v3/examples/full-api-example.md + - v2 Manual: + - Getting Started: v2/getting-started.md + - Migrating to v3: v2/migrating-to-v3.md + - Migrating From Older Releases: v2/migrating-from-older-releases.md + - Examples: + - Greet: v2/examples/greet.md + - Arguments: v2/examples/arguments.md + - Flags: v2/examples/flags.md + - Subcommands: v2/examples/subcommands.md + - Subcommands Categories: v2/examples/subcommands-categories.md + - Exit Codes: v2/examples/exit-codes.md + - Combining Short Options: v2/examples/combining-short-options.md + - Bash Completions: v2/examples/bash-completions.md + - Generated Help Text: v2/examples/generated-help-text.md + - Version Flag: v2/examples/version-flag.md + - Timestamp Flag: v2/examples/timestamp-flag.md + - Suggestions: v2/examples/suggestions.md + - Full API Example: v2/examples/full-api-example.md + - v1 Manual: + - Getting Started: v1/getting-started.md + - Migrating to v2: v1/migrating-to-v2.md + - Examples: + - Greet: v1/examples/greet.md + - Arguments: v1/examples/arguments.md + - Flags: v1/examples/flags.md + - Subcommands: v1/examples/subcommands.md + - Subcommands (Categories): v1/examples/subcommands-categories.md + - Exit Codes: v1/examples/exit-codes.md + - Combining Short Options: v1/examples/combining-short-options.md + - Bash Completions: v1/examples/bash-completions.md + - Generated Help Text: v1/examples/generated-help-text.md + - Version Flag: v1/examples/version-flag.md + +theme: + name: material + palette: + - media: "(prefers-color-scheme: light)" + scheme: default + toggle: + icon: material/brightness-4 + name: dark mode + - media: "(prefers-color-scheme: dark)" + scheme: slate + toggle: + icon: material/brightness-7 + name: light mode + features: + - content.code.annotate + - navigation.top + - navigation.instant + - navigation.expand + - navigation.sections + - navigation.tabs + - navigation.tabs.sticky + +plugins: + - git-revision-date-localized + - search + - redirects: + redirect_maps: + 'v3/examples/bash-completions.md': 'v3/examples/completions/shell-completions.md' + - tags + +# NOTE: this is the recommended configuration from +# https://squidfunk.github.io/mkdocs-material/setup/extensions/#recommended-configuration +markdown_extensions: + - abbr + - admonition + - attr_list + - def_list + - footnotes + - meta + - md_in_html + - toc: + permalink: true + - pymdownx.arithmatex: + generic: true + - pymdownx.betterem: + smart_enable: all + - pymdownx.caret + - pymdownx.details + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + - pymdownx.highlight + - pymdownx.inlinehilite + - pymdownx.keys + - pymdownx.mark + - pymdownx.smartsymbols + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + - pymdownx.tasklist: + custom_checkbox: true + - pymdownx.tilde diff --git a/vendor/github.com/urfave/cli/v3/sort.go b/vendor/github.com/urfave/cli/v3/sort.go new file mode 100644 index 00000000..23d1c2f7 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/sort.go @@ -0,0 +1,29 @@ +package cli + +import "unicode" + +// lexicographicLess compares strings alphabetically considering case. +func lexicographicLess(i, j string) bool { + iRunes := []rune(i) + jRunes := []rune(j) + + lenShared := len(iRunes) + if lenShared > len(jRunes) { + lenShared = len(jRunes) + } + + for index := 0; index < lenShared; index++ { + ir := iRunes[index] + jr := jRunes[index] + + if lir, ljr := unicode.ToLower(ir), unicode.ToLower(jr); lir != ljr { + return lir < ljr + } + + if ir != jr { + return ir < jr + } + } + + return i < j +} diff --git a/vendor/github.com/urfave/cli/v3/staticcheck.conf b/vendor/github.com/urfave/cli/v3/staticcheck.conf new file mode 100644 index 00000000..233d9e73 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/staticcheck.conf @@ -0,0 +1 @@ +checks=["all"] diff --git a/vendor/github.com/urfave/cli/v3/suggestions.go b/vendor/github.com/urfave/cli/v3/suggestions.go new file mode 100644 index 00000000..6f29f122 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/suggestions.go @@ -0,0 +1,147 @@ +package cli + +import ( + "math" +) + +const suggestDidYouMeanTemplate = "Did you mean %q?" + +var ( + SuggestFlag SuggestFlagFunc = suggestFlag + SuggestCommand SuggestCommandFunc = suggestCommand + SuggestDidYouMeanTemplate string = suggestDidYouMeanTemplate +) + +type SuggestFlagFunc func(flags []Flag, provided string, hideHelp bool) string + +type SuggestCommandFunc func(commands []*Command, provided string) string + +// jaroDistance is the measure of similarity between two strings. It returns a +// value between 0 and 1, where 1 indicates identical strings and 0 indicates +// completely different strings. +// +// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro.go. +func jaroDistance(a, b string) float64 { + if len(a) == 0 && len(b) == 0 { + return 1 + } + if len(a) == 0 || len(b) == 0 { + return 0 + } + + lenA := float64(len(a)) + lenB := float64(len(b)) + hashA := make([]bool, len(a)) + hashB := make([]bool, len(b)) + maxDistance := int(math.Max(0, math.Floor(math.Max(lenA, lenB)/2.0)-1)) + + var matches float64 + for i := 0; i < len(a); i++ { + start := int(math.Max(0, float64(i-maxDistance))) + end := int(math.Min(lenB-1, float64(i+maxDistance))) + + for j := start; j <= end; j++ { + if hashB[j] { + continue + } + if a[i] == b[j] { + hashA[i] = true + hashB[j] = true + matches++ + break + } + } + } + if matches == 0 { + return 0 + } + + var transpositions float64 + var j int + for i := 0; i < len(a); i++ { + if !hashA[i] { + continue + } + for !hashB[j] { + j++ + } + if a[i] != b[j] { + transpositions++ + } + j++ + } + + transpositions /= 2 + return ((matches / lenA) + (matches / lenB) + ((matches - transpositions) / matches)) / 3.0 +} + +// jaroWinkler is more accurate when strings have a common prefix up to a +// defined maximum length. +// +// Adapted from https://github.com/xrash/smetrics/blob/5f08fbb34913bc8ab95bb4f2a89a0637ca922666/jaro-winkler.go. +func jaroWinkler(a, b string) float64 { + const ( + boostThreshold = 0.7 + prefixSize = 4 + ) + jaroDist := jaroDistance(a, b) + if jaroDist <= boostThreshold { + return jaroDist + } + + prefix := int(math.Min(float64(len(a)), math.Min(float64(prefixSize), float64(len(b))))) + + var prefixMatch float64 + for i := 0; i < prefix; i++ { + if a[i] == b[i] { + prefixMatch++ + } else { + break + } + } + return jaroDist + 0.1*prefixMatch*(1.0-jaroDist) +} + +func suggestFlag(flags []Flag, provided string, hideHelp bool) string { + distance := 0.0 + suggestion := "" + + for _, flag := range flags { + flagNames := flag.Names() + if !hideHelp && HelpFlag != nil { + flagNames = append(flagNames, HelpFlag.Names()...) + } + for _, name := range flagNames { + newDistance := jaroWinkler(name, provided) + if newDistance > distance { + distance = newDistance + suggestion = name + } + } + } + + if len(suggestion) == 1 { + suggestion = "-" + suggestion + } else if len(suggestion) > 1 { + suggestion = "--" + suggestion + } + + return suggestion +} + +// suggestCommand takes a list of commands and a provided string to suggest a +// command name +func suggestCommand(commands []*Command, provided string) (suggestion string) { + distance := 0.0 + for _, command := range commands { + for _, name := range append(command.Names(), helpName, helpAlias) { + newDistance := jaroWinkler(name, provided) + if newDistance > distance { + distance = newDistance + suggestion = name + } + } + } + + return suggestion +} diff --git a/vendor/github.com/urfave/cli/v3/template.go b/vendor/github.com/urfave/cli/v3/template.go new file mode 100644 index 00000000..29c8e8c7 --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/template.go @@ -0,0 +1,125 @@ +package cli + +var ( + helpNameTemplate = `{{$v := offset .FullName 6}}{{wrap .FullName 3}}{{if .Usage}} - {{wrap .Usage $v}}{{end}}` + argsTemplate = `{{if .Arguments}}{{range .Arguments}}{{.Usage}}{{end}}{{end}}` + usageTemplate = `{{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleFlags}} [options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} {{template "argsTemplate" .}}{{end}}{{end}}{{end}}` + descriptionTemplate = `{{wrap .Description 3}}` + authorsTemplate = `{{with $length := len .Authors}}{{if ne 1 $length}}S{{end}}{{end}}: + {{range $index, $author := .Authors}}{{if $index}} + {{end}}{{$author}}{{end}}` +) + +var visibleCommandTemplate = `{{ $cv := offsetCommands .VisibleCommands 5}}{{range .VisibleCommands}} + {{$s := join .Names ", "}}{{$s}}{{ $sp := subtract $cv (offset $s 3) }}{{ indent $sp ""}}{{wrap .Usage $cv}}{{end}}` + +var visibleCommandCategoryTemplate = `{{range .VisibleCategories}}{{if .Name}} + + {{.Name}}:{{range .VisibleCommands}} + {{join .Names ", "}}{{"\t"}}{{.Usage}}{{end}}{{else}}{{template "visibleCommandTemplate" .}}{{end}}{{end}}` + +var visibleFlagCategoryTemplate = `{{range .VisibleFlagCategories}} + {{if .Name}}{{.Name}} + + {{end}}{{$flglen := len .Flags}}{{range $i, $e := .Flags}}{{if eq (subtract $flglen $i) 1}}{{$e}} +{{else}}{{$e}} + {{end}}{{end}}{{end}}` + +var visibleFlagTemplate = `{{range $i, $e := .VisibleFlags}} + {{wrap $e.String 6}}{{end}}` + +var visiblePersistentFlagTemplate = `{{range $i, $e := .VisiblePersistentFlags}} + {{wrap $e.String 6}}{{end}}` + +var versionTemplate = `{{if .Version}}{{if not .HideVersion}} + +VERSION: + {{.Version}}{{end}}{{end}}` + +var copyrightTemplate = `{{wrap .Copyright 3}}` + +// RootCommandHelpTemplate is the text template for the Default help topic. +// cli.go uses text/template to render templates. You can +// render custom help text by setting this variable. +var RootCommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}} {{if .VisibleFlags}}[global options]{{end}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Version}}{{if not .HideVersion}} + +VERSION: + {{.Version}}{{end}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}} +{{- if len .Authors}} + +AUTHOR{{template "authorsTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandCategoryTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +GLOBAL OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +GLOBAL OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .Copyright}} + +COPYRIGHT: + {{template "copyrightTemplate" .}}{{end}} +` + +// CommandHelpTemplate is the text template for the command help topic. +// cli.go uses text/template to render templates. You can +// render custom help text by setting this variable. +var CommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{template "usageTemplate" .}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}}{{if .VisiblePersistentFlags}} + +GLOBAL OPTIONS:{{template "visiblePersistentFlagTemplate" .}}{{end}} +` + +// SubcommandHelpTemplate is the text template for the subcommand help topic. +// cli.go uses text/template to render templates. You can +// render custom help text by setting this variable. +var SubcommandHelpTemplate = `NAME: + {{template "helpNameTemplate" .}} + +USAGE: + {{if .UsageText}}{{wrap .UsageText 3}}{{else}}{{.FullName}}{{if .VisibleCommands}} [command [command options]]{{end}}{{if .ArgsUsage}} {{.ArgsUsage}}{{else}}{{if .Arguments}} [arguments...]{{end}}{{end}}{{end}}{{if .Category}} + +CATEGORY: + {{.Category}}{{end}}{{if .Description}} + +DESCRIPTION: + {{template "descriptionTemplate" .}}{{end}}{{if .VisibleCommands}} + +COMMANDS:{{template "visibleCommandTemplate" .}}{{end}}{{if .VisibleFlagCategories}} + +OPTIONS:{{template "visibleFlagCategoryTemplate" .}}{{else if .VisibleFlags}} + +OPTIONS:{{template "visibleFlagTemplate" .}}{{end}} +` + +var FishCompletionTemplate = `# {{ .Command.Name }} fish shell completion + +function __fish_{{ .Command.Name }}_no_subcommand --description 'Test if there has been any subcommand yet' + for i in (commandline -opc) + if contains -- $i{{ range $v := .AllCommands }} {{ $v }}{{ end }} + return 1 + end + end + return 0 +end + +{{ range $v := .Completions }}{{ $v }} +{{ end }}` diff --git a/vendor/github.com/urfave/cli/v3/value_source.go b/vendor/github.com/urfave/cli/v3/value_source.go new file mode 100644 index 00000000..44b0173b --- /dev/null +++ b/vendor/github.com/urfave/cli/v3/value_source.go @@ -0,0 +1,257 @@ +package cli + +import ( + "fmt" + "os" + "strings" +) + +// ValueSource is a source which can be used to look up a value, +// typically for use with a cli.Flag +type ValueSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source and if it was found + // or returns an empty string and false + Lookup() (string, bool) +} + +// EnvValueSource is to specifically detect env sources when +// printing help text +type EnvValueSource interface { + IsFromEnv() bool + Key() string +} + +// MapSource is a source which can be used to look up a value +// based on a key +// typically for use with a cli.Flag +type MapSource interface { + fmt.Stringer + fmt.GoStringer + + // Lookup returns the value from the source based on key + // and if it was found + // or returns an empty string and false + Lookup(string) (any, bool) +} + +// ValueSourceChain contains an ordered series of ValueSource that +// allows for lookup where the first ValueSource to resolve is +// returned +type ValueSourceChain struct { + Chain []ValueSource +} + +func NewValueSourceChain(src ...ValueSource) ValueSourceChain { + return ValueSourceChain{ + Chain: src, + } +} + +func (vsc *ValueSourceChain) Append(other ValueSourceChain) { + vsc.Chain = append(vsc.Chain, other.Chain...) +} + +func (vsc *ValueSourceChain) EnvKeys() []string { + vals := []string{} + + for _, src := range vsc.Chain { + if v, ok := src.(EnvValueSource); ok && v.IsFromEnv() { + vals = append(vals, v.Key()) + } + } + + return vals +} + +func (vsc *ValueSourceChain) String() string { + s := []string{} + + for _, vs := range vsc.Chain { + s = append(s, vs.String()) + } + + return strings.Join(s, ",") +} + +func (vsc *ValueSourceChain) GoString() string { + s := []string{} + + for _, vs := range vsc.Chain { + s = append(s, vs.GoString()) + } + + return fmt.Sprintf("&ValueSourceChain{Chain:{%[1]s}}", strings.Join(s, ",")) +} + +func (vsc *ValueSourceChain) Lookup() (string, bool) { + s, _, ok := vsc.LookupWithSource() + return s, ok +} + +func (vsc *ValueSourceChain) LookupWithSource() (string, ValueSource, bool) { + for _, src := range vsc.Chain { + if value, found := src.Lookup(); found { + return value, src, true + } + } + + return "", nil, false +} + +// envVarValueSource encapsulates a ValueSource from an environment variable +type envVarValueSource struct { + key string +} + +func (e *envVarValueSource) Lookup() (string, bool) { + return os.LookupEnv(strings.TrimSpace(string(e.key))) +} + +func (e *envVarValueSource) IsFromEnv() bool { + return true +} + +func (e *envVarValueSource) Key() string { + return e.key +} + +func (e *envVarValueSource) String() string { return fmt.Sprintf("environment variable %[1]q", e.key) } +func (e *envVarValueSource) GoString() string { + return fmt.Sprintf("&envVarValueSource{Key:%[1]q}", e.key) +} + +func EnvVar(key string) ValueSource { + return &envVarValueSource{ + key: key, + } +} + +// EnvVars is a helper function to encapsulate a number of +// envVarValueSource together as a ValueSourceChain +func EnvVars(keys ...string) ValueSourceChain { + vsc := ValueSourceChain{Chain: []ValueSource{}} + + for _, key := range keys { + vsc.Chain = append(vsc.Chain, EnvVar(key)) + } + + return vsc +} + +// fileValueSource encapsulates a ValueSource from a file +type fileValueSource struct { + Path string +} + +func (f *fileValueSource) Lookup() (string, bool) { + data, err := os.ReadFile(f.Path) + return string(data), err == nil +} + +func (f *fileValueSource) String() string { return fmt.Sprintf("file %[1]q", f.Path) } +func (f *fileValueSource) GoString() string { + return fmt.Sprintf("&fileValueSource{Path:%[1]q}", f.Path) +} + +func File(path string) ValueSource { + return &fileValueSource{Path: path} +} + +// Files is a helper function to encapsulate a number of +// fileValueSource together as a ValueSourceChain +func Files(paths ...string) ValueSourceChain { + vsc := ValueSourceChain{Chain: []ValueSource{}} + + for _, path := range paths { + vsc.Chain = append(vsc.Chain, File(path)) + } + + return vsc +} + +type mapSource struct { + name string + m map[any]any +} + +func NewMapSource(name string, m map[any]any) MapSource { + return &mapSource{ + name: name, + m: m, + } +} + +func (ms *mapSource) String() string { return fmt.Sprintf("map source %[1]q", ms.name) } +func (ms *mapSource) GoString() string { + return fmt.Sprintf("&mapSource{name:%[1]q}", ms.name) +} + +// Lookup returns a value from the map source. The lookup name may be a dot-separated path into the map. +// If that is the case, it will recursively traverse the map based on the '.' delimited sections to find +// a nested value for the key. +func (ms *mapSource) Lookup(name string) (any, bool) { + sections := strings.Split(name, ".") + if name == "" || len(sections) == 0 { + return nil, false + } + + node := ms.m + + // traverse into the map based on the dot-separated sections + if len(sections) >= 2 { // the last section is the value we want, we will return it directly at the end + for _, section := range sections[:len(sections)-1] { + child, ok := node[section] + if !ok { + return nil, false + } + + switch child := child.(type) { + case map[string]any: + node = make(map[any]any, len(child)) + for k, v := range child { + node[k] = v + } + case map[any]any: + node = child + default: + return nil, false + } + } + } + + if val, ok := node[sections[len(sections)-1]]; ok { + return val, true + } + return nil, false +} + +type mapValueSource struct { + key string + ms MapSource +} + +func NewMapValueSource(key string, ms MapSource) ValueSource { + return &mapValueSource{ + key: key, + ms: ms, + } +} + +func (mvs *mapValueSource) String() string { + return fmt.Sprintf("key %[1]q from %[2]s", mvs.key, mvs.ms.String()) +} + +func (mvs *mapValueSource) GoString() string { + return fmt.Sprintf("&mapValueSource{key:%[1]q, src:%[2]s}", mvs.key, mvs.ms.GoString()) +} + +func (mvs *mapValueSource) Lookup() (string, bool) { + if v, ok := mvs.ms.Lookup(mvs.key); !ok { + return "", false + } else { + return fmt.Sprintf("%+v", v), true + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 22fe6365..d87790b9 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -1,6 +1,39 @@ # github.com/Masterminds/semver/v3 v3.4.0 ## explicit; go 1.21 github.com/Masterminds/semver/v3 +# github.com/NVIDIA/go-nvlib v0.7.2 +## explicit; go 1.20 +github.com/NVIDIA/go-nvlib/pkg/nvlib/device +github.com/NVIDIA/go-nvlib/pkg/nvlib/info +# github.com/NVIDIA/go-nvml v0.13.0-1 +## explicit; go 1.20 +github.com/NVIDIA/go-nvml/pkg/dl +github.com/NVIDIA/go-nvml/pkg/nvml +github.com/NVIDIA/go-nvml/pkg/nvml/mock +github.com/NVIDIA/go-nvml/pkg/nvml/mock/dgxa100 +# github.com/NVIDIA/nvidia-container-toolkit v1.17.8 +## explicit; go 1.22 +github.com/NVIDIA/nvidia-container-toolkit/internal/config/image +github.com/NVIDIA/nvidia-container-toolkit/internal/discover +github.com/NVIDIA/nvidia-container-toolkit/internal/dxcore +github.com/NVIDIA/nvidia-container-toolkit/internal/edits +github.com/NVIDIA/nvidia-container-toolkit/internal/info/drm +github.com/NVIDIA/nvidia-container-toolkit/internal/info/proc +github.com/NVIDIA/nvidia-container-toolkit/internal/ldcache +github.com/NVIDIA/nvidia-container-toolkit/internal/logger +github.com/NVIDIA/nvidia-container-toolkit/internal/lookup +github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/cuda +github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/root +github.com/NVIDIA/nvidia-container-toolkit/internal/lookup/symlinks +github.com/NVIDIA/nvidia-container-toolkit/internal/nvcaps +github.com/NVIDIA/nvidia-container-toolkit/internal/nvsandboxutils +github.com/NVIDIA/nvidia-container-toolkit/internal/oci +github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/dgpu +github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra +github.com/NVIDIA/nvidia-container-toolkit/internal/platform-support/tegra/csv +github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi +github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/spec +github.com/NVIDIA/nvidia-container-toolkit/pkg/nvcdi/transform # github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc ## explicit github.com/davecgh/go-spew/spew @@ -8,6 +41,10 @@ github.com/davecgh/go-spew/spew ## explicit; go 1.13 github.com/emicklei/go-restful/v3 github.com/emicklei/go-restful/v3/log +# github.com/fsnotify/fsnotify v1.9.0 +## explicit; go 1.17 +github.com/fsnotify/fsnotify +github.com/fsnotify/fsnotify/internal # github.com/fxamacker/cbor/v2 v2.9.0 ## explicit; go 1.20 github.com/fxamacker/cbor/v2 @@ -108,9 +145,26 @@ github.com/onsi/gomega/matchers/support/goraph/edge github.com/onsi/gomega/matchers/support/goraph/node github.com/onsi/gomega/matchers/support/goraph/util github.com/onsi/gomega/types +# github.com/opencontainers/runtime-spec v1.2.1 +## explicit +github.com/opencontainers/runtime-spec/specs-go +# github.com/opencontainers/runtime-tools v0.9.1-0.20221107090550-2e043c6bd626 +## explicit; go 1.16 +github.com/opencontainers/runtime-tools/generate +github.com/opencontainers/runtime-tools/generate/seccomp +github.com/opencontainers/runtime-tools/validate/capabilities # github.com/pkg/errors v0.9.1 ## explicit github.com/pkg/errors +# github.com/sirupsen/logrus v1.9.3 +## explicit; go 1.13 +github.com/sirupsen/logrus +# github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 +## explicit +github.com/syndtr/gocapability/capability +# github.com/urfave/cli/v3 v3.4.1 +## explicit; go 1.22 +github.com/urfave/cli/v3 # github.com/x448/float16 v0.8.4 ## explicit; go 1.11 github.com/x448/float16 @@ -552,3 +606,12 @@ sigs.k8s.io/structured-merge-diff/v6/value # sigs.k8s.io/yaml v1.6.0 ## explicit; go 1.22 sigs.k8s.io/yaml +# tags.cncf.io/container-device-interface v0.8.1 +## explicit; go 1.20 +tags.cncf.io/container-device-interface/internal/validation +tags.cncf.io/container-device-interface/internal/validation/k8s +tags.cncf.io/container-device-interface/pkg/cdi +tags.cncf.io/container-device-interface/pkg/parser +# tags.cncf.io/container-device-interface/specs-go v1.0.0 +## explicit; go 1.19 +tags.cncf.io/container-device-interface/specs-go diff --git a/vendor/tags.cncf.io/container-device-interface/LICENSE b/vendor/tags.cncf.io/container-device-interface/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/objectmeta.go b/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/objectmeta.go new file mode 100644 index 00000000..fb86c67a --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/objectmeta.go @@ -0,0 +1,56 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Adapted from k8s.io/apimachinery/pkg/api/validation: +// https://github.com/kubernetes/apimachinery/blob/7687996c715ee7d5c8cf1e3215e607eb065a4221/pkg/api/validation/objectmeta.go + +package k8s + +import ( + "errors" + "fmt" + "strings" +) + +// TotalAnnotationSizeLimitB defines the maximum size of all annotations in characters. +const TotalAnnotationSizeLimitB int = 256 * (1 << 10) // 256 kB + +// ValidateAnnotations validates that a set of annotations are correctly defined. +func ValidateAnnotations(annotations map[string]string, path string) error { + errs := []error{} + for k := range annotations { + // The rule is QualifiedName except that case doesn't matter, so convert to lowercase before checking. + for _, msg := range IsQualifiedName(strings.ToLower(k)) { + errs = append(errs, fmt.Errorf("%v.%v is invalid: %v", path, k, msg)) + } + } + if err := ValidateAnnotationsSize(annotations); err != nil { + errs = append(errs, fmt.Errorf("%v is too long: %v", path, err)) + } + return errors.Join(errs...) +} + +// ValidateAnnotationsSize validates that a set of annotations is not too large. +func ValidateAnnotationsSize(annotations map[string]string) error { + var totalSize int64 + for k, v := range annotations { + totalSize += (int64)(len(k)) + (int64)(len(v)) + } + if totalSize > (int64)(TotalAnnotationSizeLimitB) { + return fmt.Errorf("annotations size %d is larger than limit %d", totalSize, TotalAnnotationSizeLimitB) + } + return nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/validation.go b/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/validation.go new file mode 100644 index 00000000..5ad6ce27 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/internal/validation/k8s/validation.go @@ -0,0 +1,217 @@ +/* +Copyright 2014 The Kubernetes Authors. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +// Adapted from k8s.io/apimachinery/pkg/util/validation: +// https://github.com/kubernetes/apimachinery/blob/7687996c715ee7d5c8cf1e3215e607eb065a4221/pkg/util/validation/validation.go + +package k8s + +import ( + "fmt" + "regexp" + "strings" +) + +const qnameCharFmt string = "[A-Za-z0-9]" +const qnameExtCharFmt string = "[-A-Za-z0-9_.]" +const qualifiedNameFmt string = "(" + qnameCharFmt + qnameExtCharFmt + "*)?" + qnameCharFmt +const qualifiedNameErrMsg string = "must consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" +const qualifiedNameMaxLength int = 63 + +var qualifiedNameRegexp = regexp.MustCompile("^" + qualifiedNameFmt + "$") + +// IsQualifiedName tests whether the value passed is what Kubernetes calls a +// "qualified name". This is a format used in various places throughout the +// system. If the value is not valid, a list of error strings is returned. +// Otherwise an empty list (or nil) is returned. +func IsQualifiedName(value string) []string { + var errs []string + parts := strings.Split(value, "/") + var name string + switch len(parts) { + case 1: + name = parts[0] + case 2: + var prefix string + prefix, name = parts[0], parts[1] + if len(prefix) == 0 { + errs = append(errs, "prefix part "+EmptyError()) + } else if msgs := IsDNS1123Subdomain(prefix); len(msgs) != 0 { + errs = append(errs, prefixEach(msgs, "prefix part ")...) + } + default: + return append(errs, "a qualified name "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")+ + " with an optional DNS subdomain prefix and '/' (e.g. 'example.com/MyName')") + } + + if len(name) == 0 { + errs = append(errs, "name part "+EmptyError()) + } else if len(name) > qualifiedNameMaxLength { + errs = append(errs, "name part "+MaxLenError(qualifiedNameMaxLength)) + } + if !qualifiedNameRegexp.MatchString(name) { + errs = append(errs, "name part "+RegexError(qualifiedNameErrMsg, qualifiedNameFmt, "MyName", "my.name", "123-abc")) + } + return errs +} + +const labelValueFmt string = "(" + qualifiedNameFmt + ")?" +const labelValueErrMsg string = "a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character" + +// LabelValueMaxLength is a label's max length +const LabelValueMaxLength int = 63 + +var labelValueRegexp = regexp.MustCompile("^" + labelValueFmt + "$") + +// IsValidLabelValue tests whether the value passed is a valid label value. If +// the value is not valid, a list of error strings is returned. Otherwise an +// empty list (or nil) is returned. +func IsValidLabelValue(value string) []string { + var errs []string + if len(value) > LabelValueMaxLength { + errs = append(errs, MaxLenError(LabelValueMaxLength)) + } + if !labelValueRegexp.MatchString(value) { + errs = append(errs, RegexError(labelValueErrMsg, labelValueFmt, "MyValue", "my_value", "12345")) + } + return errs +} + +const dns1123LabelFmt string = "[a-z0-9]([-a-z0-9]*[a-z0-9])?" +const dns1123LabelErrMsg string = "a lowercase RFC 1123 label must consist of lower case alphanumeric characters or '-', and must start and end with an alphanumeric character" + +// DNS1123LabelMaxLength is a label's max length in DNS (RFC 1123) +const DNS1123LabelMaxLength int = 63 + +var dns1123LabelRegexp = regexp.MustCompile("^" + dns1123LabelFmt + "$") + +// IsDNS1123Label tests for a string that conforms to the definition of a label in +// DNS (RFC 1123). +func IsDNS1123Label(value string) []string { + var errs []string + if len(value) > DNS1123LabelMaxLength { + errs = append(errs, MaxLenError(DNS1123LabelMaxLength)) + } + if !dns1123LabelRegexp.MatchString(value) { + errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc")) + } + return errs +} + +const dns1123SubdomainFmt string = dns1123LabelFmt + "(\\." + dns1123LabelFmt + ")*" +const dns1123SubdomainErrorMsg string = "a lowercase RFC 1123 subdomain must consist of lower case alphanumeric characters, '-' or '.', and must start and end with an alphanumeric character" + +// DNS1123SubdomainMaxLength is a subdomain's max length in DNS (RFC 1123) +const DNS1123SubdomainMaxLength int = 253 + +var dns1123SubdomainRegexp = regexp.MustCompile("^" + dns1123SubdomainFmt + "$") + +// IsDNS1123Subdomain tests for a string that conforms to the definition of a +// subdomain in DNS (RFC 1123). +func IsDNS1123Subdomain(value string) []string { + var errs []string + if len(value) > DNS1123SubdomainMaxLength { + errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) + } + if !dns1123SubdomainRegexp.MatchString(value) { + errs = append(errs, RegexError(dns1123SubdomainErrorMsg, dns1123SubdomainFmt, "example.com")) + } + return errs +} + +const dns1035LabelFmt string = "[a-z]([-a-z0-9]*[a-z0-9])?" +const dns1035LabelErrMsg string = "a DNS-1035 label must consist of lower case alphanumeric characters or '-', start with an alphabetic character, and end with an alphanumeric character" + +// DNS1035LabelMaxLength is a label's max length in DNS (RFC 1035) +const DNS1035LabelMaxLength int = 63 + +var dns1035LabelRegexp = regexp.MustCompile("^" + dns1035LabelFmt + "$") + +// IsDNS1035Label tests for a string that conforms to the definition of a label in +// DNS (RFC 1035). +func IsDNS1035Label(value string) []string { + var errs []string + if len(value) > DNS1035LabelMaxLength { + errs = append(errs, MaxLenError(DNS1035LabelMaxLength)) + } + if !dns1035LabelRegexp.MatchString(value) { + errs = append(errs, RegexError(dns1035LabelErrMsg, dns1035LabelFmt, "my-name", "abc-123")) + } + return errs +} + +// wildcard definition - RFC 1034 section 4.3.3. +// examples: +// - valid: *.bar.com, *.foo.bar.com +// - invalid: *.*.bar.com, *.foo.*.com, *bar.com, f*.bar.com, * +const wildcardDNS1123SubdomainFmt = "\\*\\." + dns1123SubdomainFmt +const wildcardDNS1123SubdomainErrMsg = "a wildcard DNS-1123 subdomain must start with '*.', followed by a valid DNS subdomain, which must consist of lower case alphanumeric characters, '-' or '.' and end with an alphanumeric character" + +// IsWildcardDNS1123Subdomain tests for a string that conforms to the definition of a +// wildcard subdomain in DNS (RFC 1034 section 4.3.3). +func IsWildcardDNS1123Subdomain(value string) []string { + wildcardDNS1123SubdomainRegexp := regexp.MustCompile("^" + wildcardDNS1123SubdomainFmt + "$") + + var errs []string + if len(value) > DNS1123SubdomainMaxLength { + errs = append(errs, MaxLenError(DNS1123SubdomainMaxLength)) + } + if !wildcardDNS1123SubdomainRegexp.MatchString(value) { + errs = append(errs, RegexError(wildcardDNS1123SubdomainErrMsg, wildcardDNS1123SubdomainFmt, "*.example.com")) + } + return errs +} + +// MaxLenError returns a string explanation of a "string too long" validation +// failure. +func MaxLenError(length int) string { + return fmt.Sprintf("must be no more than %d characters", length) +} + +// RegexError returns a string explanation of a regex validation failure. +func RegexError(msg string, fmt string, examples ...string) string { + if len(examples) == 0 { + return msg + " (regex used for validation is '" + fmt + "')" + } + msg += " (e.g. " + for i := range examples { + if i > 0 { + msg += " or " + } + msg += "'" + examples[i] + "', " + } + msg += "regex used for validation is '" + fmt + "')" + return msg +} + +// EmptyError returns a string explanation of a "must not be empty" validation +// failure. +func EmptyError() string { + return "must be non-empty" +} + +func prefixEach(msgs []string, prefix string) []string { + for i := range msgs { + msgs[i] = prefix + msgs[i] + } + return msgs +} + +// InclusiveRangeError returns a string explanation of a numeric "must be +// between" validation failure. +func InclusiveRangeError(lo, hi int) string { + return fmt.Sprintf(`must be between %d and %d, inclusive`, lo, hi) +} diff --git a/vendor/tags.cncf.io/container-device-interface/internal/validation/validate.go b/vendor/tags.cncf.io/container-device-interface/internal/validation/validate.go new file mode 100644 index 00000000..5d9b55ff --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/internal/validation/validate.go @@ -0,0 +1,56 @@ +/* + Copyright © The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package validation + +import ( + "fmt" + "strings" + + "tags.cncf.io/container-device-interface/internal/validation/k8s" +) + +// ValidateSpecAnnotations checks whether spec annotations are valid. +func ValidateSpecAnnotations(name string, any interface{}) error { + if any == nil { + return nil + } + + switch v := any.(type) { + case map[string]interface{}: + annotations := make(map[string]string) + for k, v := range v { + if s, ok := v.(string); ok { + annotations[k] = s + } else { + return fmt.Errorf("invalid annotation %v.%v; %v is not a string", name, k, any) + } + } + return validateSpecAnnotations(name, annotations) + } + + return nil +} + +// validateSpecAnnotations checks whether spec annotations are valid. +func validateSpecAnnotations(name string, annotations map[string]string) error { + path := "annotations" + if name != "" { + path = strings.Join([]string{name, path}, ".") + } + + return k8s.ValidateAnnotations(annotations, path) +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/annotations.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/annotations.go new file mode 100644 index 00000000..a38b0f1b --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/annotations.go @@ -0,0 +1,141 @@ +/* + Copyright © 2021-2022 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "errors" + "fmt" + "strings" + + "tags.cncf.io/container-device-interface/pkg/parser" +) + +const ( + // AnnotationPrefix is the prefix for CDI container annotation keys. + AnnotationPrefix = "cdi.k8s.io/" +) + +// UpdateAnnotations updates annotations with a plugin-specific CDI device +// injection request for the given devices. Upon any error a non-nil error +// is returned and annotations are left intact. By convention plugin should +// be in the format of "vendor.device-type". +func UpdateAnnotations(annotations map[string]string, plugin string, deviceID string, devices []string) (map[string]string, error) { + key, err := AnnotationKey(plugin, deviceID) + if err != nil { + return annotations, fmt.Errorf("CDI annotation failed: %w", err) + } + if _, ok := annotations[key]; ok { + return annotations, fmt.Errorf("CDI annotation failed, key %q used", key) + } + value, err := AnnotationValue(devices) + if err != nil { + return annotations, fmt.Errorf("CDI annotation failed: %w", err) + } + + if annotations == nil { + annotations = make(map[string]string) + } + annotations[key] = value + + return annotations, nil +} + +// ParseAnnotations parses annotations for CDI device injection requests. +// The keys and devices from all such requests are collected into slices +// which are returned as the result. All devices are expected to be fully +// qualified CDI device names. If any device fails this check empty slices +// are returned along with a non-nil error. The annotations are expected +// to be formatted by, or in a compatible fashion to UpdateAnnotations(). +func ParseAnnotations(annotations map[string]string) ([]string, []string, error) { + var ( + keys []string + devices []string + ) + + for key, value := range annotations { + if !strings.HasPrefix(key, AnnotationPrefix) { + continue + } + for _, d := range strings.Split(value, ",") { + if !IsQualifiedName(d) { + return nil, nil, fmt.Errorf("invalid CDI device name %q", d) + } + devices = append(devices, d) + } + keys = append(keys, key) + } + + return keys, devices, nil +} + +// AnnotationKey returns a unique annotation key for an device allocation +// by a K8s device plugin. pluginName should be in the format of +// "vendor.device-type". deviceID is the ID of the device the plugin is +// allocating. It is used to make sure that the generated key is unique +// even if multiple allocations by a single plugin needs to be annotated. +func AnnotationKey(pluginName, deviceID string) (string, error) { + const maxNameLen = 63 + + if pluginName == "" { + return "", errors.New("invalid plugin name, empty") + } + if deviceID == "" { + return "", errors.New("invalid deviceID, empty") + } + + name := pluginName + "_" + strings.ReplaceAll(deviceID, "/", "_") + + if len(name) > maxNameLen { + return "", fmt.Errorf("invalid plugin+deviceID %q, too long", name) + } + + if c := rune(name[0]); !parser.IsAlphaNumeric(c) { + return "", fmt.Errorf("invalid name %q, first '%c' should be alphanumeric", + name, c) + } + if len(name) > 2 { + for _, c := range name[1 : len(name)-1] { + switch { + case parser.IsAlphaNumeric(c): + case c == '_' || c == '-' || c == '.': + default: + return "", fmt.Errorf("invalid name %q, invalid character '%c'", + name, c) + } + } + } + if c := rune(name[len(name)-1]); !parser.IsAlphaNumeric(c) { + return "", fmt.Errorf("invalid name %q, last '%c' should be alphanumeric", + name, c) + } + + return AnnotationPrefix + name, nil +} + +// AnnotationValue returns an annotation value for the given devices. +func AnnotationValue(devices []string) (string, error) { + value, sep := "", "" + for _, d := range devices { + if _, _, _, err := ParseQualifiedName(d); err != nil { + return "", err + } + value += sep + d + sep = "," + } + + return value, nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache.go new file mode 100644 index 00000000..9afa4b18 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache.go @@ -0,0 +1,598 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "errors" + "fmt" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + "sync" + + "github.com/fsnotify/fsnotify" + oci "github.com/opencontainers/runtime-spec/specs-go" + cdi "tags.cncf.io/container-device-interface/specs-go" +) + +// Option is an option to change some aspect of default CDI behavior. +type Option func(*Cache) + +// Cache stores CDI Specs loaded from Spec directories. +type Cache struct { + sync.Mutex + specDirs []string + specs map[string][]*Spec + devices map[string]*Device + errors map[string][]error + dirErrors map[string]error + + autoRefresh bool + watch *watch +} + +// WithAutoRefresh returns an option to control automatic Cache refresh. +// By default, auto-refresh is enabled, the list of Spec directories are +// monitored and the Cache is automatically refreshed whenever a change +// is detected. This option can be used to disable this behavior when a +// manually refreshed mode is preferable. +func WithAutoRefresh(autoRefresh bool) Option { + return func(c *Cache) { + c.autoRefresh = autoRefresh + } +} + +// NewCache creates a new CDI Cache. The cache is populated from a set +// of CDI Spec directories. These can be specified using a WithSpecDirs +// option. The default set of directories is exposed in DefaultSpecDirs. +// +// Note: +// +// The error returned by this function is always nil and it is only +// returned to maintain API compatibility with consumers. +func NewCache(options ...Option) (*Cache, error) { + return newCache(options...), nil +} + +// newCache creates a CDI cache with the supplied options. +// This function allows testing without handling the nil error returned by the +// NewCache function. +func newCache(options ...Option) *Cache { + c := &Cache{ + autoRefresh: true, + watch: &watch{}, + } + + WithSpecDirs(DefaultSpecDirs...)(c) + c.Lock() + defer c.Unlock() + + c.configure(options...) + return c +} + +// Configure applies options to the Cache. Updates and refreshes the +// Cache if options have changed. +func (c *Cache) Configure(options ...Option) error { + if len(options) == 0 { + return nil + } + + c.Lock() + defer c.Unlock() + + c.configure(options...) + + return nil +} + +// Configure the Cache. Start/stop CDI Spec directory watch, refresh +// the Cache if necessary. +func (c *Cache) configure(options ...Option) { + for _, o := range options { + o(c) + } + + c.dirErrors = make(map[string]error) + + c.watch.stop() + if c.autoRefresh { + c.watch.setup(c.specDirs, c.dirErrors) + c.watch.start(&c.Mutex, c.refresh, c.dirErrors) + } + c.refresh() +} + +// Refresh rescans the CDI Spec directories and refreshes the Cache. +// In manual refresh mode the cache is always refreshed. In auto- +// refresh mode the cache is only refreshed if it is out of date. +func (c *Cache) Refresh() error { + c.Lock() + defer c.Unlock() + + // force a refresh in manual mode + if refreshed, err := c.refreshIfRequired(!c.autoRefresh); refreshed { + return err + } + + // collect and return cached errors, much like refresh() does it + errs := []error{} + for _, specErrs := range c.errors { + errs = append(errs, errors.Join(specErrs...)) + } + return errors.Join(errs...) +} + +// Refresh the Cache by rescanning CDI Spec directories and files. +func (c *Cache) refresh() error { + var ( + specs = map[string][]*Spec{} + devices = map[string]*Device{} + conflicts = map[string]struct{}{} + specErrors = map[string][]error{} + ) + + // collect errors per spec file path and once globally + collectError := func(err error, paths ...string) { + for _, path := range paths { + specErrors[path] = append(specErrors[path], err) + } + } + // resolve conflicts based on device Spec priority (order of precedence) + resolveConflict := func(name string, dev *Device, old *Device) bool { + devSpec, oldSpec := dev.GetSpec(), old.GetSpec() + devPrio, oldPrio := devSpec.GetPriority(), oldSpec.GetPriority() + switch { + case devPrio > oldPrio: + return false + case devPrio == oldPrio: + devPath, oldPath := devSpec.GetPath(), oldSpec.GetPath() + collectError(fmt.Errorf("conflicting device %q (specs %q, %q)", + name, devPath, oldPath), devPath, oldPath) + conflicts[name] = struct{}{} + } + return true + } + + _ = scanSpecDirs(c.specDirs, func(path string, priority int, spec *Spec, err error) error { + path = filepath.Clean(path) + if err != nil { + collectError(fmt.Errorf("failed to load CDI Spec %w", err), path) + return nil + } + + vendor := spec.GetVendor() + specs[vendor] = append(specs[vendor], spec) + + for _, dev := range spec.devices { + qualified := dev.GetQualifiedName() + other, ok := devices[qualified] + if ok { + if resolveConflict(qualified, dev, other) { + continue + } + } + devices[qualified] = dev + } + + return nil + }) + + for conflict := range conflicts { + delete(devices, conflict) + } + + c.specs = specs + c.devices = devices + c.errors = specErrors + + errs := []error{} + for _, specErrs := range specErrors { + errs = append(errs, errors.Join(specErrs...)) + } + return errors.Join(errs...) +} + +// RefreshIfRequired triggers a refresh if necessary. +func (c *Cache) refreshIfRequired(force bool) (bool, error) { + // We need to refresh if + // - it's forced by an explicit call to Refresh() in manual mode + // - a missing Spec dir appears (added to watch) in auto-refresh mode + if force || (c.autoRefresh && c.watch.update(c.dirErrors)) { + return true, c.refresh() + } + return false, nil +} + +// InjectDevices injects the given qualified devices to an OCI Spec. It +// returns any unresolvable devices and an error if injection fails for +// any of the devices. +func (c *Cache) InjectDevices(ociSpec *oci.Spec, devices ...string) ([]string, error) { + var unresolved []string + + if ociSpec == nil { + return devices, fmt.Errorf("can't inject devices, nil OCI Spec") + } + + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + edits := &ContainerEdits{} + specs := map[*Spec]struct{}{} + + for _, device := range devices { + d := c.devices[device] + if d == nil { + unresolved = append(unresolved, device) + continue + } + if _, ok := specs[d.GetSpec()]; !ok { + specs[d.GetSpec()] = struct{}{} + edits.Append(d.GetSpec().edits()) + } + edits.Append(d.edits()) + } + + if unresolved != nil { + return unresolved, fmt.Errorf("unresolvable CDI devices %s", + strings.Join(unresolved, ", ")) + } + + if err := edits.Apply(ociSpec); err != nil { + return nil, fmt.Errorf("failed to inject devices: %w", err) + } + + return nil, nil +} + +// highestPrioritySpecDir returns the Spec directory with highest priority +// and its priority. +func (c *Cache) highestPrioritySpecDir() (string, int) { + if len(c.specDirs) == 0 { + return "", -1 + } + + prio := len(c.specDirs) - 1 + dir := c.specDirs[prio] + + return dir, prio +} + +// WriteSpec writes a Spec file with the given content into the highest +// priority Spec directory. If name has a "json" or "yaml" extension it +// choses the encoding. Otherwise the default YAML encoding is used. +func (c *Cache) WriteSpec(raw *cdi.Spec, name string) error { + var ( + specDir string + path string + prio int + spec *Spec + err error + ) + + specDir, prio = c.highestPrioritySpecDir() + if specDir == "" { + return errors.New("no Spec directories to write to") + } + + path = filepath.Join(specDir, name) + if ext := filepath.Ext(path); ext != ".json" && ext != ".yaml" { + path += defaultSpecExt + } + + spec, err = newSpec(raw, path, prio) + if err != nil { + return err + } + + return spec.write(true) +} + +// RemoveSpec removes a Spec with the given name from the highest +// priority Spec directory. This function can be used to remove a +// Spec previously written by WriteSpec(). If the file exists and +// its removal fails RemoveSpec returns an error. +func (c *Cache) RemoveSpec(name string) error { + var ( + specDir string + path string + err error + ) + + specDir, _ = c.highestPrioritySpecDir() + if specDir == "" { + return errors.New("no Spec directories to remove from") + } + + path = filepath.Join(specDir, name) + if ext := filepath.Ext(path); ext != ".json" && ext != ".yaml" { + path += defaultSpecExt + } + + err = os.Remove(path) + if err != nil && errors.Is(err, fs.ErrNotExist) { + err = nil + } + + return err +} + +// GetDevice returns the cached device for the given qualified name. +func (c *Cache) GetDevice(device string) *Device { + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + return c.devices[device] +} + +// ListDevices lists all cached devices by qualified name. +func (c *Cache) ListDevices() []string { + var devices []string + + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + for name := range c.devices { + devices = append(devices, name) + } + sort.Strings(devices) + + return devices +} + +// ListVendors lists all vendors known to the cache. +func (c *Cache) ListVendors() []string { + var vendors []string + + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + for vendor := range c.specs { + vendors = append(vendors, vendor) + } + sort.Strings(vendors) + + return vendors +} + +// ListClasses lists all device classes known to the cache. +func (c *Cache) ListClasses() []string { + var ( + cmap = map[string]struct{}{} + classes []string + ) + + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + for _, specs := range c.specs { + for _, spec := range specs { + cmap[spec.GetClass()] = struct{}{} + } + } + for class := range cmap { + classes = append(classes, class) + } + sort.Strings(classes) + + return classes +} + +// GetVendorSpecs returns all specs for the given vendor. +func (c *Cache) GetVendorSpecs(vendor string) []*Spec { + c.Lock() + defer c.Unlock() + + c.refreshIfRequired(false) + + return c.specs[vendor] +} + +// GetSpecErrors returns all errors encountered for the spec during the +// last cache refresh. +func (c *Cache) GetSpecErrors(spec *Spec) []error { + var errors []error + + c.Lock() + defer c.Unlock() + + if errs, ok := c.errors[spec.GetPath()]; ok { + errors = make([]error, len(errs)) + copy(errors, errs) + } + + return errors +} + +// GetErrors returns all errors encountered during the last +// cache refresh. +func (c *Cache) GetErrors() map[string][]error { + c.Lock() + defer c.Unlock() + + errors := map[string][]error{} + for path, errs := range c.errors { + errors[path] = errs + } + for path, err := range c.dirErrors { + errors[path] = []error{err} + } + + return errors +} + +// GetSpecDirectories returns the CDI Spec directories currently in use. +func (c *Cache) GetSpecDirectories() []string { + c.Lock() + defer c.Unlock() + + dirs := make([]string, len(c.specDirs)) + copy(dirs, c.specDirs) + return dirs +} + +// GetSpecDirErrors returns any errors related to configured Spec directories. +func (c *Cache) GetSpecDirErrors() map[string]error { + if c.dirErrors == nil { + return nil + } + + c.Lock() + defer c.Unlock() + + errors := make(map[string]error) + for dir, err := range c.dirErrors { + errors[dir] = err + } + return errors +} + +// Our fsnotify helper wrapper. +type watch struct { + watcher *fsnotify.Watcher + tracked map[string]bool +} + +// Setup monitoring for the given Spec directories. +func (w *watch) setup(dirs []string, dirErrors map[string]error) { + var ( + dir string + err error + ) + w.tracked = make(map[string]bool) + for _, dir = range dirs { + w.tracked[dir] = false + } + + w.watcher, err = fsnotify.NewWatcher() + if err != nil { + for _, dir := range dirs { + dirErrors[dir] = fmt.Errorf("failed to create watcher: %w", err) + } + return + } + + w.update(dirErrors) +} + +// Start watching Spec directories for relevant changes. +func (w *watch) start(m *sync.Mutex, refresh func() error, dirErrors map[string]error) { + go w.watch(w.watcher, m, refresh, dirErrors) +} + +// Stop watching directories. +func (w *watch) stop() { + if w.watcher == nil { + return + } + + w.watcher.Close() + w.tracked = nil +} + +// Watch Spec directory changes, triggering a refresh if necessary. +func (w *watch) watch(fsw *fsnotify.Watcher, m *sync.Mutex, refresh func() error, dirErrors map[string]error) { + watch := fsw + if watch == nil { + return + } + for { + select { + case event, ok := <-watch.Events: + if !ok { + return + } + + if (event.Op & (fsnotify.Rename | fsnotify.Remove | fsnotify.Write)) == 0 { + continue + } + if event.Op == fsnotify.Write { + if ext := filepath.Ext(event.Name); ext != ".json" && ext != ".yaml" { + continue + } + } + + m.Lock() + if event.Op == fsnotify.Remove && w.tracked[event.Name] { + w.update(dirErrors, event.Name) + } else { + w.update(dirErrors) + } + refresh() + m.Unlock() + + case _, ok := <-watch.Errors: + if !ok { + return + } + } + } +} + +// Update watch with pending/missing or removed directories. +func (w *watch) update(dirErrors map[string]error, removed ...string) bool { + var ( + dir string + ok bool + err error + update bool + ) + + // If we failed to create an fsnotify.Watcher we have a nil watcher here + // (but with autoRefresh left on). One known case when this can happen is + // if we have too many open files. In that case we always return true and + // force a refresh. + if w.watcher == nil { + return true + } + + for dir, ok = range w.tracked { + if ok { + continue + } + + err = w.watcher.Add(dir) + if err == nil { + w.tracked[dir] = true + delete(dirErrors, dir) + update = true + } else { + w.tracked[dir] = false + dirErrors[dir] = fmt.Errorf("failed to monitor for changes: %w", err) + } + } + + for _, dir = range removed { + w.tracked[dir] = false + dirErrors[dir] = errors.New("directory removed") + update = true + } + + return update +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_unix.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_unix.go new file mode 100644 index 00000000..0ee5fb86 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_unix.go @@ -0,0 +1,26 @@ +//go:build !windows +// +build !windows + +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import "syscall" + +func osSync() { + syscall.Sync() +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_windows.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_windows.go new file mode 100644 index 00000000..c6dabf5f --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/cache_test_windows.go @@ -0,0 +1,22 @@ +//go:build windows +// +build windows + +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +func osSync() {} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go new file mode 100644 index 00000000..70791666 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits.go @@ -0,0 +1,396 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "sort" + "strings" + + oci "github.com/opencontainers/runtime-spec/specs-go" + ocigen "github.com/opencontainers/runtime-tools/generate" + "tags.cncf.io/container-device-interface/specs-go" +) + +const ( + // PrestartHook is the name of the OCI "prestart" hook. + PrestartHook = "prestart" + // CreateRuntimeHook is the name of the OCI "createRuntime" hook. + CreateRuntimeHook = "createRuntime" + // CreateContainerHook is the name of the OCI "createContainer" hook. + CreateContainerHook = "createContainer" + // StartContainerHook is the name of the OCI "startContainer" hook. + StartContainerHook = "startContainer" + // PoststartHook is the name of the OCI "poststart" hook. + PoststartHook = "poststart" + // PoststopHook is the name of the OCI "poststop" hook. + PoststopHook = "poststop" +) + +var ( + // Names of recognized hooks. + validHookNames = map[string]struct{}{ + PrestartHook: {}, + CreateRuntimeHook: {}, + CreateContainerHook: {}, + StartContainerHook: {}, + PoststartHook: {}, + PoststopHook: {}, + } +) + +// ContainerEdits represent updates to be applied to an OCI Spec. +// These updates can be specific to a CDI device, or they can be +// specific to a CDI Spec. In the former case these edits should +// be applied to all OCI Specs where the corresponding CDI device +// is injected. In the latter case, these edits should be applied +// to all OCI Specs where at least one devices from the CDI Spec +// is injected. +type ContainerEdits struct { + *specs.ContainerEdits +} + +// Apply edits to the given OCI Spec. Updates the OCI Spec in place. +// Returns an error if the update fails. +func (e *ContainerEdits) Apply(spec *oci.Spec) error { + if spec == nil { + return errors.New("can't edit nil OCI Spec") + } + if e == nil || e.ContainerEdits == nil { + return nil + } + + specgen := ocigen.NewFromSpec(spec) + if len(e.Env) > 0 { + specgen.AddMultipleProcessEnv(e.Env) + } + + for _, d := range e.DeviceNodes { + dn := DeviceNode{d} + + err := dn.fillMissingInfo() + if err != nil { + return err + } + dev := dn.toOCI() + if dev.UID == nil && spec.Process != nil { + if uid := spec.Process.User.UID; uid > 0 { + dev.UID = &uid + } + } + if dev.GID == nil && spec.Process != nil { + if gid := spec.Process.User.GID; gid > 0 { + dev.GID = &gid + } + } + + specgen.RemoveDevice(dev.Path) + specgen.AddDevice(dev) + + if dev.Type == "b" || dev.Type == "c" { + access := d.Permissions + if access == "" { + access = "rwm" + } + specgen.AddLinuxResourcesDevice(true, dev.Type, &dev.Major, &dev.Minor, access) + } + } + + if len(e.Mounts) > 0 { + for _, m := range e.Mounts { + specgen.RemoveMount(m.ContainerPath) + specgen.AddMount((&Mount{m}).toOCI()) + } + sortMounts(&specgen) + } + + for _, h := range e.Hooks { + ociHook := (&Hook{h}).toOCI() + switch h.HookName { + case PrestartHook: + specgen.AddPreStartHook(ociHook) + case PoststartHook: + specgen.AddPostStartHook(ociHook) + case PoststopHook: + specgen.AddPostStopHook(ociHook) + // TODO: Maybe runtime-tools/generate should be updated with these... + case CreateRuntimeHook: + ensureOCIHooks(spec) + spec.Hooks.CreateRuntime = append(spec.Hooks.CreateRuntime, ociHook) + case CreateContainerHook: + ensureOCIHooks(spec) + spec.Hooks.CreateContainer = append(spec.Hooks.CreateContainer, ociHook) + case StartContainerHook: + ensureOCIHooks(spec) + spec.Hooks.StartContainer = append(spec.Hooks.StartContainer, ociHook) + default: + return fmt.Errorf("unknown hook name %q", h.HookName) + } + } + + if e.IntelRdt != nil { + // The specgen is missing functionality to set all parameters so we + // just piggy-back on it to initialize all structs and the copy over. + specgen.SetLinuxIntelRdtClosID(e.IntelRdt.ClosID) + spec.Linux.IntelRdt = (&IntelRdt{e.IntelRdt}).toOCI() + } + + for _, additionalGID := range e.AdditionalGIDs { + if additionalGID == 0 { + continue + } + specgen.AddProcessAdditionalGid(additionalGID) + } + + return nil +} + +// Validate container edits. +func (e *ContainerEdits) Validate() error { + if e == nil || e.ContainerEdits == nil { + return nil + } + + if err := ValidateEnv(e.Env); err != nil { + return fmt.Errorf("invalid container edits: %w", err) + } + for _, d := range e.DeviceNodes { + if err := (&DeviceNode{d}).Validate(); err != nil { + return err + } + } + for _, h := range e.Hooks { + if err := (&Hook{h}).Validate(); err != nil { + return err + } + } + for _, m := range e.Mounts { + if err := (&Mount{m}).Validate(); err != nil { + return err + } + } + if e.IntelRdt != nil { + if err := (&IntelRdt{e.IntelRdt}).Validate(); err != nil { + return err + } + } + + return nil +} + +// Append other edits into this one. If called with a nil receiver, +// allocates and returns newly allocated edits. +func (e *ContainerEdits) Append(o *ContainerEdits) *ContainerEdits { + if o == nil || o.ContainerEdits == nil { + return e + } + if e == nil { + e = &ContainerEdits{} + } + if e.ContainerEdits == nil { + e.ContainerEdits = &specs.ContainerEdits{} + } + + e.Env = append(e.Env, o.Env...) + e.DeviceNodes = append(e.DeviceNodes, o.DeviceNodes...) + e.Hooks = append(e.Hooks, o.Hooks...) + e.Mounts = append(e.Mounts, o.Mounts...) + if o.IntelRdt != nil { + e.IntelRdt = o.IntelRdt + } + e.AdditionalGIDs = append(e.AdditionalGIDs, o.AdditionalGIDs...) + + return e +} + +// isEmpty returns true if these edits are empty. This is valid in a +// global Spec context but invalid in a Device context. +func (e *ContainerEdits) isEmpty() bool { + if e == nil { + return false + } + if len(e.Env) > 0 { + return false + } + if len(e.DeviceNodes) > 0 { + return false + } + if len(e.Hooks) > 0 { + return false + } + if len(e.Mounts) > 0 { + return false + } + if len(e.AdditionalGIDs) > 0 { + return false + } + if e.IntelRdt != nil { + return false + } + return true +} + +// ValidateEnv validates the given environment variables. +func ValidateEnv(env []string) error { + for _, v := range env { + if strings.IndexByte(v, byte('=')) <= 0 { + return fmt.Errorf("invalid environment variable %q", v) + } + } + return nil +} + +// DeviceNode is a CDI Spec DeviceNode wrapper, used for validating DeviceNodes. +type DeviceNode struct { + *specs.DeviceNode +} + +// Validate a CDI Spec DeviceNode. +func (d *DeviceNode) Validate() error { + validTypes := map[string]struct{}{ + "": {}, + "b": {}, + "c": {}, + "u": {}, + "p": {}, + } + + if d.Path == "" { + return errors.New("invalid (empty) device path") + } + if _, ok := validTypes[d.Type]; !ok { + return fmt.Errorf("device %q: invalid type %q", d.Path, d.Type) + } + for _, bit := range d.Permissions { + if bit != 'r' && bit != 'w' && bit != 'm' { + return fmt.Errorf("device %q: invalid permissions %q", + d.Path, d.Permissions) + } + } + return nil +} + +// Hook is a CDI Spec Hook wrapper, used for validating hooks. +type Hook struct { + *specs.Hook +} + +// Validate a hook. +func (h *Hook) Validate() error { + if _, ok := validHookNames[h.HookName]; !ok { + return fmt.Errorf("invalid hook name %q", h.HookName) + } + if h.Path == "" { + return fmt.Errorf("invalid hook %q with empty path", h.HookName) + } + if err := ValidateEnv(h.Env); err != nil { + return fmt.Errorf("invalid hook %q: %w", h.HookName, err) + } + return nil +} + +// Mount is a CDI Mount wrapper, used for validating mounts. +type Mount struct { + *specs.Mount +} + +// Validate a mount. +func (m *Mount) Validate() error { + if m.HostPath == "" { + return errors.New("invalid mount, empty host path") + } + if m.ContainerPath == "" { + return errors.New("invalid mount, empty container path") + } + return nil +} + +// IntelRdt is a CDI IntelRdt wrapper. +// This is used for validation and conversion to OCI specifications. +type IntelRdt struct { + *specs.IntelRdt +} + +// ValidateIntelRdt validates the IntelRdt configuration. +// +// Deprecated: ValidateIntelRdt is deprecated use IntelRdt.Validate() instead. +func ValidateIntelRdt(i *specs.IntelRdt) error { + return (&IntelRdt{i}).Validate() +} + +// Validate validates the IntelRdt configuration. +func (i *IntelRdt) Validate() error { + // ClosID must be a valid Linux filename + if len(i.ClosID) >= 4096 || i.ClosID == "." || i.ClosID == ".." || strings.ContainsAny(i.ClosID, "/\n") { + return errors.New("invalid ClosID") + } + return nil +} + +// Ensure OCI Spec hooks are not nil so we can add hooks. +func ensureOCIHooks(spec *oci.Spec) { + if spec.Hooks == nil { + spec.Hooks = &oci.Hooks{} + } +} + +// sortMounts sorts the mounts in the given OCI Spec. +func sortMounts(specgen *ocigen.Generator) { + mounts := specgen.Mounts() + specgen.ClearMounts() + sort.Sort(orderedMounts(mounts)) + specgen.Config.Mounts = mounts +} + +// orderedMounts defines how to sort an OCI Spec Mount slice. +// This is the almost the same implementation sa used by CRI-O and Docker, +// with a minor tweak for stable sorting order (easier to test): +// +// https://github.com/moby/moby/blob/17.05.x/daemon/volumes.go#L26 +type orderedMounts []oci.Mount + +// Len returns the number of mounts. Used in sorting. +func (m orderedMounts) Len() int { + return len(m) +} + +// Less returns true if the number of parts (a/b/c would be 3 parts) in the +// mount indexed by parameter 1 is less than that of the mount indexed by +// parameter 2. Used in sorting. +func (m orderedMounts) Less(i, j int) bool { + ip, jp := m.parts(i), m.parts(j) + if ip < jp { + return true + } + if jp < ip { + return false + } + return m[i].Destination < m[j].Destination +} + +// Swap swaps two items in an array of mounts. Used in sorting +func (m orderedMounts) Swap(i, j int) { + m[i], m[j] = m[j], m[i] +} + +// parts returns the number of parts in the destination of a mount. Used in sorting. +func (m orderedMounts) parts(i int) int { + return strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator)) +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_unix.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_unix.go new file mode 100644 index 00000000..59977b21 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_unix.go @@ -0,0 +1,88 @@ +//go:build !windows +// +build !windows + +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "errors" + "fmt" + + "golang.org/x/sys/unix" +) + +const ( + blockDevice = "b" + charDevice = "c" // or "u" + fifoDevice = "p" +) + +// deviceInfoFromPath takes the path to a device and returns its type, +// major and minor device numbers. +// +// It was adapted from https://github.com/opencontainers/runc/blob/v1.1.9/libcontainer/devices/device_unix.go#L30-L69 +func deviceInfoFromPath(path string) (devType string, major, minor int64, _ error) { + var stat unix.Stat_t + err := unix.Lstat(path, &stat) + if err != nil { + return "", 0, 0, err + } + switch stat.Mode & unix.S_IFMT { + case unix.S_IFBLK: + devType = blockDevice + case unix.S_IFCHR: + devType = charDevice + case unix.S_IFIFO: + devType = fifoDevice + default: + return "", 0, 0, errors.New("not a device node") + } + devNumber := uint64(stat.Rdev) //nolint:unconvert // Rdev is uint32 on e.g. MIPS. + return devType, int64(unix.Major(devNumber)), int64(unix.Minor(devNumber)), nil +} + +// fillMissingInfo fills in missing mandatory attributes from the host device. +func (d *DeviceNode) fillMissingInfo() error { + if d.HostPath == "" { + d.HostPath = d.Path + } + + if d.Type != "" && (d.Major != 0 || d.Type == "p") { + return nil + } + + deviceType, major, minor, err := deviceInfoFromPath(d.HostPath) + if err != nil { + return fmt.Errorf("failed to stat CDI host device %q: %w", d.HostPath, err) + } + + if d.Type == "" { + d.Type = deviceType + } else { + if d.Type != deviceType { + return fmt.Errorf("CDI device (%q, %q), host type mismatch (%s, %s)", + d.Path, d.HostPath, d.Type, deviceType) + } + } + if d.Major == 0 && d.Type != "p" { + d.Major = major + d.Minor = minor + } + + return nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_windows.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_windows.go new file mode 100644 index 00000000..fd91afa9 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/container-edits_windows.go @@ -0,0 +1,27 @@ +//go:build windows +// +build windows + +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import "fmt" + +// fillMissingInfo fills in missing mandatory attributes from the host device. +func (d *DeviceNode) fillMissingInfo() error { + return fmt.Errorf("unimplemented") +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/default-cache.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/default-cache.go new file mode 100644 index 00000000..7886ee51 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/default-cache.go @@ -0,0 +1,70 @@ +/* + Copyright © 2024 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "sync" + + oci "github.com/opencontainers/runtime-spec/specs-go" +) + +var ( + defaultCache *Cache + getDefaultOnce sync.Once +) + +func getOrCreateDefaultCache(options ...Option) (*Cache, bool) { + var created bool + getDefaultOnce.Do(func() { + defaultCache = newCache(options...) + created = true + }) + return defaultCache, created +} + +// GetDefaultCache returns the default CDI cache instance. +func GetDefaultCache() *Cache { + cache, _ := getOrCreateDefaultCache() + return cache +} + +// Configure applies options to the default CDI cache. Updates and refreshes +// the default cache if options are not empty. +func Configure(options ...Option) error { + cache, created := getOrCreateDefaultCache(options...) + if len(options) == 0 || created { + return nil + } + return cache.Configure(options...) +} + +// Refresh explicitly refreshes the default CDI cache instance. +func Refresh() error { + return GetDefaultCache().Refresh() +} + +// InjectDevices injects the given qualified devices to the given OCI Spec. +// using the default CDI cache instance to resolve devices. +func InjectDevices(ociSpec *oci.Spec, devices ...string) ([]string, error) { + return GetDefaultCache().InjectDevices(ociSpec, devices...) +} + +// GetErrors returns all errors encountered during the last refresh of +// the default CDI cache instance. +func GetErrors() map[string][]error { + return GetDefaultCache().GetErrors() +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/device.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/device.go new file mode 100644 index 00000000..00be48dd --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/device.go @@ -0,0 +1,88 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "fmt" + + oci "github.com/opencontainers/runtime-spec/specs-go" + "tags.cncf.io/container-device-interface/internal/validation" + "tags.cncf.io/container-device-interface/pkg/parser" + cdi "tags.cncf.io/container-device-interface/specs-go" +) + +// Device represents a CDI device of a Spec. +type Device struct { + *cdi.Device + spec *Spec +} + +// Create a new Device, associate it with the given Spec. +func newDevice(spec *Spec, d cdi.Device) (*Device, error) { + dev := &Device{ + Device: &d, + spec: spec, + } + + if err := dev.validate(); err != nil { + return nil, err + } + + return dev, nil +} + +// GetSpec returns the Spec this device is defined in. +func (d *Device) GetSpec() *Spec { + return d.spec +} + +// GetQualifiedName returns the qualified name for this device. +func (d *Device) GetQualifiedName() string { + return parser.QualifiedName(d.spec.GetVendor(), d.spec.GetClass(), d.Name) +} + +// ApplyEdits applies the device-speific container edits to an OCI Spec. +func (d *Device) ApplyEdits(ociSpec *oci.Spec) error { + return d.edits().Apply(ociSpec) +} + +// edits returns the applicable container edits for this spec. +func (d *Device) edits() *ContainerEdits { + return &ContainerEdits{&d.ContainerEdits} +} + +// Validate the device. +func (d *Device) validate() error { + if err := ValidateDeviceName(d.Name); err != nil { + return err + } + name := d.Name + if d.spec != nil { + name = d.GetQualifiedName() + } + if err := validation.ValidateSpecAnnotations(name, d.Annotations); err != nil { + return err + } + edits := d.edits() + if edits.isEmpty() { + return fmt.Errorf("invalid device, empty device edits") + } + if err := edits.Validate(); err != nil { + return fmt.Errorf("invalid device %q: %w", d.Name, err) + } + return nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/doc.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/doc.go new file mode 100644 index 00000000..0ea07145 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/doc.go @@ -0,0 +1,290 @@ +// Package cdi has the primary purpose of providing an API for +// interacting with CDI and consuming CDI devices. +// +// For more information about Container Device Interface, please refer to +// https://tags.cncf.io/container-device-interface +// +// # Container Device Interface +// +// Container Device Interface, or CDI for short, provides comprehensive +// third party device support for container runtimes. CDI uses vendor +// provided specification files, CDI Specs for short, to describe how a +// container's runtime environment should be modified when one or more +// of the vendor-specific devices is injected into the container. Beyond +// describing the low level platform-specific details of how to gain +// basic access to a device, CDI Specs allow more fine-grained device +// initialization, and the automatic injection of any necessary vendor- +// or device-specific software that might be required for a container +// to use a device or take full advantage of it. +// +// In the CDI device model containers request access to a device using +// fully qualified device names, qualified names for short, consisting of +// a vendor identifier, a device class and a device name or identifier. +// These pieces of information together uniquely identify a device among +// all device vendors, classes and device instances. +// +// This package implements an API for easy consumption of CDI. The API +// implements discovery, loading and caching of CDI Specs and injection +// of CDI devices into containers. This is the most common functionality +// the vast majority of CDI consumers need. The API should be usable both +// by OCI runtime clients and runtime implementations. +// +// # Default CDI Cache +// +// There is a default CDI cache instance which is always implicitly +// available and instantiated the first time it is referenced directly +// or indirectly. The most frequently used cache functions are available +// as identically named package level functions which operate on the +// default cache instance. Moreover, the registry also operates on the +// same default cache. We plan to deprecate the registry and eventually +// remove it in a future release. +// +// # CDI Registry +// +// Note: the Registry and its related interfaces are deprecated and will +// be removed in a future version. Please use the default cache and its +// related package-level function instead. +// +// The primary interface to interact with CDI devices is the Registry. It +// is essentially a cache of all Specs and devices discovered in standard +// CDI directories on the host. The registry has two main functionality, +// injecting devices into an OCI Spec and refreshing the cache of CDI +// Specs and devices. +// +// # Device Injection +// +// Using the Registry one can inject CDI devices into a container with code +// similar to the following snippet: +// +// import ( +// "fmt" +// "strings" +// +// log "github.com/sirupsen/logrus" +// +// "tags.cncf.io/container-device-interface/pkg/cdi" +// oci "github.com/opencontainers/runtime-spec/specs-go" +// ) +// +// func injectCDIDevices(spec *oci.Spec, devices []string) error { +// log.Debug("pristine OCI Spec: %s", dumpSpec(spec)) +// +// unresolved, err := cdi.GetRegistry().InjectDevices(spec, devices) +// if err != nil { +// return fmt.Errorf("CDI device injection failed: %w", err) +// } +// +// log.Debug("CDI-updated OCI Spec: %s", dumpSpec(spec)) +// return nil +// } +// +// # Cache Refresh +// +// By default the CDI Spec cache monitors the configured Spec directories +// and automatically refreshes itself when necessary. This behavior can be +// disabled using the WithAutoRefresh(false) option. +// +// Failure to set up monitoring for a Spec directory causes the directory to +// get ignored and an error to be recorded among the Spec directory errors. +// These errors can be queried using the GetSpecDirErrors() function. If the +// error condition is transient, for instance a missing directory which later +// gets created, the corresponding error will be removed once the condition +// is over. +// +// With auto-refresh enabled injecting any CDI devices can be done without +// an explicit call to Refresh(), using a code snippet similar to the +// following: +// +// In a runtime implementation one typically wants to make sure the +// CDI Spec cache is up to date before performing device injection. +// A code snippet similar to the following accmplishes that: +// +// import ( +// "fmt" +// "strings" +// +// log "github.com/sirupsen/logrus" +// +// "tags.cncf.io/container-device-interface/pkg/cdi" +// oci "github.com/opencontainers/runtime-spec/specs-go" +// ) +// +// func injectCDIDevices(spec *oci.Spec, devices []string) error { +// registry := cdi.GetRegistry() +// +// if err := registry.Refresh(); err != nil { +// // Note: +// // It is up to the implementation to decide whether +// // to abort injection on errors. A failed Refresh() +// // does not necessarily render the registry unusable. +// // For instance, a parse error in a Spec file for +// // vendor A does not have any effect on devices of +// // vendor B... +// log.Warnf("pre-injection Refresh() failed: %v", err) +// } +// +// log.Debug("pristine OCI Spec: %s", dumpSpec(spec)) +// +// unresolved, err := registry.InjectDevices(spec, devices) +// if err != nil { +// return fmt.Errorf("CDI device injection failed: %w", err) +// } +// +// log.Debug("CDI-updated OCI Spec: %s", dumpSpec(spec)) +// return nil +// } +// +// # Generated Spec Files, Multiple Directories, Device Precedence +// +// It is often necessary to generate Spec files dynamically. On some +// systems the available or usable set of CDI devices might change +// dynamically which then needs to be reflected in CDI Specs. For +// some device classes it makes sense to enumerate the available +// devices at every boot and generate Spec file entries for each +// device found. Some CDI devices might need special client- or +// request-specific configuration which can only be fulfilled by +// dynamically generated client-specific entries in transient Spec +// files. +// +// CDI can collect Spec files from multiple directories. Spec files are +// automatically assigned priorities according to which directory they +// were loaded from. The later a directory occurs in the list of CDI +// directories to scan, the higher priority Spec files loaded from that +// directory are assigned to. When two or more Spec files define the +// same device, conflict is resolved by choosing the definition from the +// Spec file with the highest priority. +// +// The default CDI directory configuration is chosen to encourage +// separating dynamically generated CDI Spec files from static ones. +// The default directories are '/etc/cdi' and '/var/run/cdi'. By putting +// dynamically generated Spec files under '/var/run/cdi', those take +// precedence over static ones in '/etc/cdi'. With this scheme, static +// Spec files, typically installed by distro-specific packages, go into +// '/etc/cdi' while all the dynamically generated Spec files, transient +// or other, go into '/var/run/cdi'. +// +// # Spec File Generation +// +// CDI offers two functions for writing and removing dynamically generated +// Specs from CDI Spec directories. These functions, WriteSpec() and +// RemoveSpec() implicitly follow the principle of separating dynamic Specs +// from the rest and therefore always write to and remove Specs from the +// last configured directory. +// +// Corresponding functions are also provided for generating names for Spec +// files. These functions follow a simple naming convention to ensure that +// multiple entities generating Spec files simultaneously on the same host +// do not end up using conflicting Spec file names. GenerateSpecName(), +// GenerateNameForSpec(), GenerateTransientSpecName(), and +// GenerateTransientNameForSpec() all generate names which can be passed +// as such to WriteSpec() and subsequently to RemoveSpec(). +// +// Generating a Spec file for a vendor/device class can be done with a +// code snippet similar to the following: +// +// import ( +// +// "fmt" +// ... +// "tags.cncf.io/container-device-interface/specs-go" +// "tags.cncf.io/container-device-interface/pkg/cdi" +// +// ) +// +// func generateDeviceSpecs() error { +// registry := cdi.GetRegistry() +// spec := &specs.Spec{ +// Version: specs.CurrentVersion, +// Kind: vendor+"/"+class, +// } +// +// for _, dev := range enumerateDevices() { +// spec.Devices = append(spec.Devices, specs.Device{ +// Name: dev.Name, +// ContainerEdits: getContainerEditsForDevice(dev), +// }) +// } +// +// specName, err := cdi.GenerateNameForSpec(spec) +// if err != nil { +// return fmt.Errorf("failed to generate Spec name: %w", err) +// } +// +// return registry.SpecDB().WriteSpec(spec, specName) +// } +// +// Similarly, generating and later cleaning up transient Spec files can be +// done with code fragments similar to the following. These transient Spec +// files are temporary Spec files with container-specific parametrization. +// They are typically created before the associated container is created +// and removed once that container is removed. +// +// import ( +// +// "fmt" +// ... +// "tags.cncf.io/container-device-interface/specs-go" +// "tags.cncf.io/container-device-interface/pkg/cdi" +// +// ) +// +// func generateTransientSpec(ctr Container) error { +// registry := cdi.GetRegistry() +// devices := getContainerDevs(ctr, vendor, class) +// spec := &specs.Spec{ +// Version: specs.CurrentVersion, +// Kind: vendor+"/"+class, +// } +// +// for _, dev := range devices { +// spec.Devices = append(spec.Devices, specs.Device{ +// // the generated name needs to be unique within the +// // vendor/class domain on the host/node. +// Name: generateUniqueDevName(dev, ctr), +// ContainerEdits: getEditsForContainer(dev), +// }) +// } +// +// // transientID is expected to guarantee that the Spec file name +// // generated using is unique within +// // the host/node. If more than one device is allocated with the +// // same vendor/class domain, either all generated Spec entries +// // should go to a single Spec file (like in this sample snippet), +// // or transientID should be unique for each generated Spec file. +// transientID := getSomeSufficientlyUniqueIDForContainer(ctr) +// specName, err := cdi.GenerateNameForTransientSpec(vendor, class, transientID) +// if err != nil { +// return fmt.Errorf("failed to generate Spec name: %w", err) +// } +// +// return registry.SpecDB().WriteSpec(spec, specName) +// } +// +// func removeTransientSpec(ctr Container) error { +// registry := cdi.GetRegistry() +// transientID := getSomeSufficientlyUniqueIDForContainer(ctr) +// specName := cdi.GenerateNameForTransientSpec(vendor, class, transientID) +// +// return registry.SpecDB().RemoveSpec(specName) +// } +// +// # CDI Spec Validation +// +// This package performs both syntactic and semantic validation of CDI +// Spec file data when a Spec file is loaded via the registry or using +// the ReadSpec API function. As part of the semantic verification, the +// Spec file is verified against the CDI Spec JSON validation schema. +// +// If a valid externally provided JSON validation schema is found in +// the filesystem at /etc/cdi/schema/schema.json it is loaded and used +// as the default validation schema. If such a file is not found or +// fails to load, an embedded no-op schema is used. +// +// The used validation schema can also be changed programmatically using +// the SetSchema API convenience function. This function also accepts +// the special "builtin" (BuiltinSchemaName) and "none" (NoneSchemaName) +// schema names which switch the used schema to the in-repo validation +// schema embedded into the binary or the now default no-op schema +// correspondingly. Other names are interpreted as the path to the actual +// validation schema to load and use. +package cdi diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go new file mode 100644 index 00000000..4d62c41f --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/oci.go @@ -0,0 +1,65 @@ +/* +Copyright © 2021 The CDI Authors + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package cdi + +import ( + spec "github.com/opencontainers/runtime-spec/specs-go" +) + +// toOCI returns the opencontainers runtime Spec Hook for this Hook. +func (h *Hook) toOCI() spec.Hook { + return spec.Hook{ + Path: h.Path, + Args: h.Args, + Env: h.Env, + Timeout: h.Timeout, + } +} + +// toOCI returns the opencontainers runtime Spec Mount for this Mount. +func (m *Mount) toOCI() spec.Mount { + return spec.Mount{ + Source: m.HostPath, + Destination: m.ContainerPath, + Options: m.Options, + Type: m.Type, + } +} + +// toOCI returns the opencontainers runtime Spec LinuxDevice for this DeviceNode. +func (d *DeviceNode) toOCI() spec.LinuxDevice { + return spec.LinuxDevice{ + Path: d.Path, + Type: d.Type, + Major: d.Major, + Minor: d.Minor, + FileMode: d.FileMode, + UID: d.UID, + GID: d.GID, + } +} + +// toOCI returns the opencontainers runtime Spec LinuxIntelRdt for this IntelRdt config. +func (i *IntelRdt) toOCI() *spec.LinuxIntelRdt { + return &spec.LinuxIntelRdt{ + ClosID: i.ClosID, + L3CacheSchema: i.L3CacheSchema, + MemBwSchema: i.MemBwSchema, + EnableCMT: i.EnableCMT, + EnableMBM: i.EnableMBM, + } +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/qualified-device.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/qualified-device.go new file mode 100644 index 00000000..0bdfdc16 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/qualified-device.go @@ -0,0 +1,113 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "tags.cncf.io/container-device-interface/pkg/parser" +) + +// QualifiedName returns the qualified name for a device. +// The syntax for a qualified device names is +// +// "/=". +// +// A valid vendor and class name may contain the following runes: +// +// 'A'-'Z', 'a'-'z', '0'-'9', '.', '-', '_'. +// +// A valid device name may contain the following runes: +// +// 'A'-'Z', 'a'-'z', '0'-'9', '-', '_', '.', ':' +// +// Deprecated: use parser.QualifiedName instead +func QualifiedName(vendor, class, name string) string { + return parser.QualifiedName(vendor, class, name) +} + +// IsQualifiedName tests if a device name is qualified. +// +// Deprecated: use parser.IsQualifiedName instead +func IsQualifiedName(device string) bool { + return parser.IsQualifiedName(device) +} + +// ParseQualifiedName splits a qualified name into device vendor, class, +// and name. If the device fails to parse as a qualified name, or if any +// of the split components fail to pass syntax validation, vendor and +// class are returned as empty, together with the verbatim input as the +// name and an error describing the reason for failure. +// +// Deprecated: use parser.ParseQualifiedName instead +func ParseQualifiedName(device string) (string, string, string, error) { + return parser.ParseQualifiedName(device) +} + +// ParseDevice tries to split a device name into vendor, class, and name. +// If this fails, for instance in the case of unqualified device names, +// ParseDevice returns an empty vendor and class together with name set +// to the verbatim input. +// +// Deprecated: use parser.ParseDevice instead +func ParseDevice(device string) (string, string, string) { + return parser.ParseDevice(device) +} + +// ParseQualifier splits a device qualifier into vendor and class. +// The syntax for a device qualifier is +// +// "/" +// +// If parsing fails, an empty vendor and the class set to the +// verbatim input is returned. +// +// Deprecated: use parser.ParseQualifier instead +func ParseQualifier(kind string) (string, string) { + return parser.ParseQualifier(kind) +} + +// ValidateVendorName checks the validity of a vendor name. +// A vendor name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, and dot ('_', '-', and '.') +// +// Deprecated: use parser.ValidateVendorName instead +func ValidateVendorName(vendor string) error { + return parser.ValidateVendorName(vendor) +} + +// ValidateClassName checks the validity of class name. +// A class name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, and dot ('_', '-', and '.') +// +// Deprecated: use parser.ValidateClassName instead +func ValidateClassName(class string) error { + return parser.ValidateClassName(class) +} + +// ValidateDeviceName checks the validity of a device name. +// A device name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, dot, colon ('_', '-', '.', ':') +// +// Deprecated: use parser.ValidateDeviceName instead +func ValidateDeviceName(name string) error { + return parser.ValidateDeviceName(name) +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/registry.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/registry.go new file mode 100644 index 00000000..3113a05a --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/registry.go @@ -0,0 +1,178 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "sync" + + oci "github.com/opencontainers/runtime-spec/specs-go" + cdi "tags.cncf.io/container-device-interface/specs-go" +) + +// Registry keeps a cache of all CDI Specs installed or generated on +// the host. Registry is the primary interface clients should use to +// interact with CDI. +// +// The most commonly used Registry functions are for refreshing the +// registry and injecting CDI devices into an OCI Spec. +// +// Deprecated: Registry is deprecated and will be removed in a future +// version. Please update your code to use the corresponding package- +// level functions Configure(), Refresh(), InjectDevices(), GetErrors(), +// and GetDefaultCache(). +type Registry interface { + RegistryResolver + RegistryRefresher + DeviceDB() RegistryDeviceDB + SpecDB() RegistrySpecDB +} + +// RegistryRefresher is the registry interface for refreshing the +// cache of CDI Specs and devices. +// +// Configure reconfigures the registry with the given options. +// +// Refresh rescans all CDI Spec directories and updates the +// state of the cache to reflect any changes. It returns any +// errors encountered during the refresh. +// +// GetErrors returns all errors encountered for any of the scanned +// Spec files during the last cache refresh. +// +// GetSpecDirectories returns the set up CDI Spec directories +// currently in use. The directories are returned in the scan +// order of Refresh(). +// +// GetSpecDirErrors returns any errors related to the configured +// Spec directories. +// +// Deprecated: RegistryRefresher is deprecated and will be removed +// in a future version. Please use the default cache and its related +// package-level functions instead. +type RegistryRefresher interface { + Configure(...Option) error + Refresh() error + GetErrors() map[string][]error + GetSpecDirectories() []string + GetSpecDirErrors() map[string]error +} + +// RegistryResolver is the registry interface for injecting CDI +// devices into an OCI Spec. +// +// InjectDevices takes an OCI Spec and injects into it a set of +// CDI devices given by qualified name. It returns the names of +// any unresolved devices and an error if injection fails. +// +// Deprecated: RegistryRefresher is deprecated and will be removed +// in a future version. Please use the default cache and its related +// package-level functions instead. +type RegistryResolver interface { + InjectDevices(spec *oci.Spec, device ...string) (unresolved []string, err error) +} + +// RegistryDeviceDB is the registry interface for querying devices. +// +// GetDevice returns the CDI device for the given qualified name. If +// the device is not GetDevice returns nil. +// +// ListDevices returns a slice with the names of qualified device +// known. The returned slice is sorted. +// +// Deprecated: RegistryDeviceDB is deprecated and will be removed +// in a future version. Please use the default cache and its related +// package-level functions instead. +// and will be removed in a future version. Please use the default +// cache and its related package-level functions instead. +type RegistryDeviceDB interface { + GetDevice(device string) *Device + ListDevices() []string +} + +// RegistrySpecDB is the registry interface for querying CDI Specs. +// +// ListVendors returns a slice with all vendors known. The returned +// slice is sorted. +// +// ListClasses returns a slice with all classes known. The returned +// slice is sorted. +// +// GetVendorSpecs returns a slice of all Specs for the vendor. +// +// GetSpecErrors returns any errors for the Spec encountered during +// the last cache refresh. +// +// WriteSpec writes the Spec with the given content and name to the +// last Spec directory. +// +// Deprecated: RegistrySpecDB is deprecated and will be removed +// in a future version. Please use the default cache and its related +// package-level functions instead. +type RegistrySpecDB interface { + ListVendors() []string + ListClasses() []string + GetVendorSpecs(vendor string) []*Spec + GetSpecErrors(*Spec) []error + WriteSpec(raw *cdi.Spec, name string) error + RemoveSpec(name string) error +} + +type registry struct { + *Cache +} + +var _ Registry = ®istry{} + +var ( + reg *registry + initOnce sync.Once +) + +// GetRegistry returns the CDI registry. If any options are given, those +// are applied to the registry. +// +// Deprecated: GetRegistry is deprecated and will be removed in a future +// version. Please use the default cache and its related package-level +// functions instead. +func GetRegistry(options ...Option) Registry { + initOnce.Do(func() { + reg = ®istry{GetDefaultCache()} + }) + if len(options) > 0 { + // We don't care about errors here + _ = reg.Configure(options...) + } + return reg +} + +// DeviceDB returns the registry interface for querying devices. +// +// Deprecated: DeviceDB is deprecated and will be removed in a future +// version. Please use the default cache and its related package-level +// functions instead. +func (r *registry) DeviceDB() RegistryDeviceDB { + return r +} + +// SpecDB returns the registry interface for querying Specs. +// +// Deprecated: SpecDB is deprecated and will be removed in a future +// version. Please use the default cache and its related package-level +// functions instead. +func (r *registry) SpecDB() RegistrySpecDB { + return r +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go new file mode 100644 index 00000000..09005d69 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec-dirs.go @@ -0,0 +1,113 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "errors" + "io/fs" + "os" + "path/filepath" +) + +const ( + // DefaultStaticDir is the default directory for static CDI Specs. + DefaultStaticDir = "/etc/cdi" + // DefaultDynamicDir is the default directory for generated CDI Specs + DefaultDynamicDir = "/var/run/cdi" +) + +var ( + // DefaultSpecDirs is the default Spec directory configuration. + // While altering this variable changes the package defaults, + // the preferred way of overriding the default directories is + // to use a WithSpecDirs options. Otherwise the change is only + // effective if it takes place before creating the Registry or + // other Cache instances. + DefaultSpecDirs = []string{DefaultStaticDir, DefaultDynamicDir} + // ErrStopScan can be returned from a ScanSpecFunc to stop the scan. + ErrStopScan = errors.New("stop Spec scan") +) + +// WithSpecDirs returns an option to override the CDI Spec directories. +func WithSpecDirs(dirs ...string) Option { + return func(c *Cache) { + specDirs := make([]string, len(dirs)) + for i, dir := range dirs { + specDirs[i] = filepath.Clean(dir) + } + c.specDirs = specDirs + } +} + +// scanSpecFunc is a function for processing CDI Spec files. +type scanSpecFunc func(string, int, *Spec, error) error + +// ScanSpecDirs scans the given directories looking for CDI Spec files, +// which are all files with a '.json' or '.yaml' suffix. For every Spec +// file discovered, ScanSpecDirs loads a Spec from the file then calls +// the scan function passing it the path to the file, the priority (the +// index of the directory in the slice of directories given), the Spec +// itself, and any error encountered while loading the Spec. +// +// Scanning stops once all files have been processed or when the scan +// function returns an error. The result of ScanSpecDirs is the error +// returned by the scan function, if any. The special error ErrStopScan +// can be used to terminate the scan gracefully without ScanSpecDirs +// returning an error. ScanSpecDirs silently skips any subdirectories. +func scanSpecDirs(dirs []string, scanFn scanSpecFunc) error { + var ( + spec *Spec + err error + ) + + for priority, dir := range dirs { + err = filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + // for initial stat failure Walk calls us with nil info + if info == nil { + if errors.Is(err, fs.ErrNotExist) { + return nil + } + return err + } + // first call from Walk is for dir itself, others we skip + if info.IsDir() { + if path == dir { + return nil + } + return filepath.SkipDir + } + + // ignore obviously non-Spec files + if ext := filepath.Ext(path); ext != ".json" && ext != ".yaml" { + return nil + } + + if err != nil { + return scanFn(path, priority, nil, err) + } + + spec, err = ReadSpec(path, priority) + return scanFn(path, priority, spec, err) + }) + + if err != nil && err != ErrStopScan { + return err + } + } + + return nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec.go new file mode 100644 index 00000000..1a0a662b --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec.go @@ -0,0 +1,351 @@ +/* + Copyright © 2021 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "strings" + "sync" + + oci "github.com/opencontainers/runtime-spec/specs-go" + "sigs.k8s.io/yaml" + + "tags.cncf.io/container-device-interface/internal/validation" + cdi "tags.cncf.io/container-device-interface/specs-go" +) + +const ( + // defaultSpecExt is the file extension for the default encoding. + defaultSpecExt = ".yaml" +) + +var ( + // Externally set CDI Spec validation function. + specValidator func(*cdi.Spec) error + validatorLock sync.RWMutex +) + +// Spec represents a single CDI Spec. It is usually loaded from a +// file and stored in a cache. The Spec has an associated priority. +// This priority is inherited from the associated priority of the +// CDI Spec directory that contains the CDI Spec file and is used +// to resolve conflicts if multiple CDI Spec files contain entries +// for the same fully qualified device. +type Spec struct { + *cdi.Spec + vendor string + class string + path string + priority int + devices map[string]*Device +} + +// ReadSpec reads the given CDI Spec file. The resulting Spec is +// assigned the given priority. If reading or parsing the Spec +// data fails ReadSpec returns a nil Spec and an error. +func ReadSpec(path string, priority int) (*Spec, error) { + data, err := os.ReadFile(path) + switch { + case os.IsNotExist(err): + return nil, err + case err != nil: + return nil, fmt.Errorf("failed to read CDI Spec %q: %w", path, err) + } + + raw, err := ParseSpec(data) + if err != nil { + return nil, fmt.Errorf("failed to parse CDI Spec %q: %w", path, err) + } + if raw == nil { + return nil, fmt.Errorf("failed to parse CDI Spec %q, no Spec data", path) + } + + spec, err := newSpec(raw, path, priority) + if err != nil { + return nil, err + } + + return spec, nil +} + +// newSpec creates a new Spec from the given CDI Spec data. The +// Spec is marked as loaded from the given path with the given +// priority. If Spec data validation fails newSpec returns a nil +// Spec and an error. +func newSpec(raw *cdi.Spec, path string, priority int) (*Spec, error) { + err := validateSpec(raw) + if err != nil { + return nil, err + } + + spec := &Spec{ + Spec: raw, + path: filepath.Clean(path), + priority: priority, + } + + if ext := filepath.Ext(spec.path); ext != ".yaml" && ext != ".json" { + spec.path += defaultSpecExt + } + + spec.vendor, spec.class = ParseQualifier(spec.Kind) + + if spec.devices, err = spec.validate(); err != nil { + return nil, fmt.Errorf("invalid CDI Spec: %w", err) + } + + return spec, nil +} + +// Write the CDI Spec to the file associated with it during instantiation +// by newSpec() or ReadSpec(). +func (s *Spec) write(overwrite bool) error { + var ( + data []byte + dir string + tmp *os.File + err error + ) + + err = validateSpec(s.Spec) + if err != nil { + return err + } + + if filepath.Ext(s.path) == ".yaml" { + data, err = yaml.Marshal(s.Spec) + data = append([]byte("---\n"), data...) + } else { + data, err = json.Marshal(s.Spec) + } + if err != nil { + return fmt.Errorf("failed to marshal Spec file: %w", err) + } + + dir = filepath.Dir(s.path) + err = os.MkdirAll(dir, 0o755) + if err != nil { + return fmt.Errorf("failed to create Spec dir: %w", err) + } + + tmp, err = os.CreateTemp(dir, "spec.*.tmp") + if err != nil { + return fmt.Errorf("failed to create Spec file: %w", err) + } + _, err = tmp.Write(data) + tmp.Close() + if err != nil { + return fmt.Errorf("failed to write Spec file: %w", err) + } + + err = renameIn(dir, filepath.Base(tmp.Name()), filepath.Base(s.path), overwrite) + + if err != nil { + os.Remove(tmp.Name()) + err = fmt.Errorf("failed to write Spec file: %w", err) + } + + return err +} + +// GetVendor returns the vendor of this Spec. +func (s *Spec) GetVendor() string { + return s.vendor +} + +// GetClass returns the device class of this Spec. +func (s *Spec) GetClass() string { + return s.class +} + +// GetDevice returns the device for the given unqualified name. +func (s *Spec) GetDevice(name string) *Device { + return s.devices[name] +} + +// GetPath returns the filesystem path of this Spec. +func (s *Spec) GetPath() string { + return s.path +} + +// GetPriority returns the priority of this Spec. +func (s *Spec) GetPriority() int { + return s.priority +} + +// ApplyEdits applies the Spec's global-scope container edits to an OCI Spec. +func (s *Spec) ApplyEdits(ociSpec *oci.Spec) error { + return s.edits().Apply(ociSpec) +} + +// edits returns the applicable global container edits for this spec. +func (s *Spec) edits() *ContainerEdits { + return &ContainerEdits{&s.ContainerEdits} +} + +// Validate the Spec. +func (s *Spec) validate() (map[string]*Device, error) { + if err := validateVersion(s.Version); err != nil { + return nil, err + } + + minVersion, err := MinimumRequiredVersion(s.Spec) + if err != nil { + return nil, fmt.Errorf("could not determine minimum required version: %v", err) + } + if newVersion(minVersion).IsGreaterThan(newVersion(s.Version)) { + return nil, fmt.Errorf("the spec version must be at least v%v", minVersion) + } + + if err := ValidateVendorName(s.vendor); err != nil { + return nil, err + } + if err := ValidateClassName(s.class); err != nil { + return nil, err + } + if err := validation.ValidateSpecAnnotations(s.Kind, s.Annotations); err != nil { + return nil, err + } + if err := s.edits().Validate(); err != nil { + return nil, err + } + + devices := make(map[string]*Device) + for _, d := range s.Devices { + dev, err := newDevice(s, d) + if err != nil { + return nil, fmt.Errorf("failed add device %q: %w", d.Name, err) + } + if _, conflict := devices[d.Name]; conflict { + return nil, fmt.Errorf("invalid spec, multiple device %q", d.Name) + } + devices[d.Name] = dev + } + + return devices, nil +} + +// validateVersion checks whether the specified spec version is supported. +func validateVersion(version string) error { + if !validSpecVersions.isValidVersion(version) { + return fmt.Errorf("invalid version %q", version) + } + + return nil +} + +// ParseSpec parses CDI Spec data into a raw CDI Spec. +func ParseSpec(data []byte) (*cdi.Spec, error) { + var raw *cdi.Spec + err := yaml.UnmarshalStrict(data, &raw) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal CDI Spec: %w", err) + } + return raw, nil +} + +// SetSpecValidator sets a CDI Spec validator function. This function +// is used for extra CDI Spec content validation whenever a Spec file +// loaded (using ReadSpec() or written (using WriteSpec()). +func SetSpecValidator(fn func(*cdi.Spec) error) { + validatorLock.Lock() + defer validatorLock.Unlock() + specValidator = fn +} + +// validateSpec validates the Spec using the extneral validator. +func validateSpec(raw *cdi.Spec) error { + validatorLock.RLock() + defer validatorLock.RUnlock() + + if specValidator == nil { + return nil + } + err := specValidator(raw) + if err != nil { + return fmt.Errorf("Spec validation failed: %w", err) + } + return nil +} + +// GenerateSpecName generates a vendor+class scoped Spec file name. The +// name can be passed to WriteSpec() to write a Spec file to the file +// system. +// +// vendor and class should match the vendor and class of the CDI Spec. +// The file name is generated without a ".json" or ".yaml" extension. +// The caller can append the desired extension to choose a particular +// encoding. Otherwise WriteSpec() will use its default encoding. +// +// This function always returns the same name for the same vendor/class +// combination. Therefore it cannot be used as such to generate multiple +// Spec file names for a single vendor and class. +func GenerateSpecName(vendor, class string) string { + return vendor + "-" + class +} + +// GenerateTransientSpecName generates a vendor+class scoped transient +// Spec file name. The name can be passed to WriteSpec() to write a Spec +// file to the file system. +// +// Transient Specs are those whose lifecycle is tied to that of some +// external entity, for instance a container. vendor and class should +// match the vendor and class of the CDI Spec. transientID should be +// unique among all CDI users on the same host that might generate +// transient Spec files using the same vendor/class combination. If +// the external entity to which the lifecycle of the transient Spec +// is tied to has a unique ID of its own, then this is usually a +// good choice for transientID. +// +// The file name is generated without a ".json" or ".yaml" extension. +// The caller can append the desired extension to choose a particular +// encoding. Otherwise WriteSpec() will use its default encoding. +func GenerateTransientSpecName(vendor, class, transientID string) string { + transientID = strings.ReplaceAll(transientID, "/", "_") + return GenerateSpecName(vendor, class) + "_" + transientID +} + +// GenerateNameForSpec generates a name for the given Spec using +// GenerateSpecName with the vendor and class taken from the Spec. +// On success it returns the generated name and a nil error. If +// the Spec does not contain a valid vendor or class, it returns +// an empty name and a non-nil error. +func GenerateNameForSpec(raw *cdi.Spec) (string, error) { + vendor, class := ParseQualifier(raw.Kind) + if vendor == "" { + return "", fmt.Errorf("invalid vendor/class %q in Spec", raw.Kind) + } + + return GenerateSpecName(vendor, class), nil +} + +// GenerateNameForTransientSpec generates a name for the given transient +// Spec using GenerateTransientSpecName with the vendor and class taken +// from the Spec. On success it returns the generated name and a nil error. +// If the Spec does not contain a valid vendor or class, it returns an +// an empty name and a non-nil error. +func GenerateNameForTransientSpec(raw *cdi.Spec, transientID string) (string, error) { + vendor, class := ParseQualifier(raw.Kind) + if vendor == "" { + return "", fmt.Errorf("invalid vendor/class %q in Spec", raw.Kind) + } + + return GenerateTransientSpecName(vendor, class, transientID), nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_linux.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_linux.go new file mode 100644 index 00000000..9ad27392 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_linux.go @@ -0,0 +1,48 @@ +/* + Copyright © 2022 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "fmt" + "os" + + "golang.org/x/sys/unix" +) + +// Rename src to dst, both relative to the directory dir. If dst already exists +// refuse renaming with an error unless overwrite is explicitly asked for. +func renameIn(dir, src, dst string, overwrite bool) error { + var flags uint + + dirf, err := os.Open(dir) + if err != nil { + return fmt.Errorf("rename failed: %w", err) + } + defer dirf.Close() + + if !overwrite { + flags = unix.RENAME_NOREPLACE + } + + dirFd := int(dirf.Fd()) + err = unix.Renameat2(dirFd, src, dirFd, dst, flags) + if err != nil { + return fmt.Errorf("rename failed: %w", err) + } + + return nil +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_other.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_other.go new file mode 100644 index 00000000..285e04e2 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/spec_other.go @@ -0,0 +1,39 @@ +//go:build !linux +// +build !linux + +/* + Copyright © 2022 The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "os" + "path/filepath" +) + +// Rename src to dst, both relative to the directory dir. If dst already exists +// refuse renaming with an error unless overwrite is explicitly asked for. +func renameIn(dir, src, dst string, overwrite bool) error { + src = filepath.Join(dir, src) + dst = filepath.Join(dir, dst) + + _, err := os.Stat(dst) + if err == nil && !overwrite { + return os.ErrExist + } + + return os.Rename(src, dst) +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/cdi/version.go b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/version.go new file mode 100644 index 00000000..9ca91267 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/cdi/version.go @@ -0,0 +1,222 @@ +/* + Copyright © The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package cdi + +import ( + "strings" + + "golang.org/x/mod/semver" + + "tags.cncf.io/container-device-interface/pkg/parser" + cdi "tags.cncf.io/container-device-interface/specs-go" +) + +const ( + // CurrentVersion is the current version of the CDI Spec. + CurrentVersion = cdi.CurrentVersion + + // vCurrent is the current version as a semver-comparable type + vCurrent version = "v" + CurrentVersion + + // These represent the released versions of the CDI specification + v010 version = "v0.1.0" + v020 version = "v0.2.0" + v030 version = "v0.3.0" + v040 version = "v0.4.0" + v050 version = "v0.5.0" + v060 version = "v0.6.0" + v070 version = "v0.7.0" + v080 version = "v0.8.0" + + // vEarliest is the earliest supported version of the CDI specification + vEarliest version = v030 +) + +// validSpecVersions stores a map of spec versions to functions to check the required versions. +// Adding new fields / spec versions requires that a `requiredFunc` be implemented and +// this map be updated. +var validSpecVersions = requiredVersionMap{ + v010: nil, + v020: nil, + v030: nil, + v040: requiresV040, + v050: requiresV050, + v060: requiresV060, + v070: requiresV070, + v080: requiresV080, +} + +// MinimumRequiredVersion determines the minimum spec version for the input spec. +func MinimumRequiredVersion(spec *cdi.Spec) (string, error) { + minVersion := validSpecVersions.requiredVersion(spec) + return minVersion.String(), nil +} + +// version represents a semantic version string +type version string + +// newVersion creates a version that can be used for semantic version comparisons. +func newVersion(v string) version { + return version("v" + strings.TrimPrefix(v, "v")) +} + +// String returns the string representation of the version. +// This trims a leading v if present. +func (v version) String() string { + return strings.TrimPrefix(string(v), "v") +} + +// IsGreaterThan checks with a version is greater than the specified version. +func (v version) IsGreaterThan(o version) bool { + return semver.Compare(string(v), string(o)) > 0 +} + +// IsLatest checks whether the version is the latest supported version +func (v version) IsLatest() bool { + return v == vCurrent +} + +type requiredFunc func(*cdi.Spec) bool + +type requiredVersionMap map[version]requiredFunc + +// isValidVersion checks whether the specified version is valid. +// A version is valid if it is contained in the required version map. +func (r requiredVersionMap) isValidVersion(specVersion string) bool { + _, ok := validSpecVersions[newVersion(specVersion)] + + return ok +} + +// requiredVersion returns the minimum version required for the given spec +func (r requiredVersionMap) requiredVersion(spec *cdi.Spec) version { + minVersion := vEarliest + + for v, isRequired := range validSpecVersions { + if isRequired == nil { + continue + } + if isRequired(spec) && v.IsGreaterThan(minVersion) { + minVersion = v + } + // If we have already detected the latest version then no later version could be detected + if minVersion.IsLatest() { + break + } + } + + return minVersion +} + +// requiresV080 returns true if the spec uses v0.8.0 features. +// Since the v0.8.0 spec bump was due to the removed .ToOCI functions on the +// spec types, there are explicit spec changes. +func requiresV080(_ *cdi.Spec) bool { + return false +} + +// requiresV070 returns true if the spec uses v0.7.0 features +func requiresV070(spec *cdi.Spec) bool { + if spec.ContainerEdits.IntelRdt != nil { + return true + } + // The v0.7.0 spec allows additional GIDs to be specified at a spec level. + if len(spec.ContainerEdits.AdditionalGIDs) > 0 { + return true + } + + for _, d := range spec.Devices { + if d.ContainerEdits.IntelRdt != nil { + return true + } + // The v0.7.0 spec allows additional GIDs to be specified at a device level. + if len(d.ContainerEdits.AdditionalGIDs) > 0 { + return true + } + } + + return false +} + +// requiresV060 returns true if the spec uses v0.6.0 features +func requiresV060(spec *cdi.Spec) bool { + // The v0.6.0 spec allows annotations to be specified at a spec level + for range spec.Annotations { + return true + } + + // The v0.6.0 spec allows annotations to be specified at a device level + for _, d := range spec.Devices { + for range d.Annotations { + return true + } + } + + // The v0.6.0 spec allows dots "." in Kind name label (class) + vendor, class := parser.ParseQualifier(spec.Kind) + if vendor != "" { + if strings.ContainsRune(class, '.') { + return true + } + } + + return false +} + +// requiresV050 returns true if the spec uses v0.5.0 features +func requiresV050(spec *cdi.Spec) bool { + var edits []*cdi.ContainerEdits + + for _, d := range spec.Devices { + // The v0.5.0 spec allowed device names to start with a digit instead of requiring a letter + if len(d.Name) > 0 && !parser.IsLetter(rune(d.Name[0])) { + return true + } + edits = append(edits, &d.ContainerEdits) + } + + edits = append(edits, &spec.ContainerEdits) + for _, e := range edits { + for _, dn := range e.DeviceNodes { + // The HostPath field was added in v0.5.0 + if dn.HostPath != "" { + return true + } + } + } + return false +} + +// requiresV040 returns true if the spec uses v0.4.0 features +func requiresV040(spec *cdi.Spec) bool { + var edits []*cdi.ContainerEdits + + for _, d := range spec.Devices { + edits = append(edits, &d.ContainerEdits) + } + + edits = append(edits, &spec.ContainerEdits) + for _, e := range edits { + for _, m := range e.Mounts { + // The Type field was added in v0.4.0 + if m.Type != "" { + return true + } + } + } + return false +} diff --git a/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go b/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go new file mode 100644 index 00000000..53259895 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/pkg/parser/parser.go @@ -0,0 +1,212 @@ +/* + Copyright © The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package parser + +import ( + "fmt" + "strings" +) + +// QualifiedName returns the qualified name for a device. +// The syntax for a qualified device names is +// +// "/=". +// +// A valid vendor and class name may contain the following runes: +// +// 'A'-'Z', 'a'-'z', '0'-'9', '.', '-', '_'. +// +// A valid device name may contain the following runes: +// +// 'A'-'Z', 'a'-'z', '0'-'9', '-', '_', '.', ':' +func QualifiedName(vendor, class, name string) string { + return vendor + "/" + class + "=" + name +} + +// IsQualifiedName tests if a device name is qualified. +func IsQualifiedName(device string) bool { + _, _, _, err := ParseQualifiedName(device) + return err == nil +} + +// ParseQualifiedName splits a qualified name into device vendor, class, +// and name. If the device fails to parse as a qualified name, or if any +// of the split components fail to pass syntax validation, vendor and +// class are returned as empty, together with the verbatim input as the +// name and an error describing the reason for failure. +func ParseQualifiedName(device string) (string, string, string, error) { + vendor, class, name := ParseDevice(device) + + if vendor == "" { + return "", "", device, fmt.Errorf("unqualified device %q, missing vendor", device) + } + if class == "" { + return "", "", device, fmt.Errorf("unqualified device %q, missing class", device) + } + if name == "" { + return "", "", device, fmt.Errorf("unqualified device %q, missing device name", device) + } + + if err := ValidateVendorName(vendor); err != nil { + return "", "", device, fmt.Errorf("invalid device %q: %w", device, err) + } + if err := ValidateClassName(class); err != nil { + return "", "", device, fmt.Errorf("invalid device %q: %w", device, err) + } + if err := ValidateDeviceName(name); err != nil { + return "", "", device, fmt.Errorf("invalid device %q: %w", device, err) + } + + return vendor, class, name, nil +} + +// ParseDevice tries to split a device name into vendor, class, and name. +// If this fails, for instance in the case of unqualified device names, +// ParseDevice returns an empty vendor and class together with name set +// to the verbatim input. +func ParseDevice(device string) (string, string, string) { + if device == "" || device[0] == '/' { + return "", "", device + } + + parts := strings.SplitN(device, "=", 2) + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", "", device + } + + name := parts[1] + vendor, class := ParseQualifier(parts[0]) + if vendor == "" { + return "", "", device + } + + return vendor, class, name +} + +// ParseQualifier splits a device qualifier into vendor and class. +// The syntax for a device qualifier is +// +// "/" +// +// If parsing fails, an empty vendor and the class set to the +// verbatim input is returned. +func ParseQualifier(kind string) (string, string) { + parts := strings.SplitN(kind, "/", 2) + if len(parts) != 2 || parts[0] == "" || parts[1] == "" { + return "", kind + } + return parts[0], parts[1] +} + +// ValidateVendorName checks the validity of a vendor name. +// A vendor name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, and dot ('_', '-', and '.') +func ValidateVendorName(vendor string) error { + err := validateVendorOrClassName(vendor) + if err != nil { + err = fmt.Errorf("invalid vendor. %w", err) + } + return err +} + +// ValidateClassName checks the validity of class name. +// A class name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, and dot ('_', '-', and '.') +func ValidateClassName(class string) error { + err := validateVendorOrClassName(class) + if err != nil { + err = fmt.Errorf("invalid class. %w", err) + } + return err +} + +// validateVendorOrClassName checks the validity of vendor or class name. +// A name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, and dot ('_', '-', and '.') +func validateVendorOrClassName(name string) error { + if name == "" { + return fmt.Errorf("empty name") + } + if !IsLetter(rune(name[0])) { + return fmt.Errorf("%q, should start with letter", name) + } + for _, c := range string(name[1 : len(name)-1]) { + switch { + case IsAlphaNumeric(c): + case c == '_' || c == '-' || c == '.': + default: + return fmt.Errorf("invalid character '%c' in name %q", + c, name) + } + } + if !IsAlphaNumeric(rune(name[len(name)-1])) { + return fmt.Errorf("%q, should end with a letter or digit", name) + } + + return nil +} + +// ValidateDeviceName checks the validity of a device name. +// A device name may contain the following ASCII characters: +// - upper- and lowercase letters ('A'-'Z', 'a'-'z') +// - digits ('0'-'9') +// - underscore, dash, dot, colon ('_', '-', '.', ':') +func ValidateDeviceName(name string) error { + if name == "" { + return fmt.Errorf("invalid (empty) device name") + } + if !IsAlphaNumeric(rune(name[0])) { + return fmt.Errorf("invalid class %q, should start with a letter or digit", name) + } + if len(name) == 1 { + return nil + } + for _, c := range string(name[1 : len(name)-1]) { + switch { + case IsAlphaNumeric(c): + case c == '_' || c == '-' || c == '.' || c == ':': + default: + return fmt.Errorf("invalid character '%c' in device name %q", + c, name) + } + } + if !IsAlphaNumeric(rune(name[len(name)-1])) { + return fmt.Errorf("invalid name %q, should end with a letter or digit", name) + } + return nil +} + +// IsLetter reports whether the rune is a letter. +func IsLetter(c rune) bool { + return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z') +} + +// IsDigit reports whether the rune is a digit. +func IsDigit(c rune) bool { + return '0' <= c && c <= '9' +} + +// IsAlphaNumeric reports whether the rune is a letter or digit. +func IsAlphaNumeric(c rune) bool { + return IsLetter(c) || IsDigit(c) +} diff --git a/vendor/tags.cncf.io/container-device-interface/specs-go/LICENSE b/vendor/tags.cncf.io/container-device-interface/specs-go/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/specs-go/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/vendor/tags.cncf.io/container-device-interface/specs-go/config.go b/vendor/tags.cncf.io/container-device-interface/specs-go/config.go new file mode 100644 index 00000000..f28657b8 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/specs-go/config.go @@ -0,0 +1,72 @@ +package specs + +import "os" + +// Spec is the base configuration for CDI +type Spec struct { + Version string `json:"cdiVersion" yaml:"cdiVersion"` + Kind string `json:"kind" yaml:"kind"` + // Annotations add meta information per CDI spec. Note these are CDI-specific and do not affect container metadata. + // Added in v0.6.0. + Annotations map[string]string `json:"annotations,omitempty" yaml:"annotations,omitempty"` + Devices []Device `json:"devices" yaml:"devices"` + ContainerEdits ContainerEdits `json:"containerEdits,omitempty" yaml:"containerEdits,omitempty"` +} + +// Device is a "Device" a container runtime can add to a container +type Device struct { + Name string `json:"name" yaml:"name"` + // Annotations add meta information per device. Note these are CDI-specific and do not affect container metadata. + // Added in v0.6.0. + Annotations map[string]string `json:"annotations,omitempty" yaml:"annotations,omitempty"` + ContainerEdits ContainerEdits `json:"containerEdits" yaml:"containerEdits"` +} + +// ContainerEdits are edits a container runtime must make to the OCI spec to expose the device. +type ContainerEdits struct { + Env []string `json:"env,omitempty" yaml:"env,omitempty"` + DeviceNodes []*DeviceNode `json:"deviceNodes,omitempty" yaml:"deviceNodes,omitempty"` + Hooks []*Hook `json:"hooks,omitempty" yaml:"hooks,omitempty"` + Mounts []*Mount `json:"mounts,omitempty" yaml:"mounts,omitempty"` + IntelRdt *IntelRdt `json:"intelRdt,omitempty" yaml:"intelRdt,omitempty"` // Added in v0.7.0 + AdditionalGIDs []uint32 `json:"additionalGids,omitempty" yaml:"additionalGids,omitempty"` // Added in v0.7.0 +} + +// DeviceNode represents a device node that needs to be added to the OCI spec. +type DeviceNode struct { + Path string `json:"path" yaml:"path"` + HostPath string `json:"hostPath,omitempty" yaml:"hostPath,omitempty"` // Added in v0.5.0 + Type string `json:"type,omitempty" yaml:"type,omitempty"` + Major int64 `json:"major,omitempty" yaml:"major,omitempty"` + Minor int64 `json:"minor,omitempty" yaml:"minor,omitempty"` + FileMode *os.FileMode `json:"fileMode,omitempty" yaml:"fileMode,omitempty"` + Permissions string `json:"permissions,omitempty" yaml:"permissions,omitempty"` + UID *uint32 `json:"uid,omitempty" yaml:"uid,omitempty"` + GID *uint32 `json:"gid,omitempty" yaml:"gid,omitempty"` +} + +// Mount represents a mount that needs to be added to the OCI spec. +type Mount struct { + HostPath string `json:"hostPath" yaml:"hostPath"` + ContainerPath string `json:"containerPath" yaml:"containerPath"` + Options []string `json:"options,omitempty" yaml:"options,omitempty"` + Type string `json:"type,omitempty" yaml:"type,omitempty"` // Added in v0.4.0 +} + +// Hook represents a hook that needs to be added to the OCI spec. +type Hook struct { + HookName string `json:"hookName" yaml:"hookName"` + Path string `json:"path" yaml:"path"` + Args []string `json:"args,omitempty" yaml:"args,omitempty"` + Env []string `json:"env,omitempty" yaml:"env,omitempty"` + Timeout *int `json:"timeout,omitempty" yaml:"timeout,omitempty"` +} + +// IntelRdt describes the Linux IntelRdt parameters to set in the OCI spec. +type IntelRdt struct { + ClosID string `json:"closID,omitempty" yaml:"closID,omitempty"` + L3CacheSchema string `json:"l3CacheSchema,omitempty" yaml:"l3CacheSchema,omitempty"` + MemBwSchema string `json:"memBwSchema,omitempty" yaml:"memBwSchema,omitempty"` + EnableCMT bool `json:"enableCMT,omitempty" yaml:"enableCMT,omitempty"` + EnableMBM bool `json:"enableMBM,omitempty" yaml:"enableMBM,omitempty"` +} diff --git a/vendor/tags.cncf.io/container-device-interface/specs-go/version.go b/vendor/tags.cncf.io/container-device-interface/specs-go/version.go new file mode 100644 index 00000000..002e0350 --- /dev/null +++ b/vendor/tags.cncf.io/container-device-interface/specs-go/version.go @@ -0,0 +1,244 @@ +/* + Copyright © The CDI Authors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +*/ + +package specs + +import ( + "fmt" + "strings" + + "golang.org/x/mod/semver" +) + +const ( + // CurrentVersion is the current version of the Spec. + CurrentVersion = "1.0.0" + + // vCurrent is the current version as a semver-comparable type + vCurrent version = "v" + CurrentVersion + + // These represent the released versions of the CDI specification + v010 version = "v0.1.0" + v020 version = "v0.2.0" + v030 version = "v0.3.0" + v040 version = "v0.4.0" + v050 version = "v0.5.0" + v060 version = "v0.6.0" + v070 version = "v0.7.0" + v080 version = "v0.8.0" + v100 version = "v1.0.0" + + // vEarliest is the earliest supported version of the CDI specification + vEarliest version = v030 +) + +// validSpecVersions stores a map of spec versions to functions to check the required versions. +// Adding new fields / spec versions requires that a `requiredFunc` be implemented and +// this map be updated. +var validSpecVersions = requiredVersionMap{ + v010: nil, + v020: nil, + v030: nil, + v040: requiresV040, + v050: requiresV050, + v060: requiresV060, + v070: requiresV070, + v080: requiresV080, + v100: requiresV100, +} + +// ValidateVersion checks whether the specified spec version is valid. +// In addition to checking whether the spec version is in the set of known versions, +// the spec is inspected to determine whether the features used are available in specified +// version. +func ValidateVersion(spec *Spec) error { + if !validSpecVersions.isValidVersion(spec.Version) { + return fmt.Errorf("invalid version %q", spec.Version) + } + minVersion, err := MinimumRequiredVersion(spec) + if err != nil { + return fmt.Errorf("could not determine minimum required version: %w", err) + } + if newVersion(minVersion).isGreaterThan(newVersion(spec.Version)) { + return fmt.Errorf("the spec version must be at least v%v", minVersion) + } + return nil +} + +// MinimumRequiredVersion determines the minimum spec version for the input spec. +func MinimumRequiredVersion(spec *Spec) (string, error) { + minVersion := validSpecVersions.requiredVersion(spec) + return minVersion.String(), nil +} + +// version represents a semantic version string +type version string + +// newVersion creates a version that can be used for semantic version comparisons. +func newVersion(v string) version { + return version("v" + strings.TrimPrefix(v, "v")) +} + +// String returns the string representation of the version. +// This trims a leading v if present. +func (v version) String() string { + return strings.TrimPrefix(string(v), "v") +} + +// isGreaterThan checks with a version is greater than the specified version. +func (v version) isGreaterThan(o version) bool { + return semver.Compare(string(v), string(o)) > 0 +} + +// isLatest checks whether the version is the latest supported version +func (v version) isLatest() bool { + return v == vCurrent +} + +type requiredFunc func(*Spec) bool + +type requiredVersionMap map[version]requiredFunc + +// isValidVersion checks whether the specified version is valid. +// A version is valid if it is contained in the required version map. +func (r requiredVersionMap) isValidVersion(specVersion string) bool { + _, ok := validSpecVersions[newVersion(specVersion)] + + return ok +} + +// requiredVersion returns the minimum version required for the given spec +func (r requiredVersionMap) requiredVersion(spec *Spec) version { + minVersion := vEarliest + + for v, isRequired := range validSpecVersions { + if isRequired == nil { + continue + } + if isRequired(spec) && v.isGreaterThan(minVersion) { + minVersion = v + } + // If we have already detected the latest version then no later version could be detected + if minVersion.isLatest() { + break + } + } + + return minVersion +} + +// requiresV100 returns true if the spec uses v1.0.0 features. +// Since the v1.0.0 spec bump was due to moving the minimum version checks to +// the spec package, there are no explicit spec changes. +func requiresV100(_ *Spec) bool { + return false +} + +// requiresV080 returns true if the spec uses v0.8.0 features. +// Since the v0.8.0 spec bump was due to the removed .ToOCI functions on the +// spec types, there are no explicit spec changes. +func requiresV080(_ *Spec) bool { + return false +} + +// requiresV070 returns true if the spec uses v0.7.0 features +func requiresV070(spec *Spec) bool { + if spec.ContainerEdits.IntelRdt != nil { + return true + } + // The v0.7.0 spec allows additional GIDs to be specified at a spec level. + if len(spec.ContainerEdits.AdditionalGIDs) > 0 { + return true + } + + for _, d := range spec.Devices { + if d.ContainerEdits.IntelRdt != nil { + return true + } + // The v0.7.0 spec allows additional GIDs to be specified at a device level. + if len(d.ContainerEdits.AdditionalGIDs) > 0 { + return true + } + } + + return false +} + +// requiresV060 returns true if the spec uses v0.6.0 features +func requiresV060(spec *Spec) bool { + // The v0.6.0 spec allows annotations to be specified at a spec level + for range spec.Annotations { + return true + } + + // The v0.6.0 spec allows annotations to be specified at a device level + for _, d := range spec.Devices { + for range d.Annotations { + return true + } + } + + // The v0.6.0 spec allows dots "." in Kind name label (class) + if !strings.Contains(spec.Kind, "/") { + return false + } + class := strings.SplitN(spec.Kind, "/", 2)[1] + return strings.Contains(class, ".") +} + +// requiresV050 returns true if the spec uses v0.5.0 features +func requiresV050(spec *Spec) bool { + var edits []*ContainerEdits + + for _, d := range spec.Devices { + // The v0.5.0 spec allowed device name to start with a digit + if len(d.Name) > 0 && '0' <= d.Name[0] && d.Name[0] <= '9' { + return true + } + edits = append(edits, &d.ContainerEdits) + } + + edits = append(edits, &spec.ContainerEdits) + for _, e := range edits { + for _, dn := range e.DeviceNodes { + // The HostPath field was added in v0.5.0 + if dn.HostPath != "" { + return true + } + } + } + return false +} + +// requiresV040 returns true if the spec uses v0.4.0 features +func requiresV040(spec *Spec) bool { + var edits []*ContainerEdits + + for _, d := range spec.Devices { + edits = append(edits, &d.ContainerEdits) + } + + edits = append(edits, &spec.ContainerEdits) + for _, e := range edits { + for _, m := range e.Mounts { + // The Type field was added in v0.4.0 + if m.Type != "" { + return true + } + } + } + return false +}