1 package PVE
::SysFSTools
;
8 use PVE
::Tools
qw(file_read_firstline dir_glob_foreach);
10 my $pcisysfs = "/sys/bus/pci";
11 my $pciregex = "([a-f0-9]{4}):([a-f0-9]{2}):([a-f0-9]{2})\.([a-f0-9])";
17 dir_glob_foreach
("$pcisysfs/devices", $pciregex, sub {
18 my (undef, undef, $bus, $slot, $function) = @_;
19 my $id = "$bus:$slot";
20 my $res = { id
=> $id, function
=> $function};
21 push @{$devices->{$id}}, $res;
24 # Entries should be sorted by functions.
25 foreach my $id (keys %$devices) {
26 my $dev = $devices->{$id};
27 $devices->{$id} = [ sort { $a->{function
} <=> $b->{function
} } @$dev ];
33 sub check_iommu_support
{
34 #fixme : need to check IOMMU support
35 #http://www.linux-kvm.org/page/How_to_assign_devices_with_VT-d_in_KVM
43 my ($filename, $buf) = @_;
45 my $fh = IO
::File-
>new($filename, "w");
48 my $res = print $fh $buf;
60 return undef if $name !~ m/^${pciregex}$/;
61 my ($domain, $bus, $slot, $func) = ($1, $2, $3, $4);
63 my $irq = file_read_firstline
("$pcisysfs/devices/$name/irq");
64 return undef if !defined($irq) || $irq !~ m/^\d+$/;
66 my $vendor = file_read_firstline
("$pcisysfs/devices/$name/vendor");
67 return undef if !defined($vendor) || $vendor !~ s/^0x//;
69 my $product = file_read_firstline
("$pcisysfs/devices/$name/device");
70 return undef if !defined($product) || $product !~ s/^0x//;
81 has_fl_reset
=> -f
"$pcisysfs/devices/$name/reset" || 0,
90 my $name = $dev->{name
};
92 my $fn = "$pcisysfs/devices/$name/reset";
94 return file_write
($fn, "1");
97 sub pci_dev_bind_to_vfio
{
100 my $name = $dev->{name
};
102 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
104 if (!-d
$vfio_basedir) {
105 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
107 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
109 my $testdir = "$vfio_basedir/$name";
110 return 1 if -d
$testdir;
112 my $data = "$dev->{vendor} $dev->{product}";
113 return undef if !file_write
("$vfio_basedir/new_id", $data);
115 my $fn = "$pcisysfs/devices/$name/driver/unbind";
116 if (!file_write
($fn, $name)) {
117 return undef if -f
$fn;
120 $fn = "$vfio_basedir/bind";
122 return undef if !file_write
($fn, $name);
128 sub pci_dev_group_bind_to_vfio
{
131 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
133 if (!-d
$vfio_basedir) {
134 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
136 die "Cannot find vfio-pci module!\n" if !-d
$vfio_basedir;
138 # get IOMMU group devices
139 opendir(my $D, "$pcisysfs/devices/0000:$pciid/iommu_group/devices/") || die "Cannot open iommu_group: $!\n";
140 my @devs = grep /^0000:/, readdir($D);
143 foreach my $pciid (@devs) {
144 $pciid =~ m/^([:\.\da-f]+)$/ or die "PCI ID $pciid not valid!\n";
146 # pci bridges, switches or root ports are not supported
147 # they have a pci_bus subdirectory so skip them
148 next if (-e
"$pcisysfs/devices/$pciid/pci_bus");
150 my $info = pci_device_info
($1);
151 pci_dev_bind_to_vfio
($info) || die "Cannot bind $pciid to vfio\n";