File: gpu.go

package info (click to toggle)
incus 6.0.5-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,788 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (601 lines) | stat: -rw-r--r-- 15,473 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
//go:build linux

package resources

import (
	"bufio"
	"encoding/csv"
	"errors"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path/filepath"
	"slices"
	"strconv"
	"strings"

	"github.com/jaypipes/pcidb"
	"golang.org/x/sys/unix"

	"github.com/lxc/incus/v6/shared/api"
)

var (
	sysClassDrm      = "/sys/class/drm"
	procDriverNvidia = "/proc/driver/nvidia"
)

func loadNvidiaProc() (map[string]*api.ResourcesGPUCardNvidia, error) {
	nvidiaCards := map[string]*api.ResourcesGPUCardNvidia{}

	gpusPath := filepath.Join(procDriverNvidia, "gpus")
	if !sysfsExists(gpusPath) {
		return nil, errors.New("No NVIDIA GPU proc driver")
	}

	// List the GPUs from /proc
	entries, err := os.ReadDir(gpusPath)
	if err != nil {
		return nil, fmt.Errorf("Failed to list %q: %w", gpusPath, err)
	}

	for _, entry := range entries {
		entryName := entry.Name()
		entryPath := filepath.Join(gpusPath, entryName)

		if !sysfsExists(filepath.Join(entryPath, "information")) {
			continue
		}

		// Get the GPU information
		f, err := os.Open(filepath.Join(entryPath, "information"))
		if err != nil {
			return nil, fmt.Errorf("Failed to open %q: %w", filepath.Join(entryPath, "information"), err)
		}

		gpuInfo := bufio.NewScanner(f)
		nvidiaCard := &api.ResourcesGPUCardNvidia{}
		for gpuInfo.Scan() {
			line := strings.TrimSpace(gpuInfo.Text())

			fields := strings.SplitN(line, ":", 2)
			if len(fields) != 2 {
				continue
			}

			key := strings.TrimSpace(fields[0])
			value := strings.TrimSpace(fields[1])

			if key == "Model" {
				nvidiaCard.Model = value
				nvidiaCard.Brand = strings.Split(value, " ")[0]
			}

			if key == "Device Minor" {
				nvidiaCard.CardName = fmt.Sprintf("nvidia%s", value)
				nvidiaCard.CardDevice = fmt.Sprintf("195:%s", value)
			}
		}

		err = f.Close()
		if err != nil {
			return nil, fmt.Errorf("Failed to close %q: %w", filepath.Join(entryPath, "information"), err)
		}

		nvidiaCards[entryName] = nvidiaCard
	}

	return nvidiaCards, nil
}

func loadNvidiaContainer() (map[string]*api.ResourcesGPUCardNvidia, error) {
	// Check for nvidia-container-cli
	_, err := exec.LookPath("nvidia-container-cli")
	if err != nil {
		return nil, fmt.Errorf("Failed to locate nvidia-container-cli: %w", err)
	}

	// Prepare nvidia-container-cli call
	cmd := exec.Command("nvidia-container-cli", "info", "--csv")
	outPipe, err := cmd.StdoutPipe()
	if err != nil {
		return nil, fmt.Errorf("Failed to setup PIPE for nvidia-container-cli: %w", err)
	}

	// Run the command
	err = cmd.Start()
	if err != nil {
		return nil, fmt.Errorf("Failed to start nvidia-container-cli: %w", err)
	}

	// Parse the data
	r := csv.NewReader(outPipe)
	r.FieldsPerRecord = -1

	nvidiaCards := map[string]*api.ResourcesGPUCardNvidia{}
	nvidiaNVRM := ""
	nvidiaCUDA := ""

	line := 0
	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}

		line++

		if err != nil {
			continue
		}

		if line == 2 && len(record) >= 2 {
			nvidiaNVRM = record[0]
			nvidiaCUDA = record[1]
		} else if line >= 4 {
			nvidiaCards[record[5]] = &api.ResourcesGPUCardNvidia{
				NVRMVersion:  nvidiaNVRM,
				CUDAVersion:  nvidiaCUDA,
				Brand:        record[3],
				Model:        record[2],
				UUID:         record[4],
				Architecture: record[6],
				CardName:     fmt.Sprintf("nvidia%s", record[1]),
				CardDevice:   fmt.Sprintf("195:%s", record[1]),
			}
		}
	}

	// wait for nvidia-container-cli
	err = cmd.Wait()
	if err != nil {
		return nil, fmt.Errorf("nvidia-container-cli failed: %w", err)
	}

	return nvidiaCards, nil
}

func gpuAddDeviceInfo(devicePath string, nvidiaCards map[string]*api.ResourcesGPUCardNvidia, pciDB *pcidb.PCIDB, uname unix.Utsname, card *api.ResourcesGPUCard) error {
	// Handle nested devices.
	if isDir(filepath.Join(devicePath, "device")) {
		return gpuAddDeviceInfo(filepath.Join(devicePath, "device"), nvidiaCards, pciDB, uname, card)
	}

	// SRIOV
	if sysfsExists(filepath.Join(devicePath, "sriov_numvfs")) {
		sriov := api.ResourcesGPUCardSRIOV{}

		// Get maximum and current VF count
		vfMaximum, err := readUint(filepath.Join(devicePath, "sriov_totalvfs"))
		if err != nil {
			return fmt.Errorf("Failed to read %q: %w", filepath.Join(devicePath, "sriov_totalvfs"), err)
		}

		vfCurrent, err := readUint(filepath.Join(devicePath, "sriov_numvfs"))
		if err != nil {
			return fmt.Errorf("Failed to read %q: %w", filepath.Join(devicePath, "sriov_numvfs"), err)
		}

		sriov.MaximumVFs = vfMaximum
		sriov.CurrentVFs = vfCurrent

		// Add the SRIOV data to the card
		card.SRIOV = &sriov
	}

	// NUMA node
	if sysfsExists(filepath.Join(devicePath, "numa_node")) {
		numaNode, err := readInt(filepath.Join(devicePath, "numa_node"))
		if err != nil {
			return fmt.Errorf("Failed to read %q: %w", filepath.Join(devicePath, "numa_node"), err)
		}

		if numaNode > 0 {
			card.NUMANode = uint64(numaNode)
		}
	}

	deviceUSBPath := filepath.Join(devicePath, "device", "busnum")
	if sysfsExists(deviceUSBPath) {
		// USB address
		deviceDevicePath := filepath.Join(devicePath, "device")
		usbAddr, err := usbAddress(deviceDevicePath)
		if err != nil {
			return fmt.Errorf("Failed to find USB address for %q: %w", devicePath, err)
		}

		if usbAddr != "" {
			card.USBAddress = usbAddr
		}
	} else {
		// Vendor and product
		deviceVendorPath := filepath.Join(devicePath, "vendor")
		if sysfsExists(deviceVendorPath) {
			id, err := os.ReadFile(deviceVendorPath)
			if err != nil {
				return fmt.Errorf("Failed to read %q: %w", deviceVendorPath, err)
			}

			card.VendorID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
		}

		deviceDevicePath := filepath.Join(devicePath, "device")
		if sysfsExists(deviceDevicePath) {
			id, err := os.ReadFile(deviceDevicePath)
			if err != nil {
				return fmt.Errorf("Failed to read %q: %w", deviceDevicePath, err)
			}

			card.ProductID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
		}

		// Fill vendor and product names
		if pciDB != nil {
			vendor, ok := pciDB.Vendors[card.VendorID]
			if ok {
				card.Vendor = vendor.Name

				for _, product := range vendor.Products {
					if product.ID == card.ProductID {
						card.Product = product.Name
						break
					}
				}
			}
		}
	}

	// Driver information
	driverPath := filepath.Join(devicePath, "driver")
	if sysfsExists(driverPath) {
		linkTarget, err := filepath.EvalSymlinks(driverPath)
		if err != nil {
			return fmt.Errorf("Failed to find %q: %w", driverPath, err)
		}

		// Set the driver name
		card.Driver = filepath.Base(linkTarget)

		// Try to get the version, fallback to kernel version
		out, err := os.ReadFile(filepath.Join(driverPath, "module", "version"))
		if err == nil {
			card.DriverVersion = strings.TrimSpace(string(out))
		} else {
			card.DriverVersion = strings.TrimRight(string(uname.Release[:]), "\x00")
		}
	}

	// NVIDIA specific stuff
	if card.Driver == "nvidia" && card.PCIAddress != "" {
		nvidia, ok := nvidiaCards[card.PCIAddress]
		if ok {
			card.Nvidia = nvidia
		} else {
			nvidia, ok := nvidiaCards[fmt.Sprintf("0000%s", card.PCIAddress)]
			if ok {
				card.Nvidia = nvidia
			}
		}
	}

	// DRM information
	drmPath := filepath.Join(devicePath, "drm")
	if sysfsExists(drmPath) {
		drm := api.ResourcesGPUCardDRM{}

		// List all the devices
		entries, err := os.ReadDir(drmPath)
		if err != nil {
			return fmt.Errorf("Failed to list %q: %w", drmPath, err)
		}

		// Fill in the struct
		for _, entry := range entries {
			entryName := entry.Name()
			entryPath := filepath.Join(drmPath, entryName)

			after, ok := strings.CutPrefix(entryName, "card")
			if ok {
				// Get the card ID
				idStr := after
				id, err := strconv.ParseUint(idStr, 10, 64)
				if err != nil {
					return fmt.Errorf("Failed to parse card number: %w", err)
				}

				dev, err := os.ReadFile(filepath.Join(entryPath, "dev"))
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", filepath.Join(entryPath, "dev"), err)
				}

				drm.ID = id
				drm.CardName = entryName
				drm.CardDevice = strings.TrimSpace(string(dev))
			}

			if strings.HasPrefix(entryName, "controlD") {
				dev, err := os.ReadFile(filepath.Join(entryPath, "dev"))
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", filepath.Join(entryPath, "dev"), err)
				}

				drm.ControlName = entryName
				drm.ControlDevice = strings.TrimSpace(string(dev))
			}

			if strings.HasPrefix(entryName, "renderD") {
				dev, err := os.ReadFile(filepath.Join(entryPath, "dev"))
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", filepath.Join(entryPath, "dev"), err)
				}

				drm.RenderName = entryName
				drm.RenderDevice = strings.TrimSpace(string(dev))
			}
		}

		card.DRM = &drm
	}

	// DRM information
	mdevPath := filepath.Join(devicePath, "mdev_supported_types")
	if sysfsExists(mdevPath) {
		card.Mdev = map[string]api.ResourcesGPUCardMdev{}

		// List all the devices
		entries, err := os.ReadDir(mdevPath)
		if err != nil {
			return fmt.Errorf("Failed to list %q: %w", mdevPath, err)
		}

		// Fill in the struct
		for _, entry := range entries {
			mdev := api.ResourcesGPUCardMdev{}
			entryName := entry.Name()
			entryPath := filepath.Join(mdevPath, entryName)

			// API
			apiPath := filepath.Join(entryPath, "device_api")
			if sysfsExists(apiPath) {
				deviceAPI, err := os.ReadFile(apiPath)
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", apiPath, err)
				}

				mdev.API = strings.TrimSpace(string(deviceAPI))
			}

			// Available
			availablePath := filepath.Join(entryPath, "available_instances")
			if sysfsExists(availablePath) {
				available, err := readUint(availablePath)
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", availablePath, err)
				}

				mdev.Available = available
			}

			// Description
			descriptionPath := filepath.Join(entryPath, "description")
			if sysfsExists(descriptionPath) {
				description, err := os.ReadFile(descriptionPath)
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", descriptionPath, err)
				}

				mdev.Description = strings.TrimSpace(string(description))
			}

			// Devices
			mdevDevicesPath := filepath.Join(entryPath, "devices")
			if sysfsExists(mdevDevicesPath) {
				devs, err := os.ReadDir(mdevDevicesPath)
				if err != nil {
					return fmt.Errorf("Failed to list %q: %w", mdevDevicesPath, err)
				}

				mdev.Devices = []string{}
				for _, dev := range devs {
					mdev.Devices = append(mdev.Devices, dev.Name())
				}
			}

			// Name
			namePath := filepath.Join(entryPath, "name")
			if sysfsExists(namePath) {
				name, err := os.ReadFile(namePath)
				if err != nil {
					return fmt.Errorf("Failed to read %q: %w", namePath, err)
				}

				mdev.Name = strings.TrimSpace(string(name))
			}

			card.Mdev[entryName] = mdev
		}
	}

	return nil
}

// GetGPU returns a filled api.ResourcesGPU struct ready for use by Incus.
func GetGPU() (*api.ResourcesGPU, error) {
	gpu := api.ResourcesGPU{}
	gpu.Cards = []api.ResourcesGPUCard{}

	// Get uname for driver version
	uname := unix.Utsname{}
	err := unix.Uname(&uname)
	if err != nil {
		return nil, fmt.Errorf("Failed to get uname: %w", err)
	}

	// Load PCI database
	pciDB, err := pcidb.New()
	if err != nil {
		pciDB = nil
	}

	// Load NVIDIA information
	nvidiaCards, err := loadNvidiaContainer()
	if err != nil {
		nvidiaCards, err = loadNvidiaProc()
		if err != nil {
			nvidiaCards = map[string]*api.ResourcesGPUCardNvidia{}
		}
	}

	// Temporary variables
	pciKnown := []string{}
	pciVFs := map[string][]api.ResourcesGPUCard{}

	// Detect all GPUs available through kernel drm interface
	if sysfsExists(sysClassDrm) {
		entries, err := os.ReadDir(sysClassDrm)
		if err != nil {
			return nil, fmt.Errorf("Failed to list %q: %w", sysClassDrm, err)
		}

		// Iterate and add to our list
		for _, entry := range entries {
			entryName := entry.Name()
			entryPath := filepath.Join(sysClassDrm, entryName)
			devicePath := filepath.Join(entryPath, "device")

			// Only care about cards not renderers
			if !strings.HasPrefix(entryName, "card") {
				continue
			}

			// Only keep the main entries not sub-cards
			if !sysfsExists(filepath.Join(entryPath, "dev")) {
				continue
			}

			// Setup the entry
			card := api.ResourcesGPUCard{}

			// PCI address.
			pciAddr, err := pciAddress(devicePath)
			if err != nil {
				return nil, fmt.Errorf("Failed to find PCI address for %q: %w", devicePath, err)
			}

			if pciAddr != "" {
				card.PCIAddress = pciAddr

				// Skip devices we already know about
				if slices.Contains(pciKnown, card.PCIAddress) {
					continue
				}

				pciKnown = append(pciKnown, card.PCIAddress)
			}

			// Add device information
			err = gpuAddDeviceInfo(devicePath, nvidiaCards, pciDB, uname, &card)
			if err != nil {
				return nil, fmt.Errorf("Failed to add device information for %q: %w", devicePath, err)
			}

			// Add to list
			if sysfsExists(filepath.Join(devicePath, "physfn")) {
				// Virtual functions need to be added to the parent
				linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
				if err != nil {
					return nil, fmt.Errorf("Failed to find %q: %w", filepath.Join(devicePath, "physfn"), err)
				}

				parentAddress := filepath.Base(linkTarget)

				_, ok := pciVFs[parentAddress]
				if !ok {
					pciVFs[parentAddress] = []api.ResourcesGPUCard{}
				}

				pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
			} else {
				gpu.Cards = append(gpu.Cards, card)
			}
		}
	}

	// Detect remaining GPUs on PCI bus
	if sysfsExists(sysBusPci) {
		entries, err := os.ReadDir(sysBusPci)
		if err != nil {
			return nil, fmt.Errorf("Failed to list %q: %w", sysBusPci, err)
		}

		// Iterate and add to our list
		for _, entry := range entries {
			entryName := entry.Name()
			devicePath := filepath.Join(sysBusPci, entryName)

			// Skip devices we already know about
			if slices.Contains(pciKnown, entryName) {
				continue
			}

			// Only care about identifiable devices
			if !sysfsExists(filepath.Join(devicePath, "class")) {
				continue
			}

			class, err := os.ReadFile(filepath.Join(devicePath, "class"))
			if err != nil {
				return nil, fmt.Errorf("Failed to read %q: %w", filepath.Join(devicePath, "class"), err)
			}

			// Only care about VGA devices
			if !strings.HasPrefix(string(class), "0x03") {
				continue
			}

			// Start building up data
			card := api.ResourcesGPUCard{}
			card.PCIAddress = entryName

			// Add device information
			err = gpuAddDeviceInfo(devicePath, nvidiaCards, pciDB, uname, &card)
			if err != nil {
				return nil, fmt.Errorf("Failed to add device information for %q: %w", devicePath, err)
			}

			// Add to list
			if sysfsExists(filepath.Join(devicePath, "physfn")) {
				// Virtual functions need to be added to the parent
				linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
				if err != nil {
					return nil, fmt.Errorf("Failed to find %q: %w", filepath.Join(devicePath, "physfn"), err)
				}

				parentAddress := filepath.Base(linkTarget)

				_, ok := pciVFs[parentAddress]
				if !ok {
					pciVFs[parentAddress] = []api.ResourcesGPUCard{}
				}

				pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
			} else {
				gpu.Cards = append(gpu.Cards, card)
			}
		}
	}

	// Add SRIOV devices and count devices
	gpu.Total = 0
	for _, card := range gpu.Cards {
		if card.SRIOV != nil {
			card.SRIOV.VFs = pciVFs[card.PCIAddress]
			gpu.Total += uint64(len(card.SRIOV.VFs))
		}

		gpu.Total++
	}

	return &gpu, nil
}