forked from NVIDIA/nvidia-driver-assistant
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMOD-NDA.py
More file actions
executable file
·1893 lines (1625 loc) · 76.2 KB
/
MOD-NDA.py
File metadata and controls
executable file
·1893 lines (1625 loc) · 76.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python3
"""Driver package query/installation tool for NVIDIA GPUs on Linux"""
# SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES.
# SPDX-License-Identifier: MIT
#
# Original Author:
# Alberto Milone <amilone@nvidia.com>
#
# Downstream Modifications:
# Manjaro Team
# - packaging adjustments
# - distribution-specific compatibility fixes
#
# Further Modifications / Maintenance:
# Gábor Gyöngyösi (@megvadulthangya)
# - refactoring and enhancements
#
#
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
# ==============================================================================
# ____ _ _
# / ___| |__ ___ ___| | __
#| | _| '_ \ / _ \/ __| |/ /
#| |_| | | | | __/ (__| <
# \____|_| |_|\___|\___|_|\_\
#
# Maintainer:
# Gábor Gyöngyösi (@megvadulthangya)
# https://links.gshoots.hu
#
# Internal-Revision: 25
# Purpose: personal development tracking
# ==============================================================================
import os
import logging
import re
import json
import argparse
import string
import sys
import platform
import subprocess
# Determine the directory where this script is located
default_directory = os.path.dirname(os.path.realpath(__file__))
default_json_path = os.path.join(default_directory, "supported-gpus", "supported-gpus.json")
install_json_path = "/usr/share/nvidia-driver-assistant/supported-gpus/supported-gpus.json"
# VDPAU feature groups
vdpau_group_a = [chr(x) for x in range(ord("a"), ord("c") + 1)]
vdpau_group_b = [chr(x) for x in range(ord("d"), ord("i") + 1)]
vdpau_group_c = [chr(x) for x in range(ord("j"), ord("l") + 1)]
# Driver type flags
proprietary_required = "proprietary_required"
proprietary_supported = "gsp_proprietary_supported"
default = "open_required"
open_supported = "kernelopen"
support_flags = (open_supported, proprietary_supported)
# ===== CONTROL VARIABLES (for distribution-specific overrides) =====
# 1. Non-legacy cards (no legacybranch in JSON)
# Set to override default driver branch for modern GPUs (e.g., "535", "545", etc.)
DISTRO_NON_LEGACY_DEFAULT_BRANCH = None
# 2. 580+ legacy branch cards (JSON has "legacybranch": "580.xx" or higher)
# Set to override 580+ legacy cards to older compatible branches (e.g., "470", "390", etc.)
DISTRO_580_LEGACY_OVERRIDE_BRANCH = None
# Old variable - backward compatibility (deprecated)
# Set to override all legacy cards regardless of architecture
DISTRO_LEGACY_OVERRIDE_BRANCH = None # Changed from "70" to None to avoid incorrect override
# ===========================================================================
# ===== LEGACY BRANCH OPENKERNEL RESTRICTION =====
# If True, all legacy branches (71.86.xx to 580.xx) will not use open kernel modules
ENABLE_LEGACY_OPENKERNEL_RESTRICTION = True
# ===== ARCHITECTURE-BASED OPENKERNEL CHECK =====
# If True, use architecture lists to determine open kernel capability
ENABLE_ARCHITECTURE_CHECK = True
# Architectures that support open kernel modules (only used if ENABLE_ARCHITECTURE_CHECK is True)
OPEN_CAPABLE_ARCHS = ("turing", "ampere", "ada", "blackwell")
# Architectures that don't support open kernel modules (require proprietary)
OPEN_UNSUPPORTED_ARCHS = (
"maxwell", "pascal", "volta", "fermi", "kepler",
"tesla2", "tesla1", "curie", "pre-curie", "unknown"
)
# ===== ARCHITECTURE MINIMUM DRIVER REQUIREMENTS =====
# Minimum driver version required for each GPU architecture
ARCHITECTURE_MIN_DRIVER = {
"blackwell": "550", # RTX 50xx: 550.40.15+
"ada": "525", # RTX 40xx: 525.60.11+
"ampere": "470", # RTX 30xx: 470.82.01+
"turing": "418", # RTX 20xx: 418.40.04+
"volta": "418", # Titan V: 418.40.04+
"pascal": "390", # GTX 10xx: 390.xx+
"maxwell": "390", # GTX 750 Ti, 900 series: 390.xx+
"kepler": "390", # GTX 600, 700 series: 390.xx+
"fermi": "390", # GTX 500 series: 390.xx
"tesla2": "340", # GTX 200 series: 340.xx
"tesla1": "304", # 8000, 9000 series: 304.xx
"curie": "96", # 7000 series: 96.xx
"pre-curie": "71", # 6000, FX series: 71.xx
"unknown": "390",
}
# ==================================================
# ===== SAFETY CONFIGURATION =====
# Enable strict compatibility checking between GPU architecture and driver version
ENABLE_STRICT_COMPATIBILITY = True
# Require user confirmation before proceeding with potentially incompatible drivers
REQUIRE_CONFIRMATION = False
# Automatically fall back to a safe driver version when incompatibility is detected
AUTO_FALLBACK = True
# Maximum allowed branch mismatch (0 = no mismatch allowed)
MAX_BRANCH_MISMATCH = 0
# =================================
if not os.environ.get("PATH"):
os.environ["PATH"] = "/sbin:/usr/sbin:/bin:/usr/bin"
# Supported Linux distributions for driver installation
supported_distros = [
"amzn", "debian", "ubuntu", "fedora", "kylin", "azurelinux",
"rhel", "rocky", "ol", "manjaro", "arch", "opensuse", "sles",
]
# Installation instructions for each distribution and driver type
instructions = {
"amzn-closed": ["sudo dnf -y module install nvidia-driver:latest-dkms"],
"amzn-open": ["sudo dnf -y module install nvidia-driver:open-dkms"],
"debian-closed": ["sudo apt-get install -Vy cuda-drivers"],
"debian-open": ["sudo apt-get install -Vy nvidia-open"],
"fedora-closed": ["sudo dnf -y install cuda-drivers"],
"fedora-open": ["sudo dnf -y install nvidia-open"],
"azurelinux-closed": ["Not supported"],
"azurelinux-open": ["sudo tdnf -y install nvidia-open"],
"kylin-closed": ["sudo dnf -y module install nvidia-driver:latest-dkms"],
"kylin-open": ["sudo dnf -y module install nvidia-driver:open-dkms"],
"opensuse-closed": ["sudo zypper --verbose install -y cuda-drivers"],
"opensuse-open": ["sudo zypper install -y nvidia-open"],
"sles-closed": ["sudo zypper install -y cuda-drivers"],
"sles-open": ["sudo zypper install -y nvidia-open"],
"rhel-closed": {
7: ["sudo dnf -y module install nvidia-driver:latest-dkms"],
10: ["sudo dnf -y install cuda-drivers"],
},
"rhel-open": {
7: ["sudo dnf -y module install nvidia-driver:open-dkms"],
10: ["sudo dnf -y install nvidia-open"],
},
"ubuntu-closed": ["sudo apt-get install -y cuda-drivers"],
"ubuntu-open": ["sudo apt-get install -y nvidia-open"],
"arch-closed": ["sudo pacman -S nvidia-dkms"],
"arch-open": ["sudo pacman -S nvidia-open-dkms"],
"manjaro-closed": ["sudo pacman -S KERNEL-nvidia"],
"manjaro-open": ["sudo pacman -S KERNEL-nvidia-open"],
}
# Installation instructions with specific branch versions
branch_instructions = {
"amzn-closed": ["sudo dnf -y module install nvidia-driver:BRANCH-dkms"],
"amzn-open": ["sudo dnf -y module install nvidia-driver:BRANCH-open"],
"debian-closed": ["sudo apt-get install -Vy cuda-drivers-BRANCH"],
"debian-open": ["sudo apt-get install -Vy nvidia-open-BRANCH"],
"fedora-closed": ["sudo dnf -y install cuda-drivers-BRANCH"],
"fedora-open": ["sudo dnf -y install nvidia-open-BRANCH"],
"azurelinux-closed": ["Not supported"],
"azurelinux-open": ["sudo tdnf -y install nvidia-open-BRANCH"],
"kylin-closed": ["sudo dnf -y module install nvidia-driver:BRANCH-dkms"],
"kylin-open": ["sudo dnf -y module install nvidia-driver:BRANCH-open"],
"opensuse-closed": ["sudo zypper --verbose install -y cuda-drivers-BRANCH"],
"opensuse-open": ["sudo zypper install -y nvidia-open-BRANCH"],
"sles-closed": ["sudo zypper install -y cuda-drivers-BRANCH"],
"sles-open": ["sudo zypper install -y nvidia-open-BRANCH"],
"rhel-closed": {
7: ["sudo dnf -y module install nvidia-driver:BRANCH-dkms"],
10: ["sudo dnf -y install cuda-drivers-BRANCH"],
},
"rhel-open": {
7: ["sudo dnf -y module install nvidia-driver:BRANCH-open"],
10: ["sudo dnf -y install nvidia-open-BRANCH"],
},
"ubuntu-closed": ["sudo apt-get install -y cuda-drivers-BRANCH"],
"ubuntu-open": ["sudo apt-get install -y nvidia-open-BRANCH"],
"arch-closed": ["Not supported"],
"arch-open": ["Not supported"],
"manjaro-closed": ["sudo pacman -S KERNEL-nvidia-BRANCHxx"],
"manjaro-open": ["sudo pacman -S KERNEL-nvidia-BRANCHxx-open"],
}
# Enhanced simulated GPU data with more detailed information
simulated_gpus = {
"545": {
"modalias": "pci:v000010DEd00001241sv000010DEsd000018FEbc03sc00i00",
"expected_name": "GeForce 545",
"expected_devid": "0x1241",
"expected_arch": "fermi",
"expected_legacy": "390"
},
"740A": {
"modalias": "pci:v000010DEd00001292sv000010DEsd000018FEbc03sc00i00",
"expected_name": "GeForce 740A",
"expected_devid": "0x1292",
"expected_arch": "kepler",
"expected_legacy": "390"
},
"750": {
"modalias": "pci:v000010DEd00001380sv000010DEsd000018FEbc03sc00i00",
"expected_name": "GeForce 750",
"expected_devid": "0x1380",
"expected_arch": "maxwell",
"expected_legacy": "470"
},
"800A": {
"modalias": "pci:v000010DEd00001058sv000017AAsd00003682bc03sc00i00",
"expected_name": "GeForce 800A",
"expected_devid": "0x1058",
"expected_subsys_vendor": "0x17AA",
"expected_subsys_device": "0x3682",
"expected_arch": "fermi",
"expected_legacy": "390"
},
"4070": {
"modalias": "pci:v000010DEd00002783sv000010DEsd000018FEbc03sc00i00",
"expected_name": "GeForce RTX 4070",
"expected_devid": "0x2783",
"expected_arch": "ada",
"expected_legacy": None
},
"5070": {
"modalias": "pci:v000010DEd00002D18sv000017AAsd00003E31bc03sc00i00",
"expected_name": "GeForce RTX 5070",
"expected_devid": "0x2D18",
"expected_arch": "blackwell",
"expected_legacy": None
},
"unknown": {
"modalias": "pci:v000010DEd000022BCsv000010DEsd000018FEbc04sc03i00",
"expected_name": "unknown",
"expected_devid": "0x22BC",
"expected_arch": "unknown",
"expected_legacy": None
},
}
class SystemInfo(object):
def __init__(self, id, version_id, pretty_name):
super(SystemInfo, self).__init__()
self.id = id
self.original_id = id
self.version_id = version_id
self.pretty_name = pretty_name
self.update_info()
def update_info(self):
"""Normalize distribution IDs for consistency"""
if self.id in ["opensuse-leap", "opensuse-tumbleweed"]:
self.id = "opensuse"
elif self.id in ["cm", "mariner"]:
self.id = "azurelinux"
elif self.id in ["rocky", "ol"]:
self.id = "rhel"
elif self.id == "arch" and "manjaro" in self.pretty_name.lower():
self.id = "manjaro"
if self.id != self.original_id:
logging.debug("get_distro(): detected %s, setting to %s" % (self.original_id, self.id))
class Device(object):
def __init__(self, id, name, features, legacy_branch, subvendorid=None, subdevid=None):
super(Device, self).__init__()
self.id = id
self.name = name
self.features = features
self.vdpau_feat = ""
self.legacy_branch = legacy_branch
self.driver_hint = ""
self.architecture = "unknown"
self.chip_family = ""
self.subvendorid = subvendorid
self.subdevid = subdevid
self.is_laptop_gpu = self._is_laptop_gpu(name)
self._determine_architecture()
self._parse_features(features)
def _is_laptop_gpu(self, name):
"""Determine if this is a laptop/mobile GPU"""
name_lower = name.lower()
# Explicit desktop exceptions that should NEVER be marked as mobile
desktop_exceptions = [
'750 ti', '1050 ti', '1650 ti', '1660 ti',
'2060 ti', '2070 ti', '2080 ti', '3060 ti',
'3070 ti', '3080 ti', '3090 ti', '4060 ti',
'4070 ti', '4080 ti', '4090 ti', 'titan',
'750', '760', '770', '780', '950', '960', '970', '980',
]
# Check for desktop exceptions first
for exception in desktop_exceptions:
if exception in name_lower:
return False
# REAL mobile indicators (with context)
# M at end of 3-4 digit number (860M, 965M, 1060M)
if re.search(r'\d{3,4}m\b', name_lower):
return True
# MX series (MX150, MX250, MX450)
if re.search(r'\bmx\d{3}\b', name_lower):
return True
# Explicit "Mobile" or "Laptop" in name
if 'mobile' in name_lower or 'laptop' in name_lower or 'notebook' in name_lower:
return True
# For ambiguous cases, check if it's in known mobile GPU list
known_mobile_gpus = [
'960m', '965m', '970m', '980m',
'1050m', '1060m', '1070m', '1080m',
'1650m', '1660m', '2060m', '2070m',
'2080m', '3050m', '3060m', '3070m',
'3080m', '4050m', '4060m', '4070m',
]
for mobile_gpu in known_mobile_gpus:
if mobile_gpu in name_lower:
return True
# Check for M suffix with space before (GeForce M)
if re.search(r'\s+m\b', name_lower) and not re.search(r'\s+ti\b', name_lower):
return True
return False
def _check_driver_compatibility(self, branch_major, legacy_override=False):
"""Check if a driver branch is compatible with this GPU architecture
Args:
branch_major: Major driver version number (e.g., "470" for 470.xx)
legacy_override: Whether we're applying a legacy override (DISTRO_LEGACY_OVERRIDE_BRANCH or DISTRO_580_LEGACY_OVERRIDE_BRANCH)
Returns:
tuple: (compatible: bool, message: str)
"""
if self.architecture == "unknown":
return True, "Unknown architecture, assuming compatibility"
try:
requested = int(branch_major)
# Check minimum requirement (applies to ALL devices)
min_driver = ARCHITECTURE_MIN_DRIVER.get(self.architecture, "390")
min_required = int(min_driver)
if requested < min_required:
# Get supported range for error message
min_supported, max_supported = self._get_supported_range(legacy_override)
return False, f"{self.architecture} requires drivers from {min_supported}.xx to {max_supported}.xx (requested: {requested}.xx)"
# Check maximum supported
# FOR LEGACY CARDS: maximum comes from JSON legacybranch
# FOR NON-LEGACY CARDS: no upper limit (999)
# If legacy_override is True, we treat as legacy for max check
min_supported, max_supported = self._get_supported_range(legacy_override)
try:
max_allowed = int(max_supported)
except ValueError:
# If max_supported is not a number (e.g., "999"), treat as no limit
max_allowed = 999
if requested > max_allowed:
return False, f"{self.architecture} requires drivers from {min_supported}.xx to {max_supported}.xx (requested: {requested}.xx)"
return True, f"{self.architecture} compatible with {branch_major}.xx (supported range: {min_supported}.xx - {max_supported}.xx)"
except ValueError:
return False, f"Invalid branch number: {branch_major}"
def _get_supported_range(self, legacy_override=False):
"""Get the supported driver range for this GPU
Args:
legacy_override: Whether we're applying a legacy override
Returns:
tuple: (min_driver: str, max_driver: str)
"""
min_driver = ARCHITECTURE_MIN_DRIVER.get(self.architecture, "390")
# Determine maximum driver version:
# 1. If this is a legacy card (has legacybranch in JSON), use that as max
# 2. If legacy_override is True (using DISTRO_LEGACY_OVERRIDE_BRANCH or DISTRO_580_LEGACY_OVERRIDE_BRANCH),
# treat as legacy and use the override branch as max (but compatibility will be checked separately)
# 3. Otherwise (non-legacy card), no upper limit (999)
if self.legacy_branch:
# Legacy card - maximum comes from JSON legacybranch
try:
max_driver = self.legacy_branch.split('.')[0]
# Validate it's a number
int(max_driver)
return min_driver, max_driver
except (ValueError, IndexError):
# If legacybranch format is invalid, use 470 as fallback for legacy cards
return min_driver, "470"
elif legacy_override:
# Applying legacy override to non-legacy card
# This is an error case - we shouldn't apply legacy override to non-legacy cards
# But if we do, use 470 as maximum (legacy default)
return min_driver, "470"
else:
# Non-legacy card - no upper limit
return min_driver, "999"
def _get_safe_fallback_branch(self, legacy_override=False):
"""Get a safe fallback branch for this GPU
Args:
legacy_override: Whether we're applying a legacy override
Returns:
str: Safe driver branch
"""
min_driver, max_driver = self._get_supported_range(legacy_override)
# For legacy cards, try to use the maximum supported if it's valid
if self.legacy_branch:
try:
legacy_major = int(self.legacy_branch.split('.')[0])
min_required = int(ARCHITECTURE_MIN_DRIVER.get(self.architecture, "390"))
# If the JSON legacybranch is valid and >= minimum, use it
if legacy_major >= min_required:
return str(legacy_major)
except (ValueError, IndexError):
pass
# Otherwise use minimum required
return min_driver
def _parse_features(self, features):
"""Parse feature flags to determine which driver to use
This method implements the driver selection logic in priority order:
1. Old variable backward compatibility override
2. Non-legacy default override
3. 580+ legacy override with safety checks
4. Legacy branch openkernel restriction (NEW)
5. Architecture-based check (if enabled)
6. Normal JSON-based logic
"""
flags = []
for feat in features:
feat = feat.lower()
logging.debug("Device: has following feature: %s" % (feat))
if feat.find("vdpaufeatureset") != -1:
self.vdpau_feat = feat.replace("vdpaufeatureset", "")[0]
elif feat in support_flags:
flags.append(feat)
logging.debug("Device: has following flags: %s" % (flags))
# ===== 1. OLD VARIABLE - BACKWARD COMPATIBILITY (deprecated) =====
if DISTRO_LEGACY_OVERRIDE_BRANCH:
# Legacy override applies - treat as legacy for compatibility check
compatible, message = self._check_driver_compatibility(
DISTRO_LEGACY_OVERRIDE_BRANCH,
legacy_override=True
)
if compatible:
self.legacy_branch = DISTRO_LEGACY_OVERRIDE_BRANCH + ".00"
self.driver_hint = proprietary_required
logging.info(
"Legacy override (old variable): %s forced to branch %s - %s"
% (self.name, self.legacy_branch, message)
)
return
else:
min_driver, max_driver = self._get_supported_range(legacy_override=True)
logging.error(
"SAFETY CHECK FAILED for %s (%s): %s",
self.name, self.architecture, message
)
if AUTO_FALLBACK:
safe_branch = self._get_safe_fallback_branch(legacy_override=True)
self.legacy_branch = safe_branch + ".00"
self.driver_hint = proprietary_required
logging.warning(
"Auto-fallback: %s using safe branch %s (original request: %s)",
self.name, safe_branch, DISTRO_LEGACY_OVERRIDE_BRANCH
)
return
# ===== 2. NON-LEGACY CARDS (no legacybranch in JSON) =====
if not self.legacy_branch and DISTRO_NON_LEGACY_DEFAULT_BRANCH:
# Non-legacy card - no upper limit (999)
compatible, message = self._check_driver_compatibility(
DISTRO_NON_LEGACY_DEFAULT_BRANCH,
legacy_override=False
)
if compatible:
self.legacy_branch = DISTRO_NON_LEGACY_DEFAULT_BRANCH + ".00"
self.driver_hint = proprietary_required
logging.info(
"Non-legacy default: %s set to branch %s - %s"
% (self.name, self.legacy_branch, message)
)
return
else:
min_driver, max_driver = self._get_supported_range(legacy_override=False)
logging.error(
"Non-legacy default FAILED for %s (%s): %s",
self.name, self.architecture, message
)
if AUTO_FALLBACK:
safe_branch = self._get_safe_fallback_branch(legacy_override=False)
self.legacy_branch = safe_branch + ".00"
self.driver_hint = proprietary_required
logging.warning(
"Auto-fallback: %s using safe branch %s (requested: %s)",
self.name, safe_branch, DISTRO_NON_LEGACY_DEFAULT_BRANCH
)
return
# ===== 3. 580+ LEGACY CARDS (JSON has "legacybranch": "580.xx" or higher) =====
# This is the main safety net for 580+ legacy cards
if self.legacy_branch and DISTRO_580_LEGACY_OVERRIDE_BRANCH:
legacy_major = self.legacy_branch.split('.')[0]
try:
legacy_major_int = int(legacy_major)
if legacy_major_int >= 580:
# Check if the requested override is compatible
compatible, message = self._check_driver_compatibility(
DISTRO_580_LEGACY_OVERRIDE_BRANCH,
legacy_override=True
)
if compatible:
self.legacy_branch = DISTRO_580_LEGACY_OVERRIDE_BRANCH + ".00"
self.driver_hint = proprietary_required
logging.info(
"580+ legacy override: %s changed from %s to %s - %s"
% (self.name, legacy_major, DISTRO_580_LEGACY_OVERRIDE_BRANCH, message)
)
return
else:
min_driver, max_driver = self._get_supported_range(legacy_override=True)
logging.error(
"580+ legacy override FAILED for %s (%s): %s",
self.name, self.architecture, message
)
if AUTO_FALLBACK:
safe_branch = self._get_safe_fallback_branch(legacy_override=True)
# Check if the original JSON legacybranch is actually valid
original_compatible, original_message = self._check_driver_compatibility(
legacy_major,
legacy_override=False # Use JSON's legacybranch as max
)
if original_compatible:
# If JSON legacybranch is valid, use it
safe_branch = legacy_major
logging.warning(
"580+ auto-fallback: %s using original JSON branch %s (%s)",
self.name, safe_branch, original_message
)
else:
# JSON legacybranch is invalid, use calculated safe branch
logging.warning(
"580+ auto-fallback: %s using safe branch %s (JSON branch %s invalid - %s)",
self.name, safe_branch, legacy_major, original_message
)
self.legacy_branch = safe_branch + ".00"
self.driver_hint = proprietary_required
return
except ValueError:
pass
# ===== 4. LEGACY BRANCH OPENKERNEL RESTRICTION (NEW LOGIC) =====
# If enabled, all legacy branches up to 580.xx cannot use open kernel modules
if self.legacy_branch and ENABLE_LEGACY_OPENKERNEL_RESTRICTION:
legacy_major = self.legacy_branch.split('.')[0]
try:
legacy_major_int = int(legacy_major)
# Legacy branches 71.86, 96.43, 173.14, 304, 340, 390, 470, 580
# All legacy branches up to 580 cannot use open kernel
if legacy_major_int <= 580:
self.driver_hint = proprietary_required
logging.debug(
"Legacy branch restriction: %s with legacy branch %s forced to proprietary",
self.name, self.legacy_branch
)
return
except ValueError:
pass
# ===== 5. ARCHITECTURE-BASED CHECK (only if enabled) =====
if ENABLE_ARCHITECTURE_CHECK:
if self.architecture in OPEN_CAPABLE_ARCHS:
if open_supported in flags:
self.driver_hint = default
else:
self.driver_hint = proprietary_required
else:
self.driver_hint = proprietary_required
return
# ===== 6. NORMAL LOGIC (JSON-based feature flags) =====
if not flags or open_supported not in flags:
self.driver_hint = proprietary_required
elif proprietary_supported in flags:
self.driver_hint = proprietary_supported
else:
if open_supported in flags:
self.driver_hint = default
else:
self.driver_hint = ""
logging.warning("device %s support level not flagged as %s" % (self.id, open_supported))
if not self.driver_hint:
if self.legacy_branch and self.legacy_branch.split(".")[0] <= "470":
self.driver_hint = proprietary_required
def _determine_architecture(self):
"""Determine GPU architecture from device name
This method analyzes the GPU name string to identify the architecture
(e.g., Turing, Pascal, Maxwell, etc.) based on known naming patterns.
"""
self.architecture = self._get_architecture_from_device_name(self.name)
logging.debug("Device architecture determined: %s -> %s" % (self.name, self.architecture))
def _get_architecture_from_device_name(self, device_name):
"""Extract architecture from GPU device name
Args:
device_name: GPU model name string
Returns:
str: Architecture identifier (e.g., "turing", "pascal", etc.)
"""
if not device_name:
return "unknown"
name_upper = device_name.upper()
# Architecture patterns in descending order of modernity
arch_patterns = {
"blackwell": ["BLACKWELL", "GB", "RTX 50", "5090", "5080", "5070", "5060", "5050"],
"ada": ["ADA", "AD", "RTX 40", "4090", "4080", "4070", "4060", "4050"],
"ampere": ["AMPERE", "GA", "RTX 30", "3090", "3080", "3070", "3060", "3050"],
"turing": ["TURING", "TU", "RTX 20", "GTX 16", "2080", "2070", "2060", "1660", "1650"],
"volta": ["VOLTA", "GV", "TITAN V"],
"pascal": ["PASCAL", "GP", "GTX 10", "1080", "1070", "1060", "1050", "P100", "P40", "P4"],
"maxwell": ["MAXWELL", "GM", "GTX 9", "GTX 7", "980", "970", "960", "750", "950", "M40", "M60", "M6", "M4"],
"kepler": ["KEPLER", "GK", "GTX 6", "GTX 7", "680", "670", "660", "650", "K80", "K40", "K20", "K10"],
"fermi": ["FERMI", "GF", "GTX 5", "580", "570", "560", "550", "540", "M2050", "M2070", "M2075"],
"tesla2": ["TESLA", "GT200", "GTX 200", "GTX 280", "GTX 285", "GTX 260", "C2050", "C2075", "M1060"],
"tesla1": ["TESLA", "G80", "G90", "G92", "G94", "G96", "G98", "GTX 8", "GTX 9", "8800", "9800"],
"curie": ["CURIE", "G70", "G71", "G72", "G73", "GeForce 7", "7300", "7600", "7900", "7800", "7950"],
"pre-curie": ["NV", "GeForce 6", "GeForce FX", "GeForce 4", "GeForce 3", "GeForce 2", "6200", "6800", "FX"]
}
for arch, patterns in arch_patterns.items():
for pattern in patterns:
if pattern in name_upper:
return arch
# Fallback logic for common naming patterns
if "RTX" in name_upper:
if "50" in name_upper:
return "blackwell"
elif "40" in name_upper:
return "ada"
elif "30" in name_upper:
return "ampere"
elif "20" in name_upper:
return "turing"
if "GTX" in name_upper or "GEFORCE" in name_upper:
if "16" in name_upper:
return "turing"
elif "10" in name_upper:
return "pascal"
elif "9" in name_upper:
return "maxwell"
elif "7" in name_upper or "6" in name_upper:
# Need to differentiate between Kepler and Maxwell for 700 series
if any(x in name_upper for x in ["750", "745", "730"]):
return "maxwell" # These are Maxwell
elif "7" in name_upper:
return "kepler" # Other 700 series are Kepler
else:
return "kepler" # 600 series are Kepler
elif "5" in name_upper:
return "fermi"
elif "4" in name_upper or "3" in name_upper or "2" in name_upper:
return "pre-curie"
if "QUADRO" in name_upper:
if "RTX" in name_upper:
if "40" in name_upper or "A" in name_upper:
return "ada"
elif "30" in name_upper:
return "ampere"
elif "20" in name_upper:
return "turing"
elif any(x in name_upper for x in ["P", "GP100", "GP102"]):
return "pascal"
elif any(x in name_upper for x in ["M", "GM200", "GM204"]):
return "maxwell"
elif any(x in name_upper for x in ["K", "GK"]):
return "kepler"
elif any(x in name_upper for x in ["5000", "6000"]):
return "fermi"
return "unknown"
def get_distro(path=None):
"""Get the Linux distribution from /etc/os-release
Args:
path: Optional path to os-release file (for testing)
Returns:
SystemInfo: Object containing distribution information
"""
release_file = "/etc/os-release" if not path else path
distro_id = None
version_id = ""
pretty_name = ""
if not os.path.exists(release_file):
logging.error("OS release file not found: %s" % release_file)
return None
try:
with open(release_file, "r") as f:
for line in f:
line = line.strip()
if line.startswith('ID='):
distro_id = line.split('=', 1)[1].strip().strip('"')
elif line.startswith('VERSION_ID='):
version_id = line.split('=', 1)[1].strip().strip('"')
elif line.startswith('PRETTY_NAME='):
pretty_name = line.split('=', 1)[1].strip().strip('"')
except Exception as e:
logging.error("failed to detect Linux distribution: cannot read %s: %s" % (release_file, e))
return None
if not distro_id:
logging.error("failed to detect Linux distribution: cannot extract valid values from %s" % release_file)
return None
if distro_id == "arch" and "manjaro" in pretty_name.lower():
distro_id = "manjaro"
system_info = SystemInfo(distro_id, version_id, pretty_name)
if system_info.id in supported_distros:
logging.debug(
"get_distro(): detected %s%s %s distribution is supported"
% (
system_info.original_id,
" (%s)" % system_info.id if system_info.id != system_info.original_id else "",
system_info.version_id,
)
)
print(
"Detected system:\n %s %s\n"
% (
(
system_info.pretty_name.replace(system_info.version_id, "").strip()
if system_info.pretty_name
else system_info.id
),
system_info.version_id,
)
)
else:
logging.debug(
"get_distro(): detected %s %s distribution is not supported"
% (system_info.id, system_info.version_id)
)
logging.error(
"Error: detected %s%s %s distribution is not supported"
% (
system_info.original_id,
" (%s)" % system_info.id if system_info.id != self.original_id else "",
system_info.version_id,
)
)
return None
return system_info
def override_distro(distro_override):
"""Process the --distro argument and return a SystemInfo object (for testing)
Args:
distro_override: Distribution string in "DISTRO:VERSION" or "DISTRO" format
Returns:
SystemInfo: Simulated distribution information
"""
if ":" in distro_override:
distro_id = distro_override.strip().split(":")[0]
version_id = distro_override.strip().split(":")[-1]
else:
distro_id = distro_override.rstrip(string.digits)
version_id = distro_override[len(distro_id):]
return SystemInfo(distro_id, version_id, "")
def get_system_modaliases(sys_path=None):
"""Get a dictionary with modaliases and paths in the system
Args:
sys_path: Optional alternative path to /sys (for testing)
Returns:
dict: Dictionary mapping modalias strings to device paths
"""
modaliases = {}
devices = "/sys/devices" if not sys_path else "%s/devices" % (sys_path)
for path, dirs, files in os.walk(devices):
modalias = None
if "modalias" in files:
try:
with open(os.path.join(path, "modalias")) as file:
modalias = file.read().strip()
except IOError as e:
logging.debug("get_system_modaliases(): failed to read %s/modalias: %s", path, e)
continue
if not modalias:
continue
driver_path = os.path.join(path, "driver")
module_path = os.path.join(driver_path, "module")
if os.path.islink(driver_path) and not os.path.islink(module_path):
continue
modaliases[modalias] = path
return modaliases
def get_pci_device_info(dev_path):
"""Get PCI device information from sysfs path
Args:
dev_path: Path to PCI device in /sys
Returns:
dict: Dictionary with device information including vendor, device, subsystem_vendor, subsystem_device
"""
info = {}
try:
# Read vendor and device IDs
with open(os.path.join(dev_path, "vendor"), "r") as f:
vendor = f.read().strip()
with open(os.path.join(dev_path, "device"), "r") as f:
device = f.read().strip()
# Read subsystem vendor and device if available
subsys_vendor_path = os.path.join(dev_path, "subsystem_vendor")
subsys_device_path = os.path.join(dev_path, "subsystem_device")
if os.path.exists(subsys_vendor_path):
with open(subsys_vendor_path, "r") as f:
subsys_vendor = f.read().strip()
info["subsystem_vendor"] = subsys_vendor
if os.path.exists(subsys_device_path):
with open(subsys_device_path, "r") as f:
subsys_device = f.read().strip()
info["subsystem_device"] = subsys_device
info["vendor"] = vendor
info["device"] = device
# Try to get device name from uevent
uevent_path = os.path.join(dev_path, "uevent")
if os.path.exists(uevent_path):
with open(uevent_path, "r") as f:
for line in f:
if line.startswith("PCI_ID="):
info["pci_id"] = line.strip().split("=")[1]
elif line.startswith("PCI_SUBSYS_ID="):
info["pci_subsys_id"] = line.strip().split("=")[1]
except Exception as e:
logging.debug(f"get_pci_device_info(): Failed to read device info from {dev_path}: {e}")
return info
def select_best_gpu_match(matching_gpus, pci_info=None, suppress_warnings=False):
"""Select the best GPU match from multiple possibilities
Selection logic (in order of priority):
1. Match by subsystem vendor and device ID (most specific)
2. Match by subsystem vendor only
3. If simulating, try to match by expected name
4. Match laptop GPU with laptop system, desktop GPU with desktop system
5. Has legacybranch field (more specific)
6. Has more features (more detailed information)
7. Name contains fewer "unknown" or generic terms
8. Original order (fallback)
Args:
matching_gpus: List of GPU dicts from JSON
pci_info: Dictionary with PCI device information (vendor, device, subsystem_vendor, subsystem_device)
suppress_warnings: Whether to suppress multiple match warnings (for MHWD/JSON output)
Returns:
dict: Selected GPU entry
"""
if len(matching_gpus) == 1:
return matching_gpus[0]
logging.debug(f"select_best_gpu_match(): Found {len(matching_gpus)} matching GPUs")
# Store the list of matching GPUs for warning message
all_matching_names = [gpu["name"] for gpu in matching_gpus]
# Convert PCI subsystem IDs to hex strings for comparison
if pci_info and 'subsystem_vendor' in pci_info and 'subsystem_device' in pci_info:
# Already in hex format from modalias parsing
subsys_vendor_hex = pci_info.get('subsystem_vendor')
subsys_device_hex = pci_info.get('subsystem_device')
logging.debug(f"select_best_gpu_match(): PCI subsystem: vendor={subsys_vendor_hex}, device={subsys_device_hex}")
# 1. Try to match by exact subsystem vendor and device
if pci_info and 'subsystem_vendor' in pci_info and 'subsystem_device' in pci_info:
for gpu in matching_gpus:
gpu_subsys_vendor = gpu.get("subvendorid")
gpu_subsys_device = gpu.get("subdevid")
if gpu_subsys_vendor and gpu_subsys_device:
# Normalize the hex strings (remove 0x prefix and compare)
gpu_vendor_norm = gpu_subsys_vendor.lower().replace("0x", "")
gpu_device_norm = gpu_subsys_device.lower().replace("0x", "")
pci_vendor_norm = subsys_vendor_hex.lower().replace("0x", "")
pci_device_norm = subsys_device_hex.lower().replace("0x", "")
if gpu_vendor_norm == pci_vendor_norm and gpu_device_norm == pci_device_norm:
logging.debug(f"select_best_gpu_match(): Exact subsystem match: {gpu['name']}")
selected_gpu = gpu
# Show warning if multiple matches and not suppressing warnings
if len(matching_gpus) > 1 and not suppress_warnings:
show_multiple_match_warning(pci_info.get('device'), selected_gpu["name"], all_matching_names)
return selected_gpu
# 2. Try to match by subsystem vendor only
if pci_info and 'subsystem_vendor' in pci_info:
for gpu in matching_gpus:
gpu_subsys_vendor = gpu.get("subvendorid")
if gpu_subsys_vendor:
gpu_vendor_norm = gpu_subsys_vendor.lower().replace("0x", "")
pci_vendor_norm = subsys_vendor_hex.lower().replace("0x", "")