1{
2 config,
3 lib,
4 pkgs,
5 ...
6}:
7
8with lib;
9
10let
11 cfg = config.virtualisation.kvmgt;
12
13 kernelPackages = config.boot.kernelPackages;
14
15 vgpuOptions = {
16 uuid = mkOption {
17 type = with types; listOf str;
18 description = "UUID(s) of VGPU device. You can generate one with `libossp_uuid`.";
19 };
20 };
21
22in
23{
24 options = {
25 virtualisation.kvmgt = {
26 enable = mkEnableOption ''
27 KVMGT (iGVT-g) VGPU support. Allows Qemu/KVM guests to share host's Intel integrated graphics card.
28 Currently only one graphical device can be shared. To allow users to access the device without root add them
29 to the kvm group: `users.extraUsers.<yourusername>.extraGroups = [ "kvm" ];`
30 '';
31 # multi GPU support is under the question
32 device = mkOption {
33 type = types.str;
34 default = "0000:00:02.0";
35 description = "PCI ID of graphics card. You can figure it with {command}`ls /sys/class/mdev_bus`.";
36 };
37 vgpus = mkOption {
38 default = { };
39 type = with types; attrsOf (submodule [ { options = vgpuOptions; } ]);
40 description = ''
41 Virtual GPUs to be used in Qemu. You can find devices via {command}`ls /sys/bus/pci/devices/*/mdev_supported_types`
42 and find info about device via {command}`cat /sys/bus/pci/devices/*/mdev_supported_types/i915-GVTg_V5_4/description`
43 '';
44 example = {
45 i915-GVTg_V5_8.uuid = [ "a297db4a-f4c2-11e6-90f6-d3b88d6c9525" ];
46 };
47 };
48 };
49 };
50
51 config = mkIf cfg.enable {
52 assertions = singleton {
53 assertion = versionAtLeast kernelPackages.kernel.version "4.16";
54 message = "KVMGT is not properly supported for kernels older than 4.16";
55 };
56
57 boot.kernelModules = [ "kvmgt" ];
58 boot.kernelParams = [ "i915.enable_gvt=1" ];
59
60 services.udev.extraRules = ''
61 SUBSYSTEM=="vfio", OWNER="root", GROUP="kvm"
62 '';
63
64 systemd =
65 let
66 vgpus = listToAttrs (
67 flatten (
68 mapAttrsToList (
69 mdev: opt:
70 map (
71 id:
72 nameValuePair "kvmgt-${id}" {
73 inherit mdev;
74 uuid = id;
75 }
76 ) opt.uuid
77 ) cfg.vgpus
78 )
79 );
80 in
81 {
82 paths = mapAttrs (_: opt: {
83 description = "KVMGT VGPU ${opt.uuid} path";
84 wantedBy = [ "multi-user.target" ];
85 pathConfig = {
86 PathExists = "/sys/bus/pci/devices/${cfg.device}/mdev_supported_types/${opt.mdev}/create";
87 };
88 }) vgpus;
89
90 services = mapAttrs (_: opt: {
91 description = "KVMGT VGPU ${opt.uuid}";
92 serviceConfig = {
93 Type = "oneshot";
94 RemainAfterExit = true;
95 ExecStart = "${pkgs.runtimeShell} -c 'echo ${opt.uuid} > /sys/bus/pci/devices/${cfg.device}/mdev_supported_types/${opt.mdev}/create'";
96 ExecStop = "${pkgs.runtimeShell} -c 'echo 1 > /sys/bus/pci/devices/${cfg.device}/${opt.uuid}/remove'";
97 };
98 }) vgpus;
99 };
100 };
101
102 meta.maintainers = with maintainers; [ patryk27 ];
103}