]> git.proxmox.com Git - pve-common.git/blob - src/PVE/SysFSTools.pm
2e7d0284156b8a153e4255c1b85de565a47be17e
[pve-common.git] / src / PVE / SysFSTools.pm
1 package PVE::SysFSTools;
2
3 use strict;
4 use warnings;
5
6 use IO::File;
7
8 use PVE::Tools qw(file_read_firstline dir_glob_foreach);
9
10 my $pcisysfs = "/sys/bus/pci";
11 my $pciregex = "([a-f0-9]{4}):([a-f0-9]{2}):([a-f0-9]{2})\.([a-f0-9])";
12
13 my $parse_pci_ids = sub {
14 my $ids = {};
15
16 open(my $fh, '<', "/usr/share/misc/pci.ids")
17 or return $ids;
18
19 my $curvendor;
20 my $curdevice;
21 while (my $line = <$fh>) {
22 if ($line =~ m/^([0-9a-fA-F]{4})\s+(.*)$/) {
23 $curvendor = ($ids->{"0x$1"} = {});
24 $curvendor->{name} = $2;
25 } elsif ($line =~ m/^\t([0-9a-fA-F]{4})\s+(.*)$/) {
26 $curdevice = ($curvendor->{devices}->{"0x$1"} = {});
27 $curdevice->{name} = $2;
28 } elsif ($line =~ m/^\t\t([0-9a-fA-F]{4}) ([0-9a-fA-F]{4})\s+(.*)$/) {
29 $curdevice->{subs}->{"0x$1"}->{"0x$2"} = $3;
30 }
31 }
32
33 return $ids;
34 };
35
36 # returns a list of pci devices
37 #
38 # filter is either a string (then it tries to match to the id)
39 # or a sub ref (then it adds the device if the sub returns truthy)
40 #
41 # verbose also returns iommu groups, subvendor/device and the
42 # human readable names from /usr/share/misc/pci.ids
43 sub lspci {
44 my ($filter, $verbose) = @_;
45
46 my $devices = [];
47 my $ids = {};
48 if ($verbose) {
49 $ids = $parse_pci_ids->();
50 }
51
52 dir_glob_foreach("$pcisysfs/devices", $pciregex, sub {
53 my ($fullid, $domain, $bus, $slot, $function) = @_;
54 my $id = "$bus:$slot.$function";
55
56 if (defined($filter) && !ref($filter) && $id !~ m/^\Q$filter\E/) {
57 return; # filter ids early
58 }
59
60 my $devdir = "$pcisysfs/devices/$fullid";
61
62 my $vendor = file_read_firstline("$devdir/vendor");
63 my $device = file_read_firstline("$devdir/device");
64 my $class = file_read_firstline("$devdir/class");
65
66 my $res = {
67 id => $id,
68 vendor => $vendor,
69 device => $device,
70 class => $class,
71 };
72
73 if (defined($filter) && ref($filter) eq 'CODE' && !$filter->($res)) {
74 return;
75 }
76
77 if ($verbose) {
78 $res->{iommugroup} = -1;
79 if (-e "$devdir/iommu_group") {
80 my ($iommugroup) = (readlink("$devdir/iommu_group") =~ m/\/(\d+)$/);
81 $res->{iommugroup} = int($iommugroup);
82 }
83
84 if (-d "$devdir/mdev_supported_types") {
85 $res->{mdev} = 1;
86 }
87
88 my $device_hash = $ids->{$vendor}->{devices}->{$device} // {};
89
90 my $sub_vendor = file_read_firstline("$devdir/subsystem_vendor");
91 my $sub_device = file_read_firstline("$devdir/subsystem_device");
92
93 my $vendor_name = $ids->{$vendor}->{name};
94 my $device_name = $device_hash->{name};
95 my $sub_vendor_name = $ids->{$sub_vendor}->{name};
96 my $sub_device_name = $device_hash->{subs}->{$sub_vendor}->{$sub_device};
97
98 $res->{vendor_name} = $vendor_name if defined($vendor_name);
99 $res->{device_name} = $device_name if defined($device_name);
100 $res->{subsystem_vendor} = $sub_vendor if defined($sub_vendor);
101 $res->{subsystem_device} = $sub_device if defined($sub_device);
102 $res->{subsystem_vendor_name} = $sub_vendor_name if defined($sub_vendor_name);
103 $res->{subsystem_device_name} = $sub_device_name if defined($sub_device_name);
104 }
105
106 push @$devices, $res;
107 });
108
109 # Entries should be sorted by ids
110 $devices = [ sort { $a->{id} cmp $b->{id} } @$devices ];
111
112 return $devices;
113 }
114
115 sub get_mdev_types {
116 my ($id) = @_;
117
118 my $fullid = $id;
119 if ($id !~ m/^[0-9a-fA-f]{4}:/) {
120 $fullid = "0000:$id";
121 }
122
123 my $types = [];
124
125 my $mdev_path = "$pcisysfs/devices/$fullid/mdev_supported_types";
126 if (!-d $mdev_path) {
127 return $types;
128 }
129
130 dir_glob_foreach($mdev_path, '[^\.].*', sub {
131 my ($type) = @_;
132
133 my $type_path = "$mdev_path/$type";
134
135 my $available = int(file_read_firstline("$type_path/available_instances"));
136 my $description = PVE::Tools::file_get_contents("$type_path/description");
137
138 push @$types, {
139 type => $type,
140 description => $description,
141 available => $available,
142 };
143 });
144
145 return $types;
146 }
147
148 sub check_iommu_support{
149 # we have IOMMU support if /sys/class/iommu/ is populated
150 return PVE::Tools::dir_glob_regex('/sys/class/iommu/', "[^\.].*");
151 }
152
153 sub file_write {
154 my ($filename, $buf) = @_;
155
156 my $fh = IO::File->new($filename, "w");
157 return undef if !$fh;
158
159 my $res = print $fh $buf;
160
161 $fh->close();
162
163 return $res;
164 }
165
166 sub pci_device_info {
167 my ($name) = @_;
168
169 my $res;
170
171 return undef if $name !~ m/^${pciregex}$/;
172 my ($domain, $bus, $slot, $func) = ($1, $2, $3, $4);
173
174 my $irq = file_read_firstline("$pcisysfs/devices/$name/irq");
175 return undef if !defined($irq) || $irq !~ m/^\d+$/;
176
177 my $vendor = file_read_firstline("$pcisysfs/devices/$name/vendor");
178 return undef if !defined($vendor) || $vendor !~ s/^0x//;
179
180 my $product = file_read_firstline("$pcisysfs/devices/$name/device");
181 return undef if !defined($product) || $product !~ s/^0x//;
182
183 $res = {
184 name => $name,
185 vendor => $vendor,
186 product => $product,
187 domain => $domain,
188 bus => $bus,
189 slot => $slot,
190 func => $func,
191 irq => $irq,
192 has_fl_reset => -f "$pcisysfs/devices/$name/reset" || 0,
193 };
194
195 return $res;
196 }
197
198 sub pci_dev_reset {
199 my ($dev) = @_;
200
201 my $name = $dev->{name};
202
203 my $fn = "$pcisysfs/devices/$name/reset";
204
205 return file_write($fn, "1");
206 }
207
208 sub pci_dev_bind_to_vfio {
209 my ($dev) = @_;
210
211 my $name = $dev->{name};
212
213 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
214
215 if (!-d $vfio_basedir) {
216 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
217 }
218 die "Cannot find vfio-pci module!\n" if !-d $vfio_basedir;
219
220 my $testdir = "$vfio_basedir/$name";
221 return 1 if -d $testdir;
222
223 my $data = "$dev->{vendor} $dev->{product}";
224 return undef if !file_write("$vfio_basedir/new_id", $data);
225
226 my $fn = "$pcisysfs/devices/$name/driver/unbind";
227 if (!file_write($fn, $name)) {
228 return undef if -f $fn;
229 }
230
231 $fn = "$vfio_basedir/bind";
232 if (! -d $testdir) {
233 return undef if !file_write($fn, $name);
234 }
235
236 return -d $testdir;
237 }
238
239 sub pci_dev_group_bind_to_vfio {
240 my ($pciid) = @_;
241
242 my $vfio_basedir = "$pcisysfs/drivers/vfio-pci";
243
244 if (!-d $vfio_basedir) {
245 system("/sbin/modprobe vfio-pci >/dev/null 2>/dev/null");
246 }
247 die "Cannot find vfio-pci module!\n" if !-d $vfio_basedir;
248
249 # get IOMMU group devices
250 opendir(my $D, "$pcisysfs/devices/0000:$pciid/iommu_group/devices/") || die "Cannot open iommu_group: $!\n";
251 my @devs = grep /^0000:/, readdir($D);
252 closedir($D);
253
254 foreach my $pciid (@devs) {
255 $pciid =~ m/^([:\.\da-f]+)$/ or die "PCI ID $pciid not valid!\n";
256
257 # pci bridges, switches or root ports are not supported
258 # they have a pci_bus subdirectory so skip them
259 next if (-e "$pcisysfs/devices/$pciid/pci_bus");
260
261 my $info = pci_device_info($1);
262 pci_dev_bind_to_vfio($info) || die "Cannot bind $pciid to vfio\n";
263 }
264
265 return 1;
266 }
267
268 sub pci_create_mdev_device {
269 my ($pciid, $uuid, $type) = @_;
270
271 my $basedir = "$pcisysfs/devices/0000:$pciid";
272 my $mdev_dir = "$basedir/mdev_supported_types";
273
274 die "pci device '$pciid' does not support mediated devices \n"
275 if !-d $mdev_dir;
276
277 die "pci device '$pciid' has no type '$type'\n"
278 if !-d "$mdev_dir/$type";
279
280 if (-d "$basedir/$uuid") {
281 # it already exists, checking type
282 my $typelink = readlink("$basedir/$uuid/mdev_type");
283 my ($existingtype) = $typelink =~ m|/([^/]+)$|;
284 die "mdev instance '$uuid' already exits, but type is not '$type'\n"
285 if $type ne $existingtype;
286
287 # instance exists, so use it but warn the user
288 warn "mdev instance '$uuid' already existed, using it.\n";
289 return undef;
290 }
291
292 my $instances = file_read_firstline("$mdev_dir/$type/available_instances");
293 my ($avail) = $instances =~ m/^(\d+)$/;
294 die "pci device '$pciid' has no available instances of '$type'\n"
295 if $avail < 1;
296
297 die "could not create 'type' for pci devices '$pciid'\n"
298 if !file_write("$mdev_dir/$type/create", $uuid);
299
300 return undef;
301 }
302
303 sub pci_cleanup_mdev_device {
304 my ($pciid, $uuid) = @_;
305
306 my $basedir = "$pcisysfs/devices/0000:$pciid/$uuid";
307
308 if (! -e $basedir) {
309 return 1; # no cleanup necessary if it does not exist
310 }
311
312 return file_write("$basedir/remove", "1");
313 }
314
315 # encode the hostpci index and vmid into the uuid
316 sub generate_mdev_uuid {
317 my ($vmid, $index) = @_;
318
319 my $string = sprintf("%08d-0000-0000-0000-%012d", $index, $vmid);
320
321 return $string;
322 }
323
324 # idea is from usbutils package (/usr/bin/usb-devices) script
325 sub __scan_usb_device {
326 my ($res, $devpath, $parent, $level) = @_;
327
328 return if ! -d $devpath;
329 return if $level && $devpath !~ m/^.*[-.](\d+)$/;
330 my $port = $level ? int($1 - 1) : 0;
331
332 my $busnum = int(file_read_firstline("$devpath/busnum"));
333 my $devnum = int(file_read_firstline("$devpath/devnum"));
334
335 my $d = {
336 port => $port,
337 level => $level,
338 busnum => $busnum,
339 devnum => $devnum,
340 speed => file_read_firstline("$devpath/speed"),
341 class => hex(file_read_firstline("$devpath/bDeviceClass")),
342 vendid => file_read_firstline("$devpath/idVendor"),
343 prodid => file_read_firstline("$devpath/idProduct"),
344 };
345
346 if ($level) {
347 my $usbpath = $devpath;
348 $usbpath =~ s|^.*/\d+\-||;
349 $d->{usbpath} = $usbpath;
350 }
351
352 my $product = file_read_firstline("$devpath/product");
353 $d->{product} = $product if $product;
354
355 my $manu = file_read_firstline("$devpath/manufacturer");
356 $d->{manufacturer} = $manu if $manu;
357
358 my $serial => file_read_firstline("$devpath/serial");
359 $d->{serial} = $serial if $serial;
360
361 push @$res, $d;
362
363 foreach my $subdev (<$devpath/$busnum-*>) {
364 next if $subdev !~ m|/$busnum-[0-9]+(\.[0-9]+)*$|;
365 __scan_usb_device($res, $subdev, $devnum, $level + 1);
366 }
367
368 };
369
370 sub scan_usb {
371
372 my $devlist = [];
373
374 foreach my $device (</sys/bus/usb/devices/usb*>) {
375 __scan_usb_device($devlist, $device, 0, 0);
376 }
377
378 return $devlist;
379 }
380
381 1;