@@ -3,9 +3,11 @@ package devices
33import (
44 "context"
55 "encoding/json"
6+ "errors"
67 "fmt"
78 "os"
89 "runtime"
10+ "slices"
911 "strings"
1012 "sync"
1113 "time"
@@ -19,16 +21,14 @@ import (
1921// InstanceLivenessChecker provides a way to check if an instance is running.
2022// This interface allows devices to query instance state without a circular dependency.
2123type InstanceLivenessChecker interface {
22- // IsInstanceRunning returns true if the instance exists and is in a running state
23- // (i.e., has an active VMM process). Returns false if the instance doesn't exist
24- // or is stopped/standby/unknown.
24+ // IsInstanceRunning counts uncertain VMM liveness as running for device reconciliation.
2525 IsInstanceRunning (ctx context.Context , instanceID string ) bool
2626
2727 // GetInstanceDevices returns the list of device IDs attached to an instance.
2828 // Returns nil if the instance doesn't exist.
2929 GetInstanceDevices (ctx context.Context , instanceID string ) []string
3030
31- // ListAllInstanceDevices returns a map of instanceID -> []deviceIDs for all instances .
31+ // ListAllInstanceDevices returns instance IDs and their device references, or nil if the inventory is incomplete .
3232 ListAllInstanceDevices (ctx context.Context ) map [string ][]string
3333
3434 // DetectSuspiciousVMMProcesses finds cloud-hypervisor processes that don't match
@@ -65,6 +65,12 @@ type Manager interface {
6565 // MarkDetached marks a device as detached from an instance
6666 MarkDetached (ctx context.Context , deviceID string ) error
6767
68+ // ReleaseInstanceDevice detaches and unbinds a passthrough device only if this instance owns it.
69+ ReleaseInstanceDevice (ctx context.Context , deviceID , instanceID string ) error
70+
71+ // DetachInstanceDevice clears the attachment without unbinding, only if this instance owns it.
72+ DetachInstanceDevice (ctx context.Context , deviceID , instanceID string ) error
73+
6874 // ReconcileDevices cleans up stale device state on startup.
6975 // It detects devices with AttachedTo referencing non-existent instances
7076 // and clears the orphaned attachment state.
@@ -75,9 +81,21 @@ type Manager interface {
7581 SetLivenessChecker (checker InstanceLivenessChecker )
7682}
7783
84+ type deviceBinder interface {
85+ deviceBoundToVFIO (string ) (bool , error )
86+ IsDeviceBoundToVFIO (string ) bool
87+ BindToVFIO (string ) error
88+ UnbindFromVFIO (string ) error
89+ CheckIOMMUGroupSafe (string , []string ) error
90+ unbindFromDriver (string , string ) error
91+ setDriverOverride (string , string ) error
92+ triggerDriverProbe (string ) error
93+ startNvidiaPersistenced () error
94+ }
95+
7896type manager struct {
7997 paths * paths.Paths
80- vfioBinder * VFIOBinder
98+ vfioBinder deviceBinder
8199 livenessChecker InstanceLivenessChecker
82100 mu sync.RWMutex
83101}
@@ -322,8 +340,6 @@ func (m *manager) BindToVFIO(ctx context.Context, id string) error {
322340}
323341
324342func (m * manager ) UnbindFromVFIO (ctx context.Context , id string ) error {
325- log := logger .FromContext (ctx )
326-
327343 m .mu .Lock ()
328344 defer m .mu .Unlock ()
329345
@@ -341,8 +357,8 @@ func (m *manager) UnbindFromVFIO(ctx context.Context, id string) error {
341357 return ErrInUse
342358 }
343359
344- // Unbind from VFIO
345- if err := m .vfioBinder . UnbindFromVFIO (device .PCIAddress ); err != nil {
360+ log := logger . FromContext ( ctx )
361+ if err := m .unbindAndVerify (device .PCIAddress ); err != nil {
346362 return err
347363 }
348364
@@ -397,11 +413,87 @@ func (m *manager) MarkDetached(ctx context.Context, deviceID string) error {
397413 return m .saveDevice (device )
398414}
399415
416+ // The driver probe can bind the device straight back to vfio-pci. Check
417+ // sysfs before recording the release or dropping the owner that can retry it.
418+ func (m * manager ) unbindAndVerify (pciAddress string ) error {
419+ if err := m .vfioBinder .UnbindFromVFIO (pciAddress ); err != nil {
420+ return err
421+ }
422+ bound , err := m .vfioBinder .deviceBoundToVFIO (pciAddress )
423+ if err != nil {
424+ return fmt .Errorf ("verify VFIO release of %s: %w" , pciAddress , err )
425+ }
426+ if bound {
427+ return fmt .Errorf ("device %s is still bound to vfio-pci" , pciAddress )
428+ }
429+ return nil
430+ }
431+
432+ // releasableDevice returns nil for a non-owner. A recorded owner may be a
433+ // stopped source whose fork still has the device open. Caller holds m.mu.
434+ func (m * manager ) releasableDevice (ctx context.Context , deviceID , instanceID string ) (* Device , error ) {
435+ device , err := m .loadDevice (deviceID )
436+ if err != nil {
437+ return nil , err
438+ }
439+ if device .AttachedTo == nil || * device .AttachedTo != instanceID {
440+ return nil , nil
441+ }
442+ var refs map [string ][]string
443+ if m .livenessChecker != nil {
444+ refs = m .livenessChecker .ListAllInstanceDevices (ctx )
445+ }
446+ if refs == nil {
447+ return nil , fmt .Errorf ("%w: cannot verify PCI device references for %s" , ErrInUse , deviceID )
448+ }
449+ for id , ids := range refs {
450+ if id != instanceID && slices .Contains (ids , deviceID ) && m .livenessChecker .IsInstanceRunning (ctx , id ) {
451+ return nil , fmt .Errorf ("%w: instance %s still references PCI device %s" , ErrInUse , id , deviceID )
452+ }
453+ }
454+ return device , nil
455+ }
456+
457+ // ReleaseInstanceDevice checks the recorded owner under the same lock as the unbind.
458+ // A fork's device list can name a passthrough device still owned by its source.
459+ func (m * manager ) ReleaseInstanceDevice (ctx context.Context , deviceID , instanceID string ) error {
460+ m .mu .Lock ()
461+ defer m .mu .Unlock ()
462+ device , err := m .releasableDevice (ctx , deviceID , instanceID )
463+ if err != nil || device == nil {
464+ return err
465+ }
466+ // A retry after the unbind but before the save sees ErrNotBound.
467+ if err := m .unbindAndVerify (device .PCIAddress ); err != nil && ! errors .Is (err , ErrNotBound ) {
468+ return err
469+ }
470+ device .AttachedTo = nil
471+ device .BoundToVFIO = false
472+ return m .saveDevice (device )
473+ }
474+
475+ // DetachInstanceDevice frees a device whose owner is being deleted after its
476+ // release failed. Nothing retries a release once the owner is gone, and
477+ // nothing but a restart clears an attachment to a missing instance.
478+ func (m * manager ) DetachInstanceDevice (ctx context.Context , deviceID , instanceID string ) error {
479+ m .mu .Lock ()
480+ defer m .mu .Unlock ()
481+ device , err := m .releasableDevice (ctx , deviceID , instanceID )
482+ if err != nil || device == nil {
483+ return err
484+ }
485+ device .AttachedTo = nil
486+ // The failed release may or may not have unbound the device, and the next
487+ // attach binds it only if this says it is unbound.
488+ device .BoundToVFIO = m .vfioBinder .IsDeviceBoundToVFIO (device .PCIAddress )
489+ return m .saveDevice (device )
490+ }
491+
400492// ReconcileDevices cleans up stale device state on startup.
401493// It performs safe-by-default reconciliation:
402494// 1. Detects orphaned device attachments (instance missing or not running)
403- // 2. Clears orphaned AttachedTo metadata
404- // 3. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver)
495+ // 2. Runs GPU-reset-lite for orphaned devices (unbind VFIO, clear override, probe driver)
496+ // 3. Clears the attachment once the device is no longer bound to VFIO
405497// 4. Logs mismatches between instance→device and device→instance references
406498// 5. Detects suspicious cloud-hypervisor processes
407499func (m * manager ) ReconcileDevices (ctx context.Context ) error {
@@ -449,14 +541,29 @@ func (m *manager) ReconcileDevices(ctx context.Context) error {
449541 var instanceDevices map [string ][]string
450542 if m .livenessChecker != nil {
451543 instanceDevices = m .livenessChecker .ListAllInstanceDevices (ctx )
544+ if instanceDevices == nil {
545+ log .WarnContext (ctx , "skipping PCI reconciliation: instance device inventory is incomplete" )
546+ return nil
547+ }
548+ }
549+ // A fork can use a device whose AttachedTo still names its stopped source.
550+ liveInstances := make (map [string ]bool )
551+ inUse := make (map [string ]bool )
552+ for id , refs := range instanceDevices {
553+ if m .livenessChecker .IsInstanceRunning (ctx , id ) {
554+ liveInstances [id ] = true
555+ for _ , ref := range refs {
556+ inUse [ref ] = true
557+ }
558+ }
452559 }
453560
454561 // Track stats
455562 var stats reconcileStats
456563
457564 // Phase 1: Detect and handle orphaned device attachments
458565 for _ , device := range allDevices {
459- if device .AttachedTo == nil {
566+ if device .AttachedTo == nil || inUse [ device . Id ] {
460567 continue
461568 }
462569
@@ -471,19 +578,6 @@ func (m *manager) ReconcileDevices(ctx context.Context) error {
471578 "orphaned_instance_id" , instanceID ,
472579 )
473580
474- // Clear the orphaned attachment
475- device .AttachedTo = nil
476- if err := m .saveDevice (device ); err != nil {
477- log .ErrorContext (ctx , "failed to save device after clearing attachment" ,
478- "device_id" , device .Id ,
479- "error" , err ,
480- )
481- stats .errors ++
482- continue
483- }
484- stats .orphanedCleared ++
485-
486- // Run GPU-reset-lite for orphaned device
487581 m .resetOrphanedDevice (ctx , device , & stats )
488582 }
489583 }
@@ -522,16 +616,14 @@ func (m *manager) ReconcileDevices(ctx context.Context) error {
522616 }
523617
524618 // Check VFIO binding state - if instance is running, device should be bound
525- if m .livenessChecker != nil && m .livenessChecker .IsInstanceRunning (ctx , instanceID ) {
526- if ! device .BoundToVFIO {
527- log .WarnContext (ctx , "running instance has device not bound to VFIO (mismatch)" ,
528- "instance_id" , instanceID ,
529- "device_id" , deviceID ,
530- "device_name" , device .Name ,
531- "pci_address" , device .PCIAddress ,
532- )
533- stats .mismatches ++
534- }
619+ if liveInstances [instanceID ] && ! device .BoundToVFIO {
620+ log .WarnContext (ctx , "running instance has device not bound to VFIO (mismatch)" ,
621+ "instance_id" , instanceID ,
622+ "device_id" , deviceID ,
623+ "device_name" , device .Name ,
624+ "pci_address" , device .PCIAddress ,
625+ )
626+ stats .mismatches ++
535627 }
536628 }
537629 }
@@ -625,7 +717,6 @@ type reconcileStats struct {
625717func (m * manager ) isInstanceOrphaned (ctx context.Context , instanceID string ) bool {
626718 // If we have a liveness checker, use it for more accurate detection
627719 if m .livenessChecker != nil {
628- // Instance is orphaned if it's not running (stopped, standby, unknown, or missing)
629720 return ! m .livenessChecker .IsInstanceRunning (ctx , instanceID )
630721 }
631722
@@ -695,30 +786,22 @@ func (m *manager) resetOrphanedDevice(ctx context.Context, device *Device, stats
695786 }
696787
697788 // Verify the device is now unbound from VFIO
698- stillBoundToVFIO := m .vfioBinder .IsDeviceBoundToVFIO (device .PCIAddress )
699- if stillBoundToVFIO {
700- log .WarnContext (ctx , "device still bound to VFIO after reset-lite" ,
701- "device_id" , device .Id ,
702- "pci_address" , device .PCIAddress ,
703- )
789+ bound , err := m .vfioBinder .deviceBoundToVFIO (device .PCIAddress )
790+ if err != nil || bound {
791+ log .WarnContext (ctx , "cannot confirm device was unbound after reset-lite; keeping attachment" ,
792+ "device_id" , device .Id , "pci_address" , device .PCIAddress , "bound_to_vfio" , bound , "error" , err )
704793 stats .resetFailed ++
705- } else {
706- log .InfoContext (ctx , "GPU-reset-lite completed for orphaned device" ,
707- "device_id" , device .Id ,
708- "device_name" , device .Name ,
709- "pci_address" , device .PCIAddress ,
710- )
711- stats .resetSucceeded ++
794+ return
712795 }
713-
714- // Update device metadata to reflect new VFIO state
715- device .BoundToVFIO = stillBoundToVFIO
796+ stats . resetSucceeded ++
797+ device . AttachedTo = nil
798+ device .BoundToVFIO = false
716799 if err := m .saveDevice (device ); err != nil {
717- log .WarnContext (ctx , "failed to save device after reset-lite" ,
718- "device_id" , device .Id ,
719- "error" , err ,
720- )
800+ log .WarnContext (ctx , "failed to save device after reset-lite" , "device_id" , device .Id , "error" , err )
801+ stats .errors ++
802+ return
721803 }
804+ stats .orphanedCleared ++
722805}
723806
724807// Helper methods
0 commit comments