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